#!/bin/csh -f

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

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
    if ($bounce3 || $bounce || $bounce2 ) then
      echo "not for ZEUS.. HELP"
      body.awk $maild/$x | \
         mail -s "Zeus needs help: Bounce? $bounce $bounce2 Unknown? $bounce3" $gm
      refile $x +help >& /dev/null
    else
      # Appears to be for a supported game
      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
