#!/bin/bash
############################################################################
############################################################################
###    WARNING - WORK IN PROGRESS  ** SCRIPT INCOMPLETE AS YET **        ###
############################################################################
############################################################################
#
# cyclone-scan  - Bureau of Meteorology information script
#                 for use with 'crontab' (seek & Email)
#
#          Original script by Steve Jones VK8SJ, Katherine NT Aust.
#
# Usage:  entry in crontab >>  cyclone-scan {nt|wa|qld|all}
#
# Requires:   Files:
#               /home/irlp/audio/custom/cyclone_warning_message.wav
#
#             System:
#               MUTT & sendmail or postfix MTA
#
#
#
# Version   Date     Who        Wot..
#  1.0  26/01/12  VK8SJ  Original hack
#  1.0  14/03/12  VK8SJ  Fixed some more errors in email section
#  2.0  14/03/12  VK8SJ  Total rehash as not all systems are numbered, back
#                        to the old drawing board,, again!
#  2.0  20/11/13  VK2YLD Tidy up of code, shift scratch files to RAM Disk
#  3.0  17/02/15  VK2YLD rehash to add 'all' to scan all 3 states at once
#  4.0  31/03/21  VK2YLD Altered user agent string to bypass BoM restriction
#                        as they say 'Screen scraping no longer supported'
#                             '''FAIL!'''
#  5.0  10/12/23  VK2YLD Rewrite to use BoM FTP Service pages.
#  5.1  11/01/24  VK2YLD Add transmitted warning audio message.
#  6.0  16/02/24  VK2YLD rehash of fetch routine and other cosmetics.
#
#
##############################################################################
#
version="6.0 16/02/2024"
#
##############################################################################
#
# get system environment.. Just to make sure..
. /home/irlp/custom/environment
#
#  Script Variables
#
source /home/irlp/custom/cyclone.cfg
if [ -z $Logfile ]; then
  echo " config file not found.. exiting."
  exit 9
fi

#Logfile="/home/irlp/log/cyclone.log"                                    # Hmmm
#send_mail="yes"                                    # Email warnings somewhere?
#send_copy="no"                                      # Courtesy copy somewhere?
#to_address="steve@vk2yld.info"                    # Email address for warnings
#cc_address="mike.alsop@tbpl.com.au"                              # CC: to who?
#cyclone_store="/home/irlp/custom/cyclones"             # Storage pit (History)
#tx_warn="local"                                     # Transmit? (yes|no|local)
#NT_warn_file="$AUDIO/custom/cyclone_NT.wav"                      # Audio to tx
#QLD_warn_file="$AUDIO/custom/cyclone_QLD.wav"                    # Audio to tx
#WA_warn_file="$AUDIO/custom/cyclone_WA.wav"                      # Audio to tx
#
#
#
##### Don't change anything below here (Script may crash!) #####
#
#Workdir="/dev/shm"                              # Work Area (RAMDISK if poss)
Workdir="/home/irlp/local"                             # Work Area (Local HDD)
Rawpage=$Workdir"/page_dump"                                    # Dump of data
Workfile=$Workdir"/page_work"                                      # Scribbler
#
BoM="ftp://ftp.bom.gov.au/anon/gen/fwo"
QLD_filelist="IDQ20065.txt IDQ20066.txt IDQ20067.txt IDQ20018.txt IDQ20068.txt IDQ20069.txt IDQ20023.txt IDQ65001.png IDQ20026.txt IDQ65003.png IDQ20029.txt"
NT_filelist="IDD20300.txt IDD20301.txt IDD20020.txt IDD20021.txt IDD20150.txt IDD65001.png IDD20250.txt IDD65002.png"
WA_filelist="IDW24000.txt IDW24010.txt IDW24020.txt IDW27600.txt IDW27700.txt IDW27800.txt IDW24100.txt IDW60280.png IDW24200.txt IDW60284.png IDW24300.txt IDW60287.png"

info_files="IDQ20065.txt IDQ20066.txt IDD20300.txt IDD20301.txt IDW24000.txt IDW24010.txt"
tech_files="IDQ20018.txt IDQ20068.txt IDD20020.txt IDD20021.txt IDW27600.txt IDW27700.txt"
advice_files="IDQ20023.txt IDQ20026.txt IDD20150.txt IDD20250.txt IDW24100.txt IDW24200.txt"
map_files="IDQ65001.png IDQ65003.png IDD65001.png IDD65002.png IDW60280.png IDW60284.png"

