#!/bin/sh
# Get diffs for all given parameters, append them to a diff-file
# and view it in a nice way...here we go

BIGDIFF="/tmp/last-commit-diff.sh.diff"
rm -f "$BIGDIFF"

svn_diff()
{
  prev=$1
  cur=$2
  thing="$3"
  echo "=> cur=r$cur, prev=r$prev"
  if [ -z "$prev" -o -z "$cur" ]; then
    echo "!! couldn't determine both cur and prev versions, aborting."
    exit 1
  fi
  svn diff -r $prev:$cur "$thing" > $BIGDIFF.tmp
  MINPLUS=`grep "^[-+]" $BIGDIFF.tmp | grep -v "^---\|^+++" | cut -b 1 | sort | uniq -c | xargs echo`
  echo "# $MINPLUS" >> $BIGDIFF
  cat $BIGDIFF.tmp >> $BIGDIFF
}

for thing in "$@"; do
  if [ -f "$thing" ]; then
    # its a file, lets cd to its directory first:
    cd `dirname "$thing"`
    thing="`basename "$thing"`"
  elif [ -d "$thing" ]; then
    # this is a dir, cd there first
    cd "$thing"
    thing=.
  fi
  
  echo "=> Checking `pwd`/$thing"
  # CVS or Subversion?
  if [ -d CVS ]; then
    cur=`cvs log $thing | grep ^head | cut -f 2 -d '.'`
    prev=$(($cur - 1))
    echo "=> cur = r$cur, prev = r$prev"
    cvs diff -u -r "1.$prev" -r "1.$cur" $thing > $BIGDIFF.tmp
    MINPLUS=`grep "^[-+]" $BIGDIFF.tmp | grep -v "^---\|^+++" | cut -b 1 | sort | uniq -c | xargs echo`
    echo "# $MINPLUS" >> $BIGDIFF
    cat $BIGDIFF.tmp >> $BIGDIFF
  elif [ -d .svn ]; then
    if [ "$thing" = "." ]; then
      # Ugly hack to enable semi-useful output when requesting
      # the latest diff of a directory
      grep committed-rev .svn/entries | cut -d\" -f 2 | sort | uniq | tail -2 | xargs echo | \
        {
          read prev cur
          svn_diff $prev $cur ""
        }
    else
      svn log "$thing" | grep -A 1 "^--*-$" | grep ^r[0-9] | \
        head -2 | sed 's/^r\([0-9]*\) | .*/\1/g' | xargs echo | \
        { 
          read cur prev
          svn_diff $prev $cur "$thing"
        }
    fi
  else
    echo "!! No information found on `pwd`/$thing"
  fi
done

if [ -s "$BIGDIFF" ]; then
  # View it!
  echo '# vim:ft=diff' \
    >> $BIGDIFF
  vim -c 'se ts=2' \
      -c 'se ft=diff ro nomod ic' \
      -c 'nmap q :q!<CR>' -R $BIGDIFF
fi

# Vim syntax highlighting screws up otherwise:
# vim:ft=sh
