#!/bin/sh
# Don't use sipb binary in #! line because it doesn't work
# everywhere that this script might be used by AFS.
test "x$BASH" = x && exec /afs/sipb.mit.edu/project/bash/bash $0 ${1+"$@"}

PATH=/usr/local/bin:/usr/bin:/usr/sbin:/usr/lib:$PATH

unset CVSROOT

umask 0

# Script to notify people and their working directories
# about a `cvs commit'.  This should be called from CVSROOT/commitinfo.

committer="`whoami`"
test -z "$committer" && committer="`id -un`"
test -z "$committer" && committer="cvs-loser"

notify=
workdirs=
repository=
files=

while [ $# -gt 0 ]; do
  case $1 in
  -w) shift; workdirs="$workdirs $1"; shift ;;
  -m) shift; test "$committer" = "$1" || notify="$notify $1"; shift ;;
  -d) shift; CVSROOT=$1; shift; export CVSROOT ;;
  -*) echo >&2 "Usage: $0 [-w DIR] [-m ADDR] REPOSITORY FILES..."; exit 1 ;;
  *) set fnord $*; shift; repository=$1; shift; files="$*"; break ;;
  esac
done

test -z "$notify" -a -z "$workdirs" && { cat > /dev/null; exit 0; }

reldir=`echo $repository | sed -n -e 's,^[^/]*/,,' -e '/\//p'`
repository=$CVSROOT/$repository

if [ "$files" ]; then
  (exec 0<&- 1>&- 2>&-
  sleep 180 # Wait for commit to finish and unlock.
  for dir in $workdirs; do
    out="$(cd $dir/$reldir; cvs update -d -Q $files 2>&1)"
    if test -n "$out"; then
      sendmail -odb -t <<EOF
From: $committer
To: `ls -ld $dir/CVS | awk '{ print $3 }'`
Subject: Errors updating $dir

The following errors were produced trying to
update $reldir in $dir from $repository after
my commit of $files.

$out
EOF
    fi
  done
  )&
fi

(
fold -s -w 70 <<EOF
Log from commit: $files

EOF
cat # Log messages on stdin.
) |
if [ -z "$notify" ]; then
  cat >/dev/null
else
  (
  cat <<EOF
From: $committer
To: $notify
Subject: Changes to $repository

EOF
  cat
  ) | sendmail -t
fi
