#!/bin/ksh
#
#
#

# program: sendrat 
VERSION=1.0
# purpose: Create current pdf shifted rating tables and email a text version of table to specified email addresses.
# usage: sendrat - no command line options currently supported (could be added pretty easily)
# history: 12/04/09  initial coding - WJW
# 
# 
#
#


#set outdir to location where pdf tables are to be sent on the nwis server-those files should then be placed on the
#web for cooperator access and the webdir variable below set to the base URL where the files can be publicly accessed.
#Script is designed for DOI external ftp server display-let the author know if you would like it modified
#for basic web-page display instead - no 20 minute delay, etc...
#Example settings shipped with script are for a system where files placed in /var/ftp/pub/coop_ratings are automatically
#transferred to ftpext.cr.usgs.gov/pub/cr/co/lakewood/wsc/coop_ratings where cooperators can access the ratings. This
#basic structure can be used in most WSCs, but the webdir setting will have to be set up specifically for each WSC.

outdir='/var/ftp/pub/coop_ratings'
webdir='ftp://ftpext.cr.usgs.gov/pub/cr/co/lakewood/wsc/coop_ratings'

#The variables below should be set to the text you want displayed for the user-selectable lists of data users'
#email addresses.  The text should be enclosed by single quotes and care should be taken with special
#characters like $ or ' that can have special meaning to the ksh programming language.  If you have less than
#five lists of data users to send email to, set the unneeded variables like this - list2test='' 
# CHANGE THE FOLLOWING:

list1text='US ARMY COE - example1@army.mil example2@army.mil example3@army.mil'
list2text='samplecooperator@coop.com'
list3text='US BOR personnel interested in station 12345678'
list4text='person that feels important when they get emails'
list5text=''

#The variables below should be set to the actual email addresses that correspond with the descriptions
#entered above.  Emailids should be completely enclosed in single quotes and be space delimited if multiple
#email addresses are entered.  The user of the script will be CC'd automatically. If you have less than
#five lists of data users to send email to, set the unneeded variables like this - emailadd3=''
# CHANGE THE FOLLOWING:

emailadd1='example1@army.mil.tmp example2@army.mil.tmp example3@army.mil.tmp'
emailadd2='samplecooperator@coop.example'
emailadd3='sampleuser1@bor.gov.tmp sampleuser2@bor.gov.tmp'
emailadd4='wscdirector@usgs.gov.tmp'
emailadd5=''

# END USER SETTINGS - NO USER SETTINGS ARE LOCATED BELOW THIS LINE



startpath=$PWD

echo $0 | read invoke

#Create temp directory to run in and cd into it
/usr/ucb/whoami | read user
mkdir /tmp/sendrat_temp_$user
chmod 775 /tmp/sendrat_temp_$user
cd /tmp/sendrat_temp_$user

trap '

   cd $startdir
   rm -f -r /tmp/sendrat_temp_$user  2>/dev/null
   print "Bye"
   exit
  ' INT

trap '

   cd $startdir
   rm -f -r /tmp/sendrat_temp_$user  2>/dev/null
   print "Bye"
   exit
  ' QUIT

trap '

   cd $startdir
   rm -f -r /tmp/sendrat_temp_$user  2>/dev/null
   print "Bye"
   exit
  ' EXIT

trap '

   cd $startdir
   rm -f -r /tmp/sendrat_temp_$user  2>/dev/null
   print "Bye"
   exit
  ' HUP

trap '

   cd $startdir
   rm -f -r /tmp/sendrat_temp_$user  2>/dev/null
   print "Bye"
   exit
  ' TERM

# Source the NWIS environment
. /usr/opt/etc/nwis.profile
. $NWISHOME/util/nwo_set_nwis_env