##############################################################################
#
# Command line switches to override TX_warn and email settings
#
if [ $(echo $@ | grep -c '\-local') -eq 1 ]; then tx_warn="local"; fi
if [ $(echo $@ | grep -c '\-tx') -eq 1 ]; then tx_warn="yes"; fi
if [ $(echo $@ | grep -c '\-notx') -eq 1 ]; then tx_warn="no"; fi
if [ $(echo $@ | grep -c '\-nomail') -eq 1 ]; then send_mail="no"; fi
#
##############################################################################
#  Qld..
#  IDQ20065.txt TC Info Bulletin-1
#  IDQ20066.txt TC Info Bulletin-2
#  IDQ20067.txt TC Info Bulletin-3
#
#  IDQ20018.txt TC Technical Bulletin-1
#  IDQ20068.txt TC Technical Bulletin-2
#  IDQ20069.txt TC Technical Bulletin-3
#
#  IDQ20023.txt TC Advice-1  IDQ65001.png  Track Map
#  IDQ20026.txt TC Advice-2  IDQ65003.png  Track Map
#  IDQ20029.txt TC Advice-3  no trackmap!
#
###############################
#  NT..
#  IDD20300.txt TC Info Bulletin-1
#  IDD20301.txt TC Info Bulletin-2
#
#  IDD20020.txt TC Technical Bulletin-1
#  IDD20021.txt TC Technical Bulletin-2
#
#  IDD20150.txt TC Advice-1  IDD65001.png  Track Map
#  IDD20250.txt TC Advice-2  IDD65002.png  Track Map
#
###############################
#  WA..
#  IDW24000.txt TC Info Bulletin-1
#  IDW24010.txt TC Info Bulletin-2
#  IDW24020.txt TC Info Bulletin-3
#
#  IDW27600.txt TC Technical Bulletin-1
#  IDW27700.txt TC Technical Bulletin-2
#  IDW27800.txt TC Technical Bulletin-3
#
#  IDW24100.txt TC Advice-1  IDW60280.png  Track Map
#  IDW24200.txt TC Advice-2  IDW60284.png  Track Map
#  IDW24300.txt TC Advice-3  IDW60287.png  Track Map
#
#
##############################################################################
############################## Functions #####################################
##############################################################################
#
###  Usage ..
#
# Spit out a how-to-use message 'coz the command-line got mashed!
#
usage() {
echo "------------------------------------------------------------------------------------------------"
echo "Usage:  cyclone-scan {nt|wa|qld|all}"
echo
echo " Command line switches :- (Temporary overrides for script settings)"
echo "              -local   - Plays file locally only"
echo "              -notx    - Inhibit transmission of warning"
echo "              -tx      - Force transmission of warning"
echo "              -nomail  - Turn off email alerts for this run"
echo
echo "      ...Bye...."
echo
echo "------------------------------------------------------------------------------------------------"
}

###  Cleanup ..
#
# This function cleans up the mess after running..
#
cleanup() {
  sleep 5
  rm -f $Workdir/IDD*
  rm -f $Workdir/IDW*
  rm -f $Workdir/IDQ*
  rm -f $Workfile
  echo; echo "Domestic Services completed..."; echo
}

###  Logging ..
#
# This function logs Date etc and running script name, then message..
#
writelog() {
#  Message="`date '+%b %d %Y %T'` ${0##*/}: "$@
  Message="`date '+%b %d %Y %T'`: "$@
  if [ ! -f "$Logfile" ]; then
    touch $Logfile   # create new log file
  fi
  echo "Logged:- "$Message
  echo $Message >> $Logfile
}

###  Get files to local store
#
fetch() {
  echo "  DEBUG :-  Fetching files = "$filelist
  cd $Workdir
  for file in $filelist; do
   echo "------------"; echo "file = "$BoM/$file
    curl --connect-timeout 15 -O -u anonymous:$to_address $BoM/$file # 2>/dev/null
  done
  echo "------------"; echo
}

