#!/bin/sh
#
# get_files --- get and post weather satellite gif's
#
#usage='usage:  nohup wgif [sleep_time[ tries]] &'
#
# run from cron:
# 02 * * * *      bin/wgif 300 10 >>wgif.err 2>&1
echo "Starting..."
if [ "$1" = "" ] ; then
  time=-3600
else
  time=$1
fi

if [ "$2" = "" ] ; then
  tries=-1
else
  tries=$2
fi

wait=3600   # how long to display the gif

echo "" >>wgif.log

echo "Entering loop..."

while true ; do
    hour=`date +%H`

    echo "Getting file list..."

    # get the name of the most recent gif

    echo "user anonymous x" > dircmds.txt
    echo "cd WX" >> dircmds.txt
    echo "dir *.GIF" >> dircmds.txt
    echo "quit" >> dircmds.txt
    echo "!sleep 60" >> dircmds.txt

    # ftp vmd.cso.uiuc.edu 128.174.5.98 
    ftp -n vmd.cso.uiuc.edu < dircmds.txt >/tmp/wgif

    firstline=`head -1 /tmp/wgif`
    if [ "$firstline" = "Not connected." ] ; then
        echo "Connection failed."
        break
    fi

    lastsaname=`grep '^SA.* GIF ' /tmp/wgif | tail -1 | nawk '{print $1 "." $2}'`
    echo "$lastsaname" >sa.time
    echo "last sa name is $lastsaname"

    echo "user anonymous x" > fetchcmds.txt
    echo "cd WX" >> fetchcmds.txt
    echo "verbose" >> fetchcmds.txt
    echo "binary" >> fetchcmds.txt

    if [ "$lastsaname" = "" ] ; then
        echo "No SA GIF files found at `date`" >>wgif.log
    elif cmp -s sa.time sa.lasttime  ; then
        echo "Last SA GIF is '$lastsaname' (same as last) at `date`" >>wgif.log
    else
        cp sa.time sa.lasttime 
        echo "get $lastsaname WXMAP.GIF" >> fetchcmds.txt
    fi    

    echo "quit" >> fetchcmds.txt

    echo "Getting files..."

    # ftp vmd.cso.uiuc.edu 128.174.5.98 
    ftp -n vmd.cso.uiuc.edu < fetchcmds.txt

    break
done #>>wgif.err 2>&1

#=========================================================================

#
# postproc - do local postprocessing on files from UIUC
#

GRAPHICS="/afs/athena.mit.edu/contrib/graphics/decmipsbin/"
KRBTKFILE=/tmp/pips_ticks
export KRBTKFILE

# create new england gif image
echo "Extracting New England Area file..."
rm ne.gif
${GRAPHICS}giftoppm WXMAP.GIF | ${GRAPHICS}pnmcut 536 116 249 161 | ${GRAPHICS}pnmenlarge 2 \
  | ${GRAPHICS}ppmtogif > ne.gif
#
# echo "Copying gif files"
# we assume that we have tokens and valid tickets
cp ne.gif /afs/athena.mit.edu/system/ti_data/images/ne.gif
cp WXMAP.GIF /afs/athena.mit.edu/system/ti_data/images/WXMAP.GIF

#cleanup
rm fetchcmds.txt
rm dircmds.txt
rm sa.lasttime
rm wgif.log
rm sa.time
rm wgif
rm WXMAP.GIF
rm ne.gif

echo "Finished."
#
#================================================================


