#!/bin/bash

#Usage: firetext.sh [lat min.] [lat max.] [long min.] [long max.] [Post Delay (sec.)] [mobile no. 1]
#
# This script downloads the incident alert XML document from
# emergency.vic.gov.au, checks the location of each incident, and
# if it is within the area specified in latitude and longitude,
# sends relevent information about the incident to the mobile
# phone numbers specified, as SMS messages.
#
#Use "watch" to repeat at a specified interval
#
# Author: The Free Thinker, 2017
#
#TODO:
#-Multiple Phone Numbers
#-Convert coordinates to GDA94 or WGS84

#Mobile Modem Device:
TTYDEV='/dev/ttyUSB2'

#Incidents XML Data URL:
URL='http://data.emergency.vic.gov.au/Show?pageId=getIncidentXML'

#Output to terminal:
messagedisplay ()
{
 echo "---  ---  ---  ---  ---  ---  ---  ---  ---

$origin_date_time_str
$category1 , $incident_type , $category2
$incident_status
$name, $incident_location
Longitude: $LONG
Latitude: $LAT

Status: $origin_status
Size: $incident_size
Resources: $RESOURCES
Incident No. $INCIDENT_NO
Event Code: $event_code

---  ---  ---  ---  ---  ---  ---  ---  ---
"
#Bell [disabled for online version]:
#echo -e "\a"
}

#Output to SMS:
#Manual terminal command:
# picocom -b 9600 -f s -r /dev/ttyUSB2
messageoutput ()
{
#SMS Commands [TODO]
stty -F "$TTYDEV" 9600 raw
#echo "\
chat \
'' AT \
OK\\r \
AT+CMGF=1 \
OK\\r \
AT+CMGS=\""$PHONENO1"\" \
>\\s \
\
"$origin_date_time_str"\\n\
"$category1 , $incident_type , $category2"\\n\
"$incident_status"\\n\
"$name, $incident_location"\\n\
"Longitude: $LONG"\\n\
"Latitude: $LAT"\\n\
\\n\
"Status: $origin_status"\\n\
"Size: $incident_size"\\n\
"Resources: $RESOURCES"\\n\
"Incident No. $INCIDENT_NO"\\n\
"Event Code: $event_code"^z \
OK\\r \
 < "$TTYDEV" > "$TTYDEV"
#" > smschat.temp

#chat -t 15 -f smschat.temp -T "$PHONENO1" < "$TTYDEV" > "$TTYDEV"

}