### Read and Process Pages from BOM
#
# NT_filelist="IDD20300.txt IDD20301.txt IDD20020.txt IDD20021.txt IDD20150.txt IDD65001.png IDD20250.txt IDD65002.png"
check_nt() {
  filelist=$NT_filelist
  fetch
  if [ -f IDD20020.txt ]; then   #TC Technical Bulletin-1
     tech_file IDD20020.txt      #process
  fi
  if [ -f IDD20021.txt ]; then   #TC Technical Bulletin-2
     tech_file IDD20021.txt      #process
  fi
  if [ -f IDD20300.txt ]; then   #TC Info Bulletin-1
     info_file IDD20300.txt      #process
  fi
  if [ -f IDD20301.txt ]; then   #TC Info Bulletin-2
     info_file IDD20301.txt      #process
  fi
  if [ -f IDD20150.txt ]; then   #TC Advice-1  IDD65001.png  Track Map
     advice_file IDD20150.txt IDD65001.png  #process + track map
   else
     if [ -f IDD65001.png ]; then         # track map with no advice file
        map_only IDD65001.png                 # save the map!
     fi
  fi
  if [ -f IDD20250.txt ]; then   #TC Advice-2  IDD65002.png  Track Map
     advice_file IDD20250.txt IDD65002.png  #process + track map
   else
     if [ -f IDD65002.png ]; then         # track map with no advice file
        map_only IDD65002.png                 # save the map!
     fi
  fi
}

# WA_filelist="IDW24000.txt IDW24010.txt IDW24020.txt IDW27600.txt IDW27700.txt IDW27800.txt IDW24100.txt IDW60280.png IDW24200.txt IDW60284.png IDW24300.txt IDW60287.png"
check_wa() {
  filelist=$WA_filelist
  fetch
  if [ -f IDW27600.txt ]; then            #TC Technical Bulletin-1
     tech_file IDW27600.txt                   #process
  fi
  if [ -f IDW27700.txt ]; then            #TC Technical Bulletin-2
     tech_file IDW27700.txt                   #process
  fi
  if [ -f IDW24000.txt ]; then            #TC Info Bulletin-1
     info_file IDW24000.txt                   #process
  fi
  if [ -f IDW24010.txt ]; then            #TC Info Bulletin-2
     info_file IDW24010.txt                   #process
  fi
  if [ -f IDW24100.txt ]; then            #TC Advice-1  IDW60281.png  Track Map
     advice_file IDW24100.txt IDW60280.png    #process + track map
   else
     if [ -f IDW60280.png ]; then         # track map with no advice file
        map_only IDW60280.png                 # save the map!
     fi
  fi
  if [ -f IDW24200.txt ]; then            #TC Advice-2  IDW60285.png  Track Map
     advice_file IDW24200.txt IDW60284.png    #process + track map
   else
     if [ -f IDW60284.png ]; then         # track map with no advice file
        map_only IDW60284.png                 # save the map!
     fi
  fi
}

# QLD_filelist="IDQ20065.txt IDQ20066.txt IDQ20067.txt IDQ20018.txt IDQ20068.txt IDQ20069.txt IDQ20023.txt IDQ65001.png IDQ20026.txt IDQ65003.png IDQ20029.txt"
check_qld() {
  filelist=$QLD_filelist
  fetch
  if [ -f IDQ20018.txt ]; then            #TC Technical Bulletin-1
     tech_file IDQ20018.txt                   #process
  fi
  if [ -f IDQ20068.txt ]; then            #TC Technical Bulletin-2
     tech_file IDQ20068.txt                   #process
  fi
  if [ -f IDQ20065.txt ]; then            #TC Info Bulletin-1
     info_file IDQ20065.txt                   #process
  fi
  if [ -f IDQ20066.txt ]; then            #TC Info Bulletin-2
     info_file IDQ20066.txt                   #process
  fi
  if [ -f IDQ20023.txt ]; then            #TC Advice-1  IDQ65001.png  Track Map
     advice_file IDQ20023.txt IDQ65001.png    #process + track map
   else
     if [ -f IDQ65001.png ]; then         # track map with no advice file
        map_only IDQ65001.png                 # save the map!
     fi
  fi
  if [ -f IDQ20026.txt ]; then            #TC Advice-2  IDQ65003.png  Track Map
     advice_file IDQ20026.txt IDQ65003.png    #process + track map
   else
     if [ -f IDQ65003.png ]; then         # track map with no advice file
        map_only IDQ65003.png                 # save the map!
     fi
  fi
}