# Get table names for later sql statements
db_no=01
sitetbl=sitefile`tsql $NWISDB -Gnwis_select "select suffix_tx from master_table where ddl_nm='SITEFILE_##' and db_no='${db_no}'"`
loctbl=loc`tsql $NWISDB -Gnwis_select "select suffix_tx from master_table where ddl_nm='LOC_##' and db_no='${db_no}'"`
ddtbl=dd`tsql $NWISDB -Gnwis_select "select suffix_tx from master_table where ddl_nm='DD_##' and db_no='${db_no}'"`
tstbl=ts_comp_inst`tsql $NWISDB -Gnwis_select "select suffix_tx from master_table where ddl_nm='TS_COMP_INST_##' and db_no='${db_no}'"`
ddtstbl=dd_ts_comp_inst`tsql $NWISDB -Gnwis_select "select suffix_tx from master_table where ddl_nm='DD_TS_COMP_INST_##' and db_no='${db_no}'"`

#Detect current date
date '+ 20%y %m %d %H %M %S' > comparedate.temp
cat comparedate.temp | read currentyear currentmonth currentday currenthr currentmin currentsec


# -------------------------test if user has write access to output directory-if not exit-----
if test -w $outdir
then
print "User has write access in output directory..."
else
print "User does not have write access to the central output directory for updated rating files. Script is"
print "setting the output directory to the current working directory.  Cooperator will not be able to"
print "retrieve a pdf table of the updated rating, but a text email of the rating will still be sent."
print "Contact your system or database administrator to get access to the central output directory at:"
print $outdir
print "Resetting main output directory to $startpath"
outdir=$startpath
fi
if test -d $outdir
then
print "Output directory looks legitimate..."
else
print "Updated rating central output directory appears to be damaged or in error."
print "sendrat is detecting $oudir is not a valid directory."
print "Please contact your system or database administrator for help fixing the problem."
print "Resetting main output directory to $startpath"
outdir=$startpath
exit
fi



# ----------------------------- cordialities ----------------------------------
clear
print "Version $VERSION"
print "###############################################################"
print "#                                                             #"
print "# sendrat - email cooperators updated shifted rating tables.  #"
print "#                                                             #"
print "###############################################################"
print
print "You should not work in ADAPS while running this script. An email"
print "will be sent to user-indicated email addresses that includes a"
print "text version of the the current shifted rating at the station "
print "along with a link to a printable pdf copy of the rating."
echo
print "You will also recieve a copy of that email."
echo
print "An NWISWeb retrieval of the new shifted rating to the ratings"
print "depot will also be triggered by the script."

# ----------------------------- get email addresses ---------------------------
until [ "$emailids" ]
do
 echo
# echo
# print "Note: email walker@usgs.gov to add email addresses to the list below."
 echo
 print "Enter a space separated list of email addresses you want the rating "
 print "emailed to or pick from the prepared options below:"
if [[ -n $list1text ]]
  then
  echo "(1) $list1text"
fi
if [[ -n $list2text ]]
  then
  echo "(2) $list2text"
fi
if [[ -n $list3text ]]
  then
  echo "(3) $list3text"
fi
if [[ -n $list4text ]]
  then
  echo "(4) $list4text"
fi
if [[ -n $list5text ]]
  then
  echo "(5) $list5text"
