#!/bin/sh -e
usage() {
   echo "$0 [-nh] directory"
   echo "	Makes a snapshot diff of the given CVS working tree"
   echo "Options:"
   echo "-h	Help (this message)"
   echo "-n	Don't commit pending changes. The diff will only"
   echo "	include commited changes."
}
do_commit=1
while [ $# -ge 1 ]; do
    case "$1" in
    -n)     # No commit
	    do_commit=
	    ;;
    -h)	    usage
    	    exit 0
	    ;;
    -*)     echo "ERROR! Unknown option $1"
	    usage
	    exit 1
	    ;;
    *)      break;
    esac
    shift
done
dir=`echo $1|sed -e's%/.*%%'`
tag=`cat $dir/CVS/Tag | sed -e 's/^T//'`
basetag=`echo $tag | sed -e 's/-local.*$//'`
root=`cat $dir/CVS/Root`
repository=`cat $dir/CVS/Repository`
version=`echo $tag | sed -e 's/-local.*//' -e 's/_/./g'`
extension=`echo $tag |sed -e 's/.*-local//' -e 's/_/./g'`
date=`date +%Y%m%d`
if [ $do_commit ]; then
    cvs commit $*
fi
module=`echo $repository | sed -e "s!^$root/*!!"`
names="";
for arg; do
  name=`echo $arg | sed -e 's!^[^/]*/*!!'`
  names="$names${names:+ }$module/$name"
done
nr=""
marker="-hno$extension.$date"
if [ -f $dir/include/version.h.henrik ] && grep -- "$marker" $dir/include/version.h.henrik >/dev/null; then
  nr=`grep -- "$marker" $dir/include/version.h.henrik | sed -e "s%.*$marker\(.*\)\"%\1%"`
  if [ -n "$nr" ]; then
     nr=`expr $nr - 1`
  else
     nr="-2"
  fi
fi
marker="$marker$nr"
patch="$version$marker.snapshot"
rm -f $patch
if [ -x .cleanpatch.$module ]; then
	cleanpatch=./.cleanpatch.$module
else
	cleanpatch=cat
fi
cvs rdiff -kk -u -r $basetag -r $tag $names | $cleanpatch >>$patch
if grep '\$Id\$' $patch >/dev/null; then
    echo "WARNING! Patch includes \$Id\$"
    echo "Press enter to continue, or CTRL-C to abort"
    read junk
fi
if [ -f $dir/include/version.h ]; then
  echo "Version tag: $marker"
  cat $dir/include/version.h | sed -e "s%\"\$%$marker\"%" >$dir/include/version.h.henrik
  echo "Index: $dir/include/version.h" >>$patch
  diff -u $dir/include/version.h $dir/include/version.h.henrik >>$patch || true
fi
log=$root/$repository/$tag.changelog
if [ -f $log ]; then
  (
    echo "================================================================="
    echo Snapshot $patch taken
    echo "================================================================="
    echo
    cat $log
  ) > $log.$$
  mv -f $log.$$ $log
  (
    cat $log
    echo "--- END OF LOG ---"
    cat $patch
  ) >$patch.$$
  mv -f $patch.$$ $patch
fi
vi $patch
gzip -9 $patch
ln -f $log $log-lastpatch