#!/bin/bash
#
# $Id: getWxAlert 85 2012-07-21 23:13:23Z  $
#
# Change the method of updating alerts.  Check if summary is different instead
# of the entire url download.  This should help prevent updating alert beacons
# that are unnecessary.
#
# Added a check to see if the download failed, if so abort and log. Also
# changed the wget options for retry=10.
#
# Spool Directory should contain the alert.info, pre/post converted files, 
# no_alert, and alert summary
#
DEBUG="0"                               # debug levels 0 = no debug
                                        # level 1 = save alerts
                                        # level 2 = detailed info


# 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

# Check Arguments...
# has only one argument, county info
if [ "$#" = "1" ] ; then
   COUNTY=$1
   COUNTY_NAME=""
fi

# has two arguments, county info and county name
if [ "$#" = "2" ] ; then
   COUNTY=$1
   COUNTY_NAME=$2
fi

# if no arguments, then use what is defined in configure file.
if [ "$1" = "" ] ; then
   # extract County Information and County  Name
   COUNTY_NAME=`echo $COUNTY | awk 'BEGIN { FS="," } { print $2} '`
   COUNTY=`echo $COUNTY | awk 'BEGIN { FS="," } { print $1} '`
   # if name is empty, then use COUNTY
   if [ "$COUNTY_NAME" = "" ] ; then
       COUNTY_NAME=$COUNTY
   fi
fi

if [ "$COUNTY" = "NOTSET" ] || [ "$COUNTY" = "" ] ; then
    echo "ERROR - The COUNTY variable in ${CUSTOM}/wx_scripts.conf is not set"
    echo "or missing, aborting..."
    exit 1
fi

if [ "$COUNTY" = "help" ] ; then                        # If no arguments
    echo "Usage getWxAlert <county>"
    echo "    where <county>=State County, for example: WIC002"
    echo "    See http://alerts.weather.gov/ for more informaton"
    echo 
    echo "    Or you can edit the wx_scripts.conf file to include the COUNTY variable."
    echo
    exit 1
fi

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

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

####### Functions ######
# Send message to LOGFILE
function debug2 () {
  MESSAGE="${0##*/} DEBUG: $@"
  echo "$MESSAGE"
  if [ -n "$LOGFILE" ]; then
    echo "`date '+%b %d %Y %T %z'` $MESSAGE" >> $LOGFILE
  fi
}

function send_email () {
for EADDR in `echo $EMAIL | sed 's/,/ /g'` ; do

    # summary version
    # $MAIL -s "Weather Alert for $COUNTY_NAME" $EADDR < /tmp/wx/$COUNTY/pre_conv_alert_summary.txt

    # full alert info
    cp /tmp/wx/$COUNTY/pre_alert.txt /tmp/wx/$COUNTY/email_alert.txt
    # append the alert to the header
    cat /tmp/wx/$COUNTY/pre_full_alert_info.txt >> /tmp/wx/$COUNTY/email_alert.txt
    # mail it
    $MAIL -s "Weather Alert for $COUNTY_NAME" $EADDR < /tmp/wx/$COUNTY/email_alert.txt

done
}

# Convert URL to file
#function geturldata () {
#    # supply URL
#    # Alternative method of getting url information:
#   ##/usr/bin/lynx -dump $URL$COUNTY > /tmp/wx/$COUNTY/alert.info
# 
#   $WGET -t 10 -w 10 --cache=off --random-wait -q $URL$COUNTY -O - > /tmp/wx/$COUNTY/alert.info
#                                   # -t 10 retries, -w 10 sec between
#                                   # turn cache off at server
#}

###### End of Functions ######
PLIST="$CUSTOM/wx_alert_product.txt"     # Product list file and directory
# URL="http://www.weather.gov/alerts-beta/wwaatmget.php?x=" # URL to RSS data
URL="http://alerts.weather.gov/cap/wwaatmget.php?x=" # URL to RSS data
DATE=`date +%Y.%m.%d.\%H\%M`
NO_WXALERT_MSG=$LOCAL/no_wxalert_msg

MAILDIR="/tmp/wx/$COUNTY"                 # Mail log file
MAILLOG="$MAILDIR/spotter_mail.log"     # Mail log file
#MAIL=/bin/mail                          # mail binary
MAIL="$CUSTOM/SendMail/SendMail.pl"     # Perl SendMail script

CRIT_TYPES=`cat $CUSTOM/wx_critical_alerts.txt`
NORM_TYPES=`cat $CUSTOM/wx_normal_alerts.txt`

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

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

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

cd $WXALERT_SPOOLDIR/$COUNTY

ALERT_DL=""
CHKCNT=0
# loop until get proper response, if after 5 attempts notify
while [ -z "$ALERT_DL" ] ; do
 
     if [ $CHKCNT -gt 5 ] ; then
         log "ERROR: $URL is not responding for getWxAlert - ${COUNTY}"
         log "        Possible issue with nws.gov server or internet connection"
         ls -l /tmp/wx/$COUNTY/alert.info
         exit 1
     fi
 
     # Alternative method of getting url information:
     ##/usr/bin/lynx -dump $URL$COUNTY > /tmp/wx/$COUNTY/alert.info
 
     $WGET -t 10 -w 10 --cache=off --random-wait -q $URL$COUNTY -O - > /tmp/wx/$COUNTY/alert.info
                                   # -t 10 retries, -w 10 sec between
                                   # turn cache off at server
 
     # place  data in variable to see if contains data
     ALERT_DL="`head -1  /tmp/wx/$COUNTY/alert.info`"
     let CHKCNT=$CHKCNT+1
     # delay before retrying
     sleep 4
done

# process the downloaded information
cat /tmp/wx/$COUNTY/alert.info | \
  grep "title>" |sed '/<title>/,/<\/title/!d' |  \
  sed  's/<title>//' | sed 's/<\/title>//' | \
  egrep -v "Current Watches" > wx_new.txt

# get full summary URL Link
FULL_SUMMARY_URL=`cat /tmp/wx/$COUNTY/alert.info | egrep "<id>|</id>" | sed  's/<id>//' | sed 's/<\/id>//'`

# Extract Alert from url information:
ALERT=`cat /tmp/wx/$COUNTY/alert.info | egrep "<title>|</title>" | sed  's/<title>//' | sed 's/<\/title>//'| sed 's/\(by NWS*\).*/\1/' | sed 's/by NWS//'`

# Extract Summary from url information:
SUMMARY=`cat /tmp/wx/$COUNTY/alert.info | egrep "<summary>|</summary>" | sed  's/<summary>//' | sed 's/<\/summary>//'`

# Debug stuff, print values for $ALERT and SUMMARY
if [ "$DEBUG" = "2" ] ; then
    echo
    debug2 "************START**************************"
    debug2 "NWS_URL=$URL"
    debug2 "FULL_SUMMARY_URL=$FULL_SUMMARY_URL"
    debug2 "CHKCNT=$CHKCNT"
    debug2 "ALERT=$ALERT"
    debug2 "SUMMARY=$SUMMARY"
    debug2 "COUNTY=$COUNTY"
    debug2 "COUNTY_NAME=$COUNTY_NAME"
fi

# Full_alert
echo "$ALERT ... $SUMMARY" > alert_summary.txt

#if the download failed, alert_summary.txt has only " ... ",  then log and exit.