fi
 print '(q) quit script'
 print "Enter space separated list of email addresses or number from list above:"
 read emailopt
  case $emailopt in
   1 ) emailids="$emailadd1"
      clear
      print
      print "You selected to send email to these users:"
      print "$emailids"
      print "Is that OK? (CR=Y):"
      read eok
       case $eok in
       n | no | N | NO | No | nO | nope | nosireebob )
        clear
        print 
        print
        print "Please reenter addresses or choose option from list."
        sleep 2
        emailids=''
       ;;
       * )
       print
       print "Continuing..."
       print
       ;;
       esac
      ;;
   2 ) emailids="$emailadd2"
      clear
      print
      print "You selected to send email to these users:"
      print "$emailids"
      print "Is that OK? (CR=Y):"
      read eok
       case $eok in
       n | no | N | NO | No | nO | nope | nosireebob )
        clear
        print 
        print
        print "Please reenter addresses or choose option from list."
        sleep 2
        emailids=''
       ;;
       * )
       print
       print "Continuing..."
       print
       ;;
       esac                 
      ;;
   3 ) emailids="$emailadd3" 
      clear
      print
      print "You selected to send email to these users:"
      print "emailids"
      print "Is that OK? (CR=Y):"
      read eok
       case $eok in
       n | no | N | NO | No | nO | nope | nosireebob )
        clear
        print 
        print
        print "Please reenter addresses or choose option from list."
        sleep 2
        emailids=''
       ;;
       * )
       print
       print "Continuing..."
       print
       ;;
       esac          
      ;;
   4 ) emailids="$emailadd4" 
      clear
      print
      print "You selected to send email to these users:"
      print "emailids"
      print "Is that OK? (CR=Y):"
      read eok
       case $eok in
       n | no | N | NO | No | nO | nope | nosireebob )
        clear
        print 
        print
        print "Please reenter addresses or choose option from list."
        sleep 2
        emailids=''
       ;;
       * )
       print
       print "Continuing..."
       print
       ;;
       esac 
      ;;
   5 ) emailids="$emailadd5" 
      clear
      print
      print
      print "You selected to send email to these users:"
      print "emailids"
      print "Is that OK? (CR=Y):"
      read eok
       case $eok in
       n | no | N | NO | No | nO | nope | nosireebob )
        clear
        print 
        print
        print "Please reenter addresses or choose option from list."
        sleep 2
        emailids=''
       ;;
       * )
       print
       print "Continuing..."
       print
       ;;
       esac
      ;;
   q | qu | quit | exit | ex | EXIT | Q | QU | QUIT | EX )
      cd $startdir
      rm -f -r /tmp/sendrat_temp_$user
      print "exiting script..."
      exit
          ;;
   * )
     clear
     print
     print
     print "You input the following addresses to send emails to:"
     print "$emailopt"
     print ""
     print "Are those entries correct? (CR=y) \c"
     read ecorr
      case $ecorr in
       n | N | no | NO | nO | NO | nope | NOPE | nosireebob )
        clear
        print 
        print
        print "Please reenter addresses or choose option from list."
        sleep 2
        emailids=''
        ;;
       * )
        emailids="$emailopt"
        ;;
      esac
   ;;
  esac
done
# ----------------------------- get station -----------------------------------
station=$1
if [ -z "$station" ]; then
 until [ $station ]
 do
  print "\nEnter station number (q=quit): \c"
  read station
  case $station in
   q | qu | quit | ex | Q | QU | QUIT | EX )
      cd $startdir
      rm -f -r /tmp/sendrat_temp_$user
      print "Exiting script"
      exit;;
  *) ;;
  esac

  statest=`tsql $NWISDB -Gnwis_select  "select s.station_nm from sitefile_01 s 
        where s.agency_cd='USGS' and s.site_no='$station'"`

  case $statest in
  '' ) 
    print $station ' does not exist in the site file. Please try again or enter q to quit.'
    print
    station='';;
  *) ;;
  esac
 done
fi

# see if station is in a field office list - if so, create field office directory or verify existing one is OK.
#ls -1 /usr/opt/Auto_Review/Swreview/Controlfiles/Fieldoffices/ > FO.tmp       #look at files in field office list directory
#grep -v readme.txt <FO.tmp> FO.tmp1                                           #strip out readme file from directory
#if test -s FO.tmp1                                                            #if other files exist there then run tests and create/verify field office directorie
#then
#cat FO.tmp1 | while read FOlist
#do
#grep $station /usr/opt/Auto_Review/Swreview/Controlfiles/Fieldoffices/$FOlist | read stationFOtest
#if [ -z "$stationFOtest" ]
#then
#echo
#else
#if test -d $outdirectory/$FOlist
#then
#if test -w $outdirectory/$FOlist
#then
#print "Field office directory looks legitimate"
#outdirectory="$outdirectory/$FOlist"
#else
#print "User does not have write access to the field office directory located at:"
#print $outdirectory/$FOlist
#print "Cannot write files to central output directory. Setting output to $startpath"
#print ""
#outdirectory=$startpath
#fi
#else
#    mkdir $outdirectory/$FOlist
#    chmod 777 $outdirectory/$FOlist
#    if test -d $outdirectory/$FOlist
#    then
#    print "Created field office directory " $outdirectory/$FOlist
#    outdirectory="$outdirectory/$FOlist"
#    else
#    print "Unable to create field office directory: $outdirectory/$FOlist "
#    print "Unable to write output files to central swreview output directory."
#    print "Please contact your database or system administrator for help."
#    print "Resetting output directory to $startpath"
#    outdirectory=$startpath
#    fi
#fi
#fi
#done
#fi
#print $outdirectory

