#!/bin/sh
# Allow tracking on your CVS modules without the need of server access
# put in cron * * * * *
# Works only properly if your receive one commit a minute.
# Rick van der Zwet <info@rickvanderzwet.nl>
# License BSD: http://rickvanderzwet.nl/LICENSE

CVSPROJECT=wk2010
CVSDIR=/home/rvdzwet/$CVSPROJECT

EMAIL_TO="info@example.org"
EMAIL_CC="foo@example.org,bar@example.org"
EMAIL_FROM="noreply@example.org"

# System internal variables
TMPDIR=`mktemp -d -t $(basename $0 .sh)`
CVSLOG=$TMPDIR/cvs.log
CVSLOG_STDERR=$TMPDIR/cvs.log.stderr
EMAIL_BODY=$TMPDIR/email-body.txt
EMAIL_FULL=$TMPDIR/email-full.msg

UPDATED=""
AUTHOR="unknown"
UPDATED_FILES=""

{
cd $CVSDIR

# Changes in repository
touch $CVSLOG_STDERR
cvs -q up 2>$CVSLOG_STDERR | tee $CVSLOG
UPDATED_FILES=`awk '/^[U|P]/ {print $2}' $CVSLOG` 
echo ""

# Deleted files
if [ -s $CVSLOG_STDERR ]; then
  cat $CVSLOG_STDERR
  echo ""
  UPDATED="yes"
fi

if [ -n "$UPDATED_FILES" ]; then
  # Log message
  UPDATED_FILE=`echo $UPDATED_FILES | awk '{print $1}'`
  cvs log -l -r$REV $UPDATED_FILE | sed -n '/-----/,/========/p'
  echo ""

  # Diff of files
  for FILE in $UPDATED_FILES; do
    UPDATED="yes"
    REV=`cvs log -h $FILE | awk '/^head:/ {print $2}'`
    PREV=`echo $REV | awk -F. '{print $1 "." $2 - 1}'`
    cvs diff -N -u -r $PREV -r $REV $FILE
   
    # Should be the same for all files
    AUTHOR=`cvs log -l -r$REV $FILE | awk '/^date:/ {print $6}' | tr -d ';'`
  done
fi
} > $EMAIL_BODY


# Send email if updated
if [ -n "$UPDATED" ]; then
  {
  echo "To: $EMAIL_TO"
  if [ -n "$EMAIL_CC" ]; then
    echo "Cc: $EMAIL_CC"
  fi
  echo "From: 'CVS Commit - $AUTHOR' <$EMAIL_FROM>"
  echo "Subject: CVS Update $CVSPROJECT `echo $UPDATED_FILES`"
  if [ -n "$EMAIL_CC" ]; then
    echo "Reply-To: $EMAIL_TO,$EMAIL_CC"
  else
    echo "Reply-To: $EMAIL_TO"
  fi
  echo "X-Mailer: cvsmailer - $CVSPROJECT"
  echo 'X-Version: $Id$'
  echo ""

  cat $EMAIL_BODY
  echo ""
  echo "==== ALL DONE generated by `id -un`@`hostname` at `date`  ===="
  } > $EMAIL_FULL
  cat $EMAIL_FULL |  /usr/sbin/sendmail -t
fi

rm -R $TMPDIR
