#!/bin/bash
#

# 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

sed -f /wxtext_conv1.sed ${WXALERT_SPOOLDIR}/${COUNTY}/plist.txt > ${WXALERT_SPOOLDIR}/${COUNTY}/conv_plist.txt

PLIST=${WXALERT_SPOOLDIR}/${COUNTY}/conv_plist.txt
#PLIST=./plist.txt

LINES=`wc -l $PLIST | awk '{print $1}'`

#Starting Count
FILECOUNT=1

for STEPS in `seq 1 $LINES`
do

    CONV_LINE=`sed -n "$STEPS p" $PLIST`
    bea[$STEPS]=`echo $CONV_LINE | awk 'BEGIN { FS = "issued"} ; {print $1}'`

    iss[$STEPS]=`echo $CONV_LINE | awk 'BEGIN { FS = "issued"} ; {print $2}' | awk 'BEGIN {FS = "until" } ; {print $1}'`

    unt[$STEPS]=`echo $CONV_LINE | awk 'BEGIN { FS = "issued" } ; { print $2 }' | awk 'BEGIN { FS = "until" } ; { print $2 }' | awk 'BEGIN {FS = "by" } ; { print $1 }'`

   echo ${bea[$STEPS]} > ${WXALERT_SPOOLDIR}/${COUNTY}/conv_beacon${FILECOUNT}
   FILECOUNT=`expr $FILECOUNT + 1`

   echo "issued ${iss[$STEPS]}" >  ${WXALERT_SPOOLDIR}/${COUNTY}/conv_beacon${FILECOUNT}
   FILECOUNT=`expr $FILECOUNT + 1`

   if [ -n "${unt[$STEPS]}" ] ; then
       echo "until ${unt[$STEPS]}" > ${WXALERT_SPOOLDIR}/${COUNTY}/conv_beacon${FILECOUNT}
       FILECOUNT=`expr $FILECOUNT + 1`
   fi
   echo
#    echo ${bea[$STEPS]}
#    echo "issued ${iss[$STEPS]}"
#    if [ -n "${unt[$STEPS]}" ] ; then
#        echo "until ${unt[$STEPS]}"
#    fi
#    echo

done

echo

