#!/bin/csh
#
# This script will grab this:
#	http://spc.igpp.ucla.edu/stereo/offset/201803StereoACounts.asc
#		substituting the year and month, of course
# file and compare it to the copy in:
#x	/disks/stereodata/stereo_public/ssw_impact/calibration
# if new versions are detected an email will be sent to Peter
# Schroeder at peters@ssl.berkeley.edu
#
# It will also see if the next month is available, in which case it will start using that one.

echo graboffsets

at -c -f graboffsets.sh noon tomorrow

# keep a log file of which offset data product, if any, has changed
if ( -e offsetstatus ) then
    /bin/rm -f offsetstatus
endif
touch offsetstatus

# see if the current file has changed first
foreach i ( "`cat currentyear``cat currentmonth`StereoACounts.asc" )
    echo Checking $i for changes
    wget -O temp.$$ http://spc.igpp.ucla.edu/stereo/offset/$i
    if ( -z temp.$$ ) then
	echo Failed to fetch $i
	exit -1
    endif
    diff $i temp.$$ >& foo.$$
    if ( ! -z foo.$$ ) then
	date -u >> offsetstatus
	echo -n "Running in directory: " >> offsetstatus
	pwd >> offsetstatus
	echo $i has changed >> offsetstatus
	mv temp.$$ $i
	tail -15l $i | grep '20[0-9][0-9]' >> offsetstatus
	echo ' ' >> offsetstatus
    else
	/bin/rm -f temp.$$
    endif
    /bin/rm -f foo.$$
end

# then see if there is a new monthly offset file
set testnew=`awk -f graboffsets.awk currentyear currentmonth`
echo Will check for $testnew
/bin/rm -f temp.$$ foo.$$
wget -O temp.$$ http://spc.igpp.ucla.edu/stereo/offset/$testnew
if ( ! -z temp.$$ ) then
    date -u >> offsetstatus
    echo -n "Running in directory: " >> offsetstatus
    pwd >> offsetstatus
    echo $testnew is a new file >> offsetstatus
    mv temp.$$ $testnew
    cat $testnew >> offsetstatus
    cp $testnew ..
    if ( `cat currentmonth` == 12 ) then
	echo -n 01 >! currentmonth
	awk -f nextyear.awk currentyear >! temp
	mv temp currentyear
    else
	awk -f nextmonth.awk currentmonth >! temp
	mv temp currentmonth
    endif
endif

/bin/rm -f temp.$$ foo.$$

if ( ! -z offsetstatus ) then
    mailx -s "offset file has changed" peters@ssl.berkeley.edu marchant@ssl.berkeley.edu < offsetstatus
    cat offsetstatus
endif
