#!/bin/sh
# Wrapper script around SVN to support using $PAGER and other handy tools.

: ${PAGER=missing}
export PAGER

set_colors()
{
  black='';  lblack=''
  red='';    lred=''
  green='';  lgreen=''
  yellow=''; lyellow=''
  blue='';   lblue=''
  purple=''; lpurple=''
  cyan='';   lcyan=''
  grey='';   lgrey=''
  white='';  lwhite=''
  std=''
}

set_nocolors()
{
  black=;  lblack=
  red=;    lred=
  green=;  lgreen=
  yellow=; lyellow=
  blue=;   lblue=
  purple=; lpurple=
  cyan=;   lcyan=
  grey=;   lgrey=
  white=;  lwhite=
  std=
}

  # ------------------- #
  # `main' starts here. #
  # ------------------- #

if test -t 1; then
  # Define colors if stdout is a tty.
  set_colors
  test "x${PAGER}" = "xmissing" && PAGER=cat
else
  set_nocolors
  PAGER=cat
fi

sed_svn_st_color="
  t dummy_sed_1
  : dummy_sed_1
  s@^?\\(......\\)+@+\\1+@
  s@^?\\(......\\)\\(.*/\\)+@+\\1\\2+@
  s@^?\\(......\\),@,\\1,@
  s@^?\\(......\\)\\(.*/\\),@,\\1\\2,@
  s/^\\(.\\)C/\\1${lred}C${std}/
  t dummy_sed_2
  : dummy_sed_2
  s/^?/${lblue}?${std}/;  t
  s/^M/${lgreen}M${std}/;  t
  s/^A/${lyellow}A${std}/;  t
  s/^X/${lblue}X${std}/;   t
  s/^+/${lyellow}+${std}/; t
  s/^D/${lyellow}D${std}/; t
  s/^,/${lred},${std}/;    t
  s/^C/${lred}C${std}/;    t
  s/^I/${purple}I${std}/;  t
  s/^R/${lyellow}R${std}/;   t
  s/^!/${lred}!${std}/;    t
  s/^~/${lwhite}~${std}/;  t"

svn_log_delim="------------------------------------------------------------------------"
awk_svn_log_ll='
function strip(str) {
  sub(/^[ \t]+/, "", str);
  sub(/[ \t]+$/, "", str);
  return str;
}
/^r[0-9]+ \| [A-Za-z(]+/ {
  in_rev=1;
  FS="|";
  $0=$0 "";
  revnum=strip($1); author=strip($2); date=strip(substr($3, 0, 26));
  FS=" ";
  getline;
  if ($0 == "Changed paths:") {
    while ($0 != "") {
      getline;
    }
  }
  getline;
};
/^.+/ && in_rev {
  msg=strip($0);
  while ($0 != "'${svn_log_delim}'") {
    getline;
  }
  if (msg == "'${svn_log_delim}'") {
    msg = "";
  }
  printf("'${yellow}'%s'${std}' %s '${lblack}'(by %s, %s)'${std}'\n", revnum, msg, author, date);
};'

awk_svn_diff='
{ str=$0;
  if (substr(str,1,1) == "@") { str = sprintf("'${lpurple}'%s'${std}'", str); }
  if (substr(str,1,1) == "-") { str = sprintf("'${lred}'%s'${std}'", str); }
  if (substr(str,1,1) == "+") { str = sprintf("'${lgreen}'%s'${std}'", str); }
  if (substr(str,1,1) == "=") { str = sprintf("'${lblue}'%s'${std}'", str); }
  if (substr(str,1,1) == "I") { str = sprintf("\n'${lblue}'%s'${std}'", str); }
  print str;
};'

case $1 in
  cat)
    exec svn "$@" | $PAGER
    ;;
  diff)
    exec svn "$@" | awk "${awk_svn_diff}" | $PAGER
    ;;
  help)
    exec svn "$@" | $PAGER
    ;;
  list|ls)
    exec svn "$@" | $PAGER
    ;;
  ll)
    shift
    exec svn log --stop-on-copy "$@" | awk "${awk_svn_log_ll}" | $PAGER
    ;;
  log)
    exec svn "$@" | $PAGER
    ;;
  status|stat|st)
    exec svn "$@" | sed "$sed_svn_st_color" | $PAGER
    ;;
  *)
    exec svn "$@"
    ;;
esac

# vim: ts=2 sts=2 shiftwidth=2 expandtab