#Check for incidents not yet processed
newincident ()
{
  local IFS='>'
  if read -d '<' TAG VALUE
  then
#   echo "TAG: $TAG"
#   echo "VALUE: $VALUE"
#The following commands use two regular expressions to extract the
#field with its data, then extract only the data from that string.
#The first, its command nested in the seccond, skips all data
#before the tag name, then ends with the final ".
#The second skips all data that isn't a number until it finds a
#sequence of numbers, beginning with a number, then outputs all
#sequential numbers after that.
#Latter part copied from sed example here:
#https://unix.stackexchange.com/questions/31476/extracting-a-regex-matched-with-sed-without-printing-the-surrounding-character/31479#31479

#Below line works on its own but not in a script for some reason...
#   UPDATETIME="`expr '\`expr "$TAG" : '.*\(last-updated-dt=\"[0-9]*\"\)'\`' : '.*[^0-9]\([0-9][0-9]*\).*'`"

   UPDATETIMETEMP=`expr "$TAG" : '.*\(last-updated-dt=\"[0-9]*\"\)'`
#Variable will be empty if not on an incident tag
   if [ -n '$UPDATETIMETEMP' ]
   then
    UPDATETIME=`expr "$UPDATETIMETEMP" : '.*[^0-9]\([0-9][0-9]*\).*'`
#   echo "UPDATETIME is: $UPDATETIME"
    if (( UPDATETIME > OLDLATESTTIME )) && (( GETINCIDENT == 0 ))
    then
#     LONG="`expr \`expr "$TAG" : '.*\(longitude=\"[.0-9]*\"\)'\` : '.*[^0-9]\([0-9]*[.][0-9]*\).*'`"
     LONG=`expr "$TAG" : '.*\(longitude=\"[.0-9]*\"\)'`
     LONG=`expr "$LONG" : '.*[^0-9]\([0-9]*[.][0-9]*\).*'`
#Remove "-" from latitude regex for northern hemisphere
#     LAT="`expr \`expr "$TAG" : '.*\(latitude=\"-[.0-9]*\"\)'\` : '.*[^0-9]\(-[0-9][.0-9]*\).*'`"
     LAT=`expr "$TAG" : '.*\(latitude=\"-[.0-9]*\"\)'`
     LAT=`expr "$LAT" : '.*[^0-9]\(-[0-9][.0-9]*\).*'`
#     RESOURCES="`expr \`expr "$TAG" : '.*\(resource-count=\"[0-9]*\"\)'\` : '.*[^0-9]\([0-9][0-9]*\).*'`"
     RESOURCES=`expr "$TAG" : '.*\(resource-count=\"[0-9]*\"\)'`
     RESOURCES=`expr "$RESOURCES" : '.*[^0-9]\([0-9][0-9]*\).*'`
#     INCIDENT_NO="`expr \`expr "$TAG" : '.*\(incident-no=\"[0-9]*\"\)'\` : '.*[^0-9]\([0-9][0-9]*\).*'`"
     INCIDENT_NO=`expr "$TAG" : '.*\(incident-no=\"[0-9]*\"\)'`
     INCIDENT_NO=`expr "$INCIDENT_NO" : '.*[^0-9]\([0-9][0-9]*\).*'`
     GETINCIDENT=1

# Track the latest incident read. assume they're not in order:
     LATESTTIME=$LATESTTIME
     if (( LATESTTIME < UPDATETIME ))
     then
      LATESTTIME=$UPDATETIME
     fi
    fi
   fi
  else
   if (( GETINCIDENT == 1 ))
   then
    echo "ERROR: Unexpected End of XML File While Reading Incident Information"
    return 1
   else
#   Save timestamp of latest incident reported:
    echo "$LATESTTIME" > "latesttime"
    return 10
   fi
  fi
 return 0
}


#Read incident info and format it in text
readincident ()
{
 
  case $TAG in

   "origin-date-time-str")
     origin_date_time_str=$VALUE
     ;;

   "incident-status")
     incident_status=$VALUE
     ;;

   "incident-type")
     incident_type=$VALUE
     ;;

   "event-code")
     event_code=$VALUE
     ;;

   "incident-location")
     incident_location=$VALUE
     ;;

   "origin-status")
     origin_status=$VALUE
     ;;

   "incident-size")
     incident_size=$VALUE
     ;;

   "category2")
     category2=$VALUE
     ;;

   "category1")
     category1=$VALUE
     ;;

   "name")
     name=$VALUE
     messagedisplay
#     messageoutput
     GETINCIDENT=0
#     sleep $WAITTIME
     ;;
  esac
return 0
}

#MAIN

#Command-Line Parameters:
LATMIN=$1
LATMAX=$2
LONGMIN=$3
LONGMAX=$4
WAITTIME=$5
PHONENO1=$6

GETINCIDENT=0
# Start latesttime at zero if it doesn't exist:
if [ ! -f latesttime ]
then
 echo "0" > "latesttime"
fi

LATESTTIME=`cat latesttime`
OLDLATESTTIME=$LATESTTIME

#Download the latest Incident XML file:
if ! wget -q -O "incident.xml" $URL
then
 echo -n "ERROR: Download of XML File Failed on: "
 date +"%Y-%m-%d %H:%M:%S"
 exit 1
fi

cat incident.xml | while newincident
do
 if (( GETINCIDENT > 0 ))
 then
  readincident
 fi
done

if (( GETINCIDENT == 0 ))
then
 exit 0
else
 echo "ERROR: Terminating before output of last message."
 exit 1
fi