#---------------------------------------get Q dd
until [ $goodq ]
do
  print "\nSelect discharge DD..."
  pick_dd -n$station | read ddq
# check for discharge
qtest=`tsql $NWISDB -Gnwis_select  "select d.parm_cd from sitefile_01 s, loc_01 l, dd_01 d
        where s.agency_cd='USGS' and s.site_no='$station' and
        l.site_id=s.site_id and d.loc_id=l.loc_id and
        d.dd_nu='$ddq'"`



case $qtest in
  00060 | 00061 | 30208 | 50042 | 99060 | 99061 )

  for proc in `tsql $NWISDB -Gnwis_select "select dt.ts_comp_inst_id \
        from ${sitetbl} s, ${loctbl} l, ${ddtbl} d, ${ddtstbl} dt, ${tstbl} t \
        where s.agency_cd='USGS' and s.site_no='${station}' and \
        l.site_id=s.site_id and d.loc_id=l.loc_id and d.dd_nu=${ddq} and \
        dt.dd_id=d.dd_id and t.ts_comp_inst_id=dt.ts_comp_inst_id and \
        t.ts_comp_end_dt > 'now'"`
  do
  process=`tsql $NWISDB -Gnwis_select "select ts_comp_inst_cd \
        from ${tstbl} \
        where ts_comp_inst_id=${proc}`
  done

  case $process in
    STGQ | SLPQ | VELQ )
    goodq='y';;
    * )
    print ''
    print 'Discharge DD does not have a valid processor. Please try again.'
    print ''
    sleep 3 
    clear
    goodq=''
    ;;
    esac
 ;;
 * )
 print ''
 print 'This is not a discharge DD. Please try again.'
 print ''
 sleep 3 
 clear
 goodq=''
 ;;
esac

done


    #-------Send output to water-year named directory under station ID directory if water year period used
#    firstdir=$outdirectory/$station                # must create station directory first-can't create two dirs at once
#    outdir=$outdirectory/$station/$wy 
#    if test -d $outdir
#    then
#    if test -w $outdir
#    then
#    print "Final station output directory OK"
#    else
#    print "User doesn't have write access to directory " $outdir
#    print "Please specify a different output directory at approximately line 118 of the swr_settings"
#    print "file or contact your database or system administrator for help."
#    exit
#    fi
#    else
#    if test -d $firstdir
#    then
#   if test -w $firstdir
#    then
#    mkdir $outdir
#    chmod 777 $outdir
#    if test -d $outdir
#    then
#    print "Created output directory " $outdir
#    else
#    print "Unable to create output directory" $outdir "please contact your database or system"
#    print "administrator for help."
#    exit
#    fi
#    else
#    print "User doesn't have write access to directory " $firstdir
#    print "Please specify a different output directory at approximately line 118 of the swr_settings"
#    print "file or contact your database or system administrator for help."
#    exit
#    fi
#    else
#    mkdir $firstdir
#    chmod 777 $firstdir
#    mkdir $outdir
#    chmod 777 $outdir
#    if test -d $outdir
#    then
#    print "Created output directory " $outdir
#    else
#    print "Unable to create output directory" $outdir "please contact your database or system"
#    print "administrator for help."
#    exit
#    fi
#    fi
#fi

