#!/bin/sh
# call randomsleep.sh beforehand to avoid overloading the server,
# but do not call it from this script itself to avoid editing this script while it is running.
ORIGINAL=`mktemp`
# coral CDN cannot be used because it defaults to a 12 hour expiry

#was 'http://www.weather.gov/data/BOX/ZFPBOX' until July 2012
#http://www.srh.noaa.gov/data/BOX/ZFPBOX stopped working on Sept 2 2014
link='https://tgftp.nws.noaa.gov/data/forecasts/zone/ma/maz014.txt'
scriptdir=/afs/sipb.mit.edu/user/kenta/zweather

# curl -L -o "$ORIGINAL" -s --compressed -m 300 --retry-max-time 1000 --retry 10 "$link"
# curl stopped working, see [curl] note on metar.sh
wget -O "$ORIGINAL" -q --timeout=300 --tries=10 "$link"

PROCESSED=`mktemp`
# no longer all caps
perl -nlwe 'if(/MAZ014/){$going=1}if(/^\$/){$going=0}print if $going' "$ORIGINAL" > "$PROCESSED"

if [ -s "$PROCESSED" ] && perl $scriptdir/sanity-check.pl "$PROCESSED"
then zwrite -c message -q -n -d -l -O AUTO -s $0 -i weather < "$PROCESSED"
    zwrite -c weather -q -n -d -l -O AUTO -s $0 -i MAz014 < "$PROCESSED"
    itemtitle=$(perl $scriptdir/finddate.pl "$PROCESSED")
    perl $scriptdir/genrss.pl "Weather forecast, Cambridge, MA" $0 "zfpbox MAz014" "$itemtitle" $link < "$PROCESSED" > /mit/kenta/Public/weather/maz014.rss
else echo FAILED $0
fi
if [ -s "$ORIGINAL" ]
then cp "$ORIGINAL" /mit/kenta/Public/weather/zfpbox
fi
rm "$PROCESSED" "$ORIGINAL"
