#!/bin/csh -f
# multi-forw

set maild = ~zeus/Mail/inbox
set gm = bampton@cs.utk.edu
set gamelist = ~zeus/games
set games = `cat $gamelist`

set path=(/usr/ucb /usr/bin /usr/local/bin /usr/local/gnu /usr/local/mh $HOME/bin)

folder +inbox > /dev/null
cd $maild


foreach x ([1-9] [1-9]? )
  if ( -e $x ) then
    echo -n "Working on $x ... "
    # Bounce-o-gram?
    grep -i "return-path:" $maild/$x | \
       grep -ivs "mailer-daemon@|root@|postmaster@"
    set bounce = $status
    grep "^Subject:" $maild/$x | head -1 | grep -isv "returned" 
    set bounce2 = $status
    grep "^Subject:" $maild/$x | head -1 | fgrep -s -i -f $gamelist
    set bounce3 = $status
    grep -i "From:" $maild/$x |  grep -ivs "mailer-daemon@|root@|postmaster@"
    set bounce4 = $status
    if ($bounce4 || $bounce3 || $bounce || $bounce2 ) then
      echo "not for ZEUS.. HELP"
      # Cut here
      set sub = "Zeus confusion: "
      if ($bounce) set sub = "$sub Return bounce"
      if ($bounce2) set sub = "$sub Returned subject bounce "
      if ($bounce3 && ! ($bounce || $bounce2 || $bounce4)) \
             set sub = "$sub unknown"
      if ($bounce4) set sub = "$sub from root"
      body.awk $maild/$x |  mail -s "$sub" $gm
      #mail -s "Zeus needs help: Bounce? $bounce $bounce2 Unknown? $bounce3" $gm
      refile $x +help >& /dev/null
    else
      # Has supported game in subject line...
      set notmatched
      foreach game ($games)
        if ($?notmatched) then
          grep "^Subject:" $x | grep -i -s -w $game
          if !($status) then
            echo $game
            refile $x +$game
            touch ~/.$game
            unset notmatched
          endif
        endif
      end
      if ($?nomatched) then
        echo "ZEUS can't figure it out. HELP"
        body.awk $maild/$x | mail -s "Zeus is confused" $gm
        refile $x +help >& /dev/null
      endif   # Game name matched
    endif     # Is a supported game
  endif       # order exists
end 

foreach game ($games)
   if ( -e ~/.$game ) then
     if ($game =~ "send") then
       server
     else
       game-forw $game
     endif
     rm ~/.$game
   endif
end