xmit() {
  echo; echo "DEBUG :-  tx_warn="$tx_warn; echo
  if [ ! -f $LOCAL/enable ] ; then return ; fi
  case $st in
  QLD)   warnfile=$QLD_warn_file ;;
  NT)    warnfile=$NT_warn_file ;;
  WA)    warnfile=$WA_warn_file ;;
  esac
  if [ ! -f $warnfile ]; then
     echo; echo "Warning Audio file not found...  "$warnfile
     writelog "Cyclone-scan: Cyclone warning audio file not found... "$warn_file
     return
  fi
  case $tx_warn in
  local)  if [ ! -f $LOCAL/active ] ; then
            $BIN/play $warnfile >/dev/null 2>&1
            sleep 2
            writelog "Cyclone-scan: $st Cyclone alert played locally"
            echo; echo $st" Cyclone alert played locally..."
          else
            echo "Node active, no audio.."
          fi ;;

  yes)    if [ -f $LOCAL/active ] ; then
              killall -9 ispeaker >&/dev/null 2>&1
              killall -9 ispeaker_PCI >&/dev/null 2>&1
              killall -9 sfswrapper >&/dev/null 2>&1
          fi
          $BIN/coscheck
          $BIN/coscheck
          $BIN/coscheck
          $BIN/coscheck
          $BIN/coscheck
          $BIN/coscheck
          $BIN/coscheck
          $BIN/coscheck
          $BIN/coscheck
          $BIN/coscheck
          $BIN/forcekey
          sleep 2
          $BIN/play $warnfile >/dev/null 2>&1
          sleep 2
          $BIN/forceunkey
          writelog "Cyclone-scan: $st Cyclone alert transmitted"
          echo; echo $st" Cyclone alert transmitted..."
          if [ -f $LOCAL/active ]; then "$SCRIPT"/sfswrapper; fi
          sleep 2 ;;

  *)      writelog "Cyclone-scan: $st Cyclone alert transmit inhibited"
          echo; echo $st" Cyclone alert transmit inhibited..." ;;

  esac
}

tech_file() {
  now=`/bin/date +%d%b%Y`
  tag=`grep -i "name" $1 | awk '{print$NF}'`
  if [ $tag = "Low" ]; then
    tag=`grep -i "identifier" $1 | awk '{print$NF}'`
    tx_warn="no"
  fi
  echo "DEBUG :-  Tech file tag = "$tag
  issue=`grep -i "at:" $1 | head -n1 | awk '{ print $2"_"$3"_"$4 }' | sed "s/\//-/g"`
  Filename=$now"_"$tag"_"$issue
  if [ ! -f $cyclone_store/$Filename"_"$st"_technical.txt" ]; then
    cp $1 $cyclone_store/$Filename"_"$st"_technical.txt"
    writelog "Cyclone Technical Bulletin received "$st"-"$issue" received."
    echo; echo "** Cyclone Technical Bulletin "$st"-"$issue" updated in archive list... **"
  else
    echo; echo "** Cyclone Technical Bulletin "$st"-"$issue" already in lists... **"; echo
  fi

}

info_file() {
  now=`/bin/date +%d%b%Y`
  issue=`grep -i "issued at" $1 | head -n1 | awk '{ print $3 }' | sed "s/:/-/g"`
  Filename=$now"_"$tag"_"$issue
  echo "DEBUG:- "$cyclone_store/$Filename"_"$st"_info.txt"
  if [ ! -f $cyclone_store/$Filename"_"$st"_info.txt" ]; then
    cp $1 $cyclone_store/$Filename"_"$st"_info.txt"
    writelog "Cyclone Information Bulletin received "$st"-"$issue" received."
    echo; echo "** Cyclone Information Bulletin "$st"-"$issue" updated in archive list... **"
  else
    echo; echo "** Cyclone Information Bulletin "$st"-"$issue" already in lists... **"; echo
  fi

}