{
print "st"
print "$station"
print "$ddq"
print "ot"
print "1"
print "of"
print "$station.rating.temp.txt"
print "pa"
print "$outdir"
print ""
sleep 1
read  ratopt
print "$ratopt"
print "di"
print "ep"
print "pr"
print ""
print "sh"
print "$currentmonth $currentday $currentyear"
print "$currenthr""$currentmin""$currentsec"
print ""
print "N"
print "di"
print ""
print "ex"
} | nwis rt_edit

if [[ -s $outdir/$station.rating.temp.txt ]]
then

grep "RATING ID:" $outdir/$station.rating.temp.txt | read crap crap1 ratingnum crap2
print " " >$outdir/temp1
print "  Please note that this rating table is provisional and subject to revision." >> $outdir/temp1
print "  " >> $outdir/temp1
print "  A PDF version of the rating table can be obtained from this URL (rating is also included below, directly in this email, but" >>$outdir/temp1
print "   may not display well depending on the email program being used):" >>$outdir/temp1
print "   $webdir/$station.rating.$currentyear-$currentmonth-$currentday.pdf" >>$outdir/temp1
print "  Note: File will be deleted after about 90 days." >>$outdir/temp1
print " ">>$outdir/temp1
print "  Real-time data for station are available here - a link to a spreadsheet compatible version of the shifted rating table is also " >>$outdir/temp1
print "  available from this page:" >>$outdir/temp1
print "   http://waterdata.usgs.gov/nwis/uv/?site_no="$station"&PARAmeter_cd=00065,00060" >>$outdir/temp1
print "  " >>$outdir/temp1
print "  Thank you for your use and support of USGS water data." >>$outdir/temp1
print " " >>$outdir/temp1
print " ___________________________________________________________________________________________________________________________________"  >>$outdir/temp1
print "  " >>$outdir/temp1
sed -e "1s/1  /   /" $outdir/$station.rating.temp.txt > $outdir/temp2
     asa $outdir/temp2 > $outdir/$station.rating.$currentyear-$currentmonth-$currentday.txt
    ascii2pdf -p8 -l $outdir/$station.rating.$currentyear-$currentmonth-$currentday.txt
    sleep 2
    rm -f $outdir/temp2 $outdir/$station.rating.temp.txt
cat $outdir/$station.rating.$currentyear-$currentmonth-$currentday.txt >>$outdir/temp1
mv $outdir/temp1 $outdir/$station.email.$currentyear-$currentmonth-$currentday.txt
print
print "PDF rating table produced in $outdir"
print ""
print "Updating shifted ratings on NWISWeb-this may take a while depending on recent activity..."
/usr/opt/nwisweb/sutil/retrieve_ratings --retrieve --changes --quiet 
print
print "Email will be sent to $emailids in about 20 minutes, once rating has transferred to ftp site..."
print
print "Next two lines show details of the process that will be sending the email, including the time it will be sent:"
at now + 20 minutes <<!
mailx -s "A rating table for station $station has been updated on $currentmonth-$currentday-$currentyear" -c "$user@usgs.gov" -~ "$emailids" < $outdir/$station.email.$currentyear-$currentmonth-$currentday.txt
print "Updated rating email has been sent for station $station"
!
print
print "To cancel the email, type 'at -r jobnumber', where jobnumber is the number"
print " shown after 'job' above"
print "i.e. - if you see: 'job 1262210389.a at Wed Dec 30 14:59:49 2009'"
print " you would enter 'at -r 1262210389.a' to cancel the email"

cd $startpath
rm -f -r /tmp/sendrat_temp_$user $outdir/temp1 2>/dev/null
else

print "Something went wrong.  There is no output in the Adaps rating file to email."
print "Please try again..."
cd $startpath
rm -f -r /tmp/sendrat_temp_$user 2>/dev/null
fi

exit
