#!/bin/sh
# forward-spool - forward a user's mail spool to another address,
#		  optionally deleting the spool when done
#
# Rob Funk <funk+@osu.edu>

# check for help request
if [ -z "$1" -o "x$1" = "x-h" ]
then
  cat <<EOT
Usage:  forward-spool [-d] fromspoolfile toaddress
          -d    delete original spool file when done
EOT
  exit
fi

# are we going to delete the spool when done?
del=0
if [ "x$1" = "x-d" ]
then
  del=1
  shift
fi

# try to make sure we have valid arguments
if [ ! -f "$1" ]
then
  echo "Error: mail spool \"$1\" does not exist!"
  echo "  (Make sure you specify the entire path to the mail spool)"
  exit 1
elif [ -z "$2" ]
then
  echo "Error: need to specify an address to forward mail to!"
  exit 1
fi

# Find usual mail spool directory
for maildir in \
  `echo ${MAILPATH}:/var/mail:/var/spool/mail:/usr/spool/mail|tr : \ ' \
  "`basename $1`"
do
  if [ -d $maildir ]; then
    break
  fi
done

# Find sendmail
for dir in `echo ${PATH}:/usr/sbin:/usr/lib:/usr/local/sbin|tr : \ `
do
  if [ -x $dir/sendmail ]; then
    sendmail=$dir/sendmail
    break
  fi       
done

# do we have the lockfile program?
for dir in `echo ${PATH}:/usr/bin:/bin:/usr/local/bin|tr : \ `
do
  if [ -x $dir/lockfile ]; then
    lockfile=$dir/lockfile
    break
  fi       
done

lock() {
  # Lock spool if not already locked
  if [ -x "$lockfile" ]; then
    if [ "`dirname $1`" = "$maildir" ]; then
      lockswitch=-ml
    else
      lockswitch="$1"
    fi
    (LOGNAME="`basename $1`"; export LOGNAME; $lockfile $lockswitch)
  else
    # fake it, non-atomic
    if [ -f "$1".lock ]
    then
      echo "Mail spool $1 is locked, cannot open"
      exit 2
    else
      (umask 0333; echo $$ > "$1".lock)
    fi
  fi
}

unlock() {
  # Unlock spool
  if [ -x "$lockfile" ]; then
    if [ "`dirname $1`" = "$maildir" ]; then
      unlockcmd="lockfile -mu"
    else
      unlockcmd="rm -f $1.lock"
    fi
    (LOGNAME="`basename $1`"; export LOGNAME; $unlockcmd)
  else
    rm -f "$1.lock"
  fi
}

# Now lock it
lock "$1"

# count # of messages in spool
msgcount=`grep '^From ' "$1" | wc -l | awk '{print $1}'`
spoolsize=`ls -s "$1" | awk '{print $1}'`

# die if nothing to do
if [ $spoolsize -eq 0 ]
then
  echo "No mail in $1 to forward!"
  unlock "$1"
  exit 0
fi

echo "There are $msgcount messages in this spool,"
echo "  totalling $spoolsize K"

# now we just forward from $1 to $2
echo "Forwarding all mail in $1"
echo "  to $2 . . ."
cat "$1" | formail -ts $sendmail "$2"
if [ $? -ne 0 ]
then
  echo "Error forwarding mail!" 1>2
  unlock "$1"
  exit 1
fi
echo "Done!"

# now delete if requested...
if [ $del -eq 1 ]
then
  echo "Removing $1"
  rm -f "$1"
  echo "$1 has now been removed"
fi

# remove lock
unlock "$1"
exit 0