advice_file() {
  echo "Filenames passed - "$1"  "$2
  if [ ! -f $1 ];then echo "File "$1" Not Found!"; fi
  if [ ! -f $2 ];then echo "File "$2" Not Found!"; fi
  Advice=`grep "ADVICE NUMBER" $1 | awk '{print($5)}'`
  if [ "$Advice" == "NUMBER" ] ; then
     New_advice=`grep "ADVICE NUMBER" $1 | awk '{print($6)}'`
     Variant=`grep "ADVICE NUMBER" $1 | awk '{print($1)}'`
     Advice=$Variant"_"$New_advice
  fi
  if [ -z $Advice ] ; then
    Advice=`grep -i "data at:" $1 | cut -d" " -f3- | sed "s/ /-/g"`
  fi

# tag done in tech file scan##    tag=`grep -i "name" $1 | awk '{print$NF}'`

  if [ -z $tag ]; then        # if no tech file, get tag here from advice file.
    while read line; do
      if [ ! -z "`echo $line | grep Headline:`" ]; then
         read line            # skip to nest line.
         tag=`echo $line | awk '{print$3}'`
         if [ "`echo $line | awk '{print$2}'`" = "Low" ]; then tx_warn="no"; fi
      fi
    done < $1
  fi
  now=`/bin/date +%d%b%Y`
  echo "Date determined to be - "$now
  Filename=$now"_"$tag"_"$Advice
  echo; echo " $st Advice# -> "$Advice", Name-tag -> "$tag", and Filename -> "$Filename
  echo " $st Trackmap -> "$2", Name-tag -> "$tag", and Filename -> "$Filename"_"$st"_trackmap.png"
  echo
#  xmit
  if [ ! -f $cyclone_store/$Filename"_"$st"_advice.txt" ]; then
    cp $1 $cyclone_store/$Filename"_"$st"_advice.txt"
 #    cp $2 $cyclone_store/$Filename"_"$st"_trackmap.png"
    if [ -f $2 ]; then cp $2 $cyclone_store/$Filename"_"$st"_trackmap.png"; else echo $2" - Trackmap file missing!"; fi
    if [ $send_mail == "yes" ]; then
      if [ $send_copy == "yes" ]; then
        if [ -f $cyclone_store/$Filename"_"$st"_trackmap.png" ]; then
          echo " Repeater signing off now...Over & Out..." | mutt -s "$st Cyclone Report $Advice $tag" -i $1 -a $cyclone_store/"$Filename"_"$st"_"trackmap.png" -c $cc_address -- $to_address
        else
          echo " Repeater signing off now...Over & Out..." | mutt -s "$st Cyclone Report $Advice $tag" -i $1 -c $cc_address -- $to_address
        fi
        echo " EMail sent to $to_address & $cc_address"
      else
        if [ -f $cyclone_store/$Filename"_"$st"_trackmap.png" ]; then
          echo " Repeater signing off now...Over & Out..." | mutt -s "$st Cyclone Report $Advice $tag" -i $1 -a $cyclone_store/"$Filename"_"$st"_"trackmap.png" -- $to_address
        else
          echo " Repeater signing off now...Over & Out..." | mutt -s "$st Cyclone Report $Advice $tag" -i $1 -- $to_address
        fi
        echo " EMail sent to $to_address"
      fi
    else
        echo " Email transmission inhibited.."
    fi
    writelog "Cyclone warning advice "$st"-"$Advice" received."
    echo; echo "** Cyclone warning advice "$st"-"$Advice" updated in archive list... **"
  else
    echo; echo "** Cyclone warning advice "$st"-"$Advice" already in lists... **"; echo
  fi
}

map_only() {
  now=`/bin/date +%d%b%Y_%H%M`
  Filename=$now"_"$tag"_Alone"
  echo "DEBUG:- "$cyclone_store/$Filename"_"$st"_trackmap.png"
  if [ ! -f $cyclone_store/$Filename"_"$st"_trackmap.png" ]; then
    cp $1 $cyclone_store/$Filename"_"$st"_trackmap.png"
    echo; echo "** Cyclone Trackmap "$st"-Alone updated in archive list... **"
  fi

}


##############################################################################
##############################################################################
###########################  End Local Functions  ############################
########################  Script Starting Location ###########################
##############################################################################
#
#  Ready to go...
clear

trap cleanup EXIT                             # Make sure all clean before leaving

echo "Beginning..."
echo "Cyclone-scan   Version-$version"
echo

scan=`echo $1 | tr '[:upper:]' '[:lower:]'`   # ensure requested state is lower case
st=`echo $scan | tr '[:lower:]' '[:upper:]'`  # shift state to upper case


case $scan in
nt)   check_nt ;;
wa)   check_wa ;;
qld)  check_qld ;;
all)  st="NT"
      check_nt
      st="WA"
      check_wa
      st="QLD"
      check_qld ;;
*)    usage
      exit 2 ;;
esac
#

exit 0
#
##############################################################################

