#!/bin/sh
#
#  Original script alert2raw -- Version 0.1.2 -- Last modified 18Feb2006
#  for Svxlink.
# 
# (c) 2006 by Tim Miller WB0RXX -- Released under the GNU GPL v2
#
# Modified for IRLP use by Chris Kovacs W0ANM 
# $Id: getWxAlert 20 2008-04-15 15:55:25Z kovacs $
#
# Script file used to parse National Weather Service XML RSS feed of weather
# alerts.  Compares data to warning/emergency/watch/advisory/statement/outage
# list, extracts matching tag, and converts this data into raw audio files for
# use in the TclWeather Svxlink module.  File names match the severity of the
# alert (I.e. WARNING.raw, ADVISORY.raw, etc.)  See the README for more 
# information on using this script.
#
# 

CUSTOM=/scripts/wx

echo $CUSTOM

# Load config file

if [ -f ${CUSTOM}/wx_scripts.conf ] ; then
    source ${CUSTOM}/wx_scripts.conf
else
    echo "Missing ${CUSTOM}/wx_scripts.conf file, aborting..."
    exit 1
fi
# if ZONE  not an argument, then use what is defined in configure file.
if [ "$1" = "" ] ; then
    ZONE_ALERT=$ZONE
else
    ZONE_ALERT=$1
fi

if [ -z $ZONE_ALERT ] ; then                        # If no arguments
    echo "Usage getWxAlert <zone>"
    echo "    where <zone>=State Zone, for example: WIZ002"
    echo "    See http://www.weather.gov/alerts/<state>.php"
    echo "                      where <state>=is the 2 letter abbreviation, for example:"
    echo "                      http://www.weather.gov/alerts/mn.php"
    echo 
    echo "    Or you can edit the wx_scripts.conf file to include the ZONE variable."
    echo
    exit 1
fi

if [ -z $TEXT2SPEECH ] ; then
    echo "TEXT2SPEECH value not defined. Please edit wx_scripts_conf file."
    exit 1
fi

# changed to "no" if debugging is not required.
DEBUG="yes"

PLIST="/scripts/wx/alert_list.txt"     # Product list file and directory
URL="http://www.weather.gov/alerts/wwarssget.php?zone=" # URL to RSS data
DATE=`date +%Y.%m.%d.\%H\%M`

#----------------------------- Main program -----------------------------

if [ ! -d $WXALERT_SPOOLDIR/$ZONE_ALERT ] ; then
    mkdir -p $WXALERT_SPOOLDIR/$ZONE_ALERT
fi

cd $WXALERT_SPOOLDIR/$ZONE_ALERT

$WGET -q $URL$ZONE_ALERT -O - | \
$XML sel -T -t -m "/rss/channel/item" -v description | \
sed "s/<br>/ /g; s/\.\.\./\n/g; s/AM/A M/g; s/PM/P M/g; $DT; $ST" > wx_new.txt

if [ ! -d /tmp/wx/$ZONE_ALERT ] ; then
    mkdir -p /tmp/wx/$ZONE_ALERT
fi

# cp downloaded wx txt to tmp and rename to full_alert.txt
cp wx_new.txt /tmp/wx/$ZONE_ALERT/full_alert.txt

# is this really needed?
rm -f wx.tmp                                # Remove old files

#####################################
# download alert, check if new, if new, build "alert.txt" file 
# if not, cleanup

