#! /bin/bash
exec >/dev/null 2>&1

. /etc/mailinforc
readonly QUIETHOURS=" $QUIETHOURS "
readonly QI="$QUIETIF"; unset QUIETIF
readonly MA="$MAILER"; MAILER="n_m"
readonly RM="$RUNMAILER"; unset RUNMAILER
MAILBOXES="n_m"
. ~/.mailinforc || exit 0
QUIETIF="$QI $QUIETIF"
test "$MAILER" = "n_m" && { MAILER="$MA"; RUNMAILER="$RM"; }
test "$MAILBOXES" = "n_m" && MAILBOXES=$MAIL
MAILBOXES=" $(eval echo $MAILBOXES) "
LOMAILBOXES=" $(eval echo $LOMAILBOXES) "
SPAMBOXES=" $(eval echo $SPAMBOXES) "

glf="/tmp/mailinfo.$LOGNAME.lock"

if test "$1" = -r; then
  ps xc|grep $MAILER && tones $MELODY &
  exit 0
elif test "$1" = -s; then
  for i in $MAILBOXES $LOMAILBOXES $SPAMBOXES; do
    test -N $i && mbox=$i && break
  done
  test $mbox || exit 0
  shutup=1
  force=1
  rm -f $glf
else
  mbox=$1
  test "${SPAMBOXES##* $mbox *}" != "${SPAMBOXES}" && exit 0
  test "${LOMAILBOXES##* $mbox *}" != "${LOMAILBOXES}" && lo=1
  test $NOPOPUP && norun=1
fi

lf=$glf${lo:+.lo}
lockfile -r 0 $lf || exit 0
test "$lo" -a -f $glf && rm -f $lf && exit 0
{ sleep 10; rm -f $lf; } &
ison=`who|awk '$1=="'$LOGNAME'" {print $2}'`
if test "$ison"; then
  for i in $ison; do
    if test "${i#tty}" != "$i"; then 
      oncon=1
    elif test "${i#@}" != "$i"; then
      oncon=1; onx=$i
    else
      onpty="$onpty $i"
    fi
  done
  test "$QUIETHOURS" != "${QUIETHOURS##*`date +%k`*}" && shutup=1
  if test "$oncon"; then
    test "$QUIETIF" && pidof $QUIETIF && quiet=1
    test -z "$force" -a -n "$NORUNIF" && ps xc|egrep " (${NORUNIF// /|})\$" && norun=1
    if test "$lo"; then
      test $quiet$shutup || tones ${LOMELODY:-$MELODY} &
    else
      killall tones
      test $shutup || tones $MELODY &
      if test "$onx" -a "$MAILER" -a -z "$norun"; then
	ps xc|grep $MAILER ||
	  ( . ~/.bashrc; DISPLAY=${onx#@}:0 ${RUNMAILER:-$MAILER} & )
      fi
    fi
  elif test "$onpty"; then
    for i in $onpty; do
      test $shutup || echo -ne "\a" >/dev/$i
      echo "*** New mail arrived in $mbox ***" >/dev/$i
      break	# only one terminal - it's annoying enough
    done
  fi
fi
exit 0