log "Checking for Wx Alerts for $ZONE_ALERT"
if ! diff -q wx_prev.txt wx_new.txt &> /dev/null; then   # Exit if files are same
    log "New Wx Alerts for $ZONE_ALERT"
    cp wx_new.txt wx_prev.txt                       # If not, copy new to old
    rm -f alert.txt *.raw                      # and remove old alerts

    while read PRODUCT; do                     # Check for alert products
        grep -m 1 "^$PRODUCT" wx_new.txt           # appending the 1st matching
    done < $PLIST >> alert.txt                 # line to alert.txt file

    #################################
    # create alert.txt file for conversion

    # check if file exists and size gt zero
    if [ -s alert.txt ]; then
        #set up header of the alert file
        echo ". . Weather Alert. for Winnebago County." >> tmp.txt

	# continue building alert file
        for TYPE in WARNING EMERGENCY WATCH STATEMENT ADVISORY OUTAGE
            do
            if grep $TYPE alert.txt >> tmp.txt; then      # Extract matching alerts
                echo ".." >> tmp.txt
                log "Get Wx Alert INFO for $ZONE_ALERT: $TYPE"
            fi
        done

        # rename to pre_alert.txt
        mv tmp.txt /tmp/wx/$ZONE_ALERT/pre_alert.txt

        #############################
	# create full alert txt file for conversion
        # insert weather header/trailer to full alert txt
        echo ". . Full Weather Alert Information for Winnebago County." >> tmp.txt
        cat /tmp/wx/$ZONE_ALERT/full_alert.txt >> tmp.txt

        # hack alert! flood statements did not have lf so whole alert was
        # converted into audio.
        fmt -w 100 tmp.txt > /tmp/wx/$ZONE_ALERT/pre_full_conv_alert.txt

        ## above lines replaces this line
        ## cp tmp.txt /tmp/wx/$ZONE_ALERT/pre_full_conv_alert.txt

        #clean up unnecessary temp files
        rm /tmp/wx/$ZONE_ALERT/full_alert.txt

        #############################
        #   Post Conversions
        # You must edit wxtext_conv.sed file to perform the post conversion.


        ##############################
        # alert txt file to conv_alert.txt
        sed -f ${CUSTOM}/wxtext_conv.sed /tmp/wx/$ZONE_ALERT/pre_alert.txt > conv_alert.txt

        ##############################
        # full alert txt file to full_conv_alert.txt
        sed -f ${CUSTOM}/wxtext_conv.sed /tmp/wx/$ZONE_ALERT/pre_full_conv_alert.txt > full_conv_alert.txt

        ##############################
        # create the audio file
        if [ $TEXT2SPEECH = "festival" ] ; then
            $TEXT2WAVE -F 8000 -scale 3.5 -otype ulaw  conv_alert.txt -o ALERT.ul
            $TEXT2WAVE -F 8000 -scale 3.5 -otype ulaw  full_conv_alert.txt -o COMPLETE_ALERT.ul
       else
            $TEXT2WAVE -p audio/encoding=ulaw -m text -f conv_alert.txt -o ALERT.ul
            $TEXT2WAVE -p audio/encoding=ulaw -m text -f full_conv_alert.txt -o COMPLETE_ALERT.ul
       fi

       #clean up
       rm -f tmp.txt



       # if WXALERT_BEACON is set to Yes, then place playWxAlertBg into 
       # background
       if [ $WXALERT_BEACON = "Y" ] ; then
           # first kill any left over process
           killall playWxAlertBg
           # call playWxAlert and place in background
           log "Launching playWxAlertBg..."
           $CUSTOM/playWxAlertBg $ZONE_ALERT  &
       fi
    else
          rm -f *.ul                              # Remove all alerts
          rm -f alert.txt
          # After clean up, add "add no active warnings"
          echo "There are no active watches, warnings or advisories for winnebago county" > full_conv_alert.txt
          if [ $TEXT2SPEECH = "festival" ] ; then
                $TEXT2WAVE -F 8000 -scale 3.5 -otype ulaw  full_conv_alert.txt -o COMPLETE_ALERT.ul
           else
                $TEXT2WAVE -p audio/encoding=ulaw -m text -f full_conv_alert.txt -o COMPLETE_ALERT.ul
            fi


	  ##############################
          # save a history of alerts
          # mv over to saved directory
          # Save alert Information
          if [ "$DEBUG" = "yes" ] ; then
              if [ ! -f alert.txt ] && [ -f /tmp/wx/$ZONE_ALERT/pre_full_conv_alert.txt ] ; then
                 # make sure directory is created
                 if [ !  -d saved/$DATE ] ; then
                     mkdir -p saved/$DATE
                 fi
                 mv /tmp/wx/$ZONE_ALERT/pre_full_conv_alert.txt  saved/$DATE/.
                 mv full_conv_alert.txt  saved/$DATE/.
             fi 
         fi
    fi
fi

exit 0

