#!/bin/ksh

set -x

#------------------------------------------------------------------
# Automated retrieval of NESDIS fire file and HYSPLIT submit
#------------------------------------------------------------------
# Revised: 10 Jul 2002 (RRD) - Initial version: Roland Draxler 
#          15 Aug 2002 (RRD) - only resubmit 10 times
#          23 Aug 2002 (RRD) - multiple file access
#          05 Feb 2003 (RRD) - single conus simulation
#          17 Mar 2003 (RRD) - fire location with no points
#          28 Apr 2003 (RRD) - conversion for frost/snow
#          10 Mar 2004 (RRD) - options for prelim or final fires
#          06 May 2004 (RRD) - capture prelim first then final  
#          26 Aug 2004 (RRD) - changed name of fire server
#          02 Sep 2004 (RRD) - simplified procedures
#          19 Nov 2004 (RRD) - additonal mail notification options
#          02 Dec 2004 (RRD) - date corrections
#          21 Dec 2004 (RRD) - missing fire file use old data
#          24 Jan 2005 (RRD) - added SAB email notification
#          14 Mar 2005 (RRD) - modified submit if no fires file
#          04 Sep 2007 (DMM) - modified from gp16 to gp12
#          06 Jun 2008 (GSM) - changed ftp server
#------------------------------------------------------------------
#Overview
#The dispersion model is preconfigured to run from selected regions using 
#a daily NAM meteorological forecast. Hourly average output maps of soot air
#concentration are produced. The fire locations for each day are tabulated
#and two dispersion simulations are produced.  A 24 h analysis simulation
#is run for the previous day using that day's fire locations.  The smoke
#particle positions at the end of the day are used to intitialze the 48 h
#dispersion forecast simulation.  The next day, the same initialization file
#is used to start the analysis simulation, prior to running the forecast.
# run submission date should be after meteorology is available    

  RUNDATE=${PDY}

  echo " rundate= ",$RUNDATE

# fire points date is valid for the previous day
  FIREDATE=${PDYm1}
  echo " firedate= ",$FIREDATE

# working directory for model results
# OLD variable removed and placed with COMINm1
#
# message log file
#  log=$COMOUT/"log.fire"
  echo "**Starting fire pm25 smoke simulation: `date`"


#------------------------------------------------------------------
# FINAL FILE FIRST ...
# Construct NESDIS file name from current local date.
# FTP the data file if not already in the local directory.
# Note NESDIS computer times are GMT!
#------------------------------------------------------------------

FILE="hmshysplit${FIREDATE}.txt"


#ping -c3 gp16.ssd.nesdis.noaa.gov
#pingerr=$?

#if [ $pingerr -eq 0 ] ; then
    ftp -nv satepsdist1e.nesdis.noaa.gov <<EOD
    user anonymous geoffrey.manikin@noaa.gov
    cd FIRE/HMS
    pwd
    ascii
    prompt
    get ${FILE}
    bye
EOD
#else
#    echo "**NESDIS HMS server unreachable"
#fi

#------------------------------------------------------------------
# PRELIM FILE NEXT ...
# Construct NESDIS file name from current local date.
# FTP the data file if not already in the local directory.
# Note NESDIS computer times are GMT!
#------------------------------------------------------------------

if [ ! -f ${FILE} ];then

   FILE="hmshysplit${FIREDATE}.prelim.txt"

#   ping -c3 gp16.ssd.nesdis.noaa.gov
#   pingerr=$?

#   if [ $pingerr -eq 0 ] ; then
     ftp -nv satepsdist1e.nesdis.noaa.gov <<EOD
     user anonymous geoffrey.manikin@noaa.gov
     cd FIRE/HMS
     pwd
     ascii
     prompt
     get ${FILE}
     bye
EOD
#   else
#     echo "**NESDIS HMS server unreachable"
#   fi

fi

#------------------------------------------------------------------
# if there is no current fire location file, was there a valid
# run yesterday as shown by FIRES.ARC       
#------------------------------------------------------------------

if [ ! -f ${FILE} ];then
   if [ -f ${OLD}/FIRES.NEW ];then
#     set dummy file name to one that exists to submit std job
      FILE="${OLD}/FIRES.NEW"
      echo "** Wildfire locations today are from yesterday"
   else
      echo "** No wildfire locations today or yesterday"
      err_exit "** No wildfire locations today or yesterday"
   fi 

#------------------------------------------------------------------
# check file sizes to determine Email notification:
# 17 bytes = header record only, no fire locations
# 34 bytes = header record plus one data record
#------------------------------------------------------------------

else
   let flen=0
   echo "`wc -c ${FILE}`" | read flen tmp

   if [ $flen -gt 10 ];then
      echo "**${FILE} found and is of length: ${flen}"
#GSM not sure if we need the mail commands here in this section
      if [ $flen -gt 30 ];then
         echo "** Wildfire locations today"
         cp ${FILE} FIRES.TXT
      else
         echo "** HMShysplit file <=30 bytes!"
         echo "~s HMShysplit file <=30 bytes! \n No fires" | mail SABSupervisor@noaa.gov
         exit
      fi
   else
      echo "** HMShysplit file <=10 bytes!"
      echo "~s HMShysplit file <=10 bytes! \n Empty file" | mail SABSupervisor@noaa.gov
   fi
fi



#------------------------------------------------------------------
# Submit standard simulation if fires available or submit test
#------------------------------------------------------------------

if [ -f ${FILE} ];then
## next step submitted here when doing serial processing
## ${USHsmoke}/smoke_hysplit.sh ${PDY} ${PDYm1}
#-------------------------------------------------------------------------

# Step 2
    ${USHsmoke}/smoke_config.sh
    err=$?

    if [ "$err" != '0' ]
    then
      echo ' '
      echo '********************************'
      echo '*** FATAL ERROR IN smoke_config.sh ***'
      echo '********************************'
      echo ' '
      postmsg "ERROR IN smoke_config.sh"
      err_chk
    else
      echo "Smoke_config.sh Completed Normally."
    fi

#  Step 3
    export pgm=hysplit_hymodelm
    . prep_step
    msg="Starting Hysplit_hymodelm run" 
    startmsg
    $EXEChysplt/hysplit_hymodelm >> $pgmout 2>errfile
    export err=$?;err_chk
#
# Run with smoke_national 
#
    ${USHsmoke}/smoke_national.sh
    err=$?

    if [ "$err" != '0' ]
    then
      echo ' '
      echo '********************************'
      echo '*** FATAL ERROR IN smoke_national.sh ***'
      echo '********************************'
      echo ' '
      postmsg "ERROR IN smoke_national.sh"
#      err_chk
    else
      echo "Smoke_national.sh Completed Normally."
    fi
#
# Run with smoke_regional
#BSM    ${USHsmoke}/smoke_regional.sh
#BSM    err=$?

#BSM    if [ "$err" != '0' ]
#BSM    then
#BSM      echo ' '
#BSM      echo '********************************'
#BSM      echo '*** FATAL ERROR IN smoke_regional.sh ***'
#BSM      echo '********************************'
#BSM      echo ' '
#BSM      postmsg "ERROR IN smoke_regional.sh"
#      err_chk
#BSM    else
#BSM      echo "Smoke_regional.sh Completed Normally"
#BSM    fi 
#
# Generate Grib and Ascii files.
    ${USHsmoke}/smoke_grib.sh ${RUNDATE}
    err=$?

    if [ "$err" != '0' ]
    then
      echo ' '
      echo '********************************'
      echo '*** FATAL ERROR IN smoke_grib.sh ***'
      echo '********************************'
      echo ' '
      postmsg "ERROR IN smoke_grib.sh"
      err_chk
      exit
    else
      echo "Smoke_grib.sh Completed Normally."
    fi
#
    cp ${DATA}/FIRES.NEW ${COMOUT}/.
    cp ${DATA}/PARDUMP* ${COMOUT}/.
    cp ${DATA}/bin* ${COMOUT}/.
    cp ${DATA}/grib* ${COMOUT}/.
    cp ${DATA}/noaasmk* ${COMOUT}/.
    cp ${DATA}/files_gif.tar ${COMOUT}/.
    cp ${DATA}/files_gis.tar ${COMOUT}/.
    cp ${DATA}/icon84.gif ${COMOUT}/.
    cp ${DATA}/MESSAGE* ${COMOUT}/.
    cp ${DATA}/files_fires.tar ${COMOUT}/.

# convert to grib2
    export DBNALERT_TYPE=${DBNALERT_TYPE:-GRIB_HIGH}
    export NET=smoke

    cd $DATA
    /nwprod/util/exec/cnvgrib -g12 -m0 -p32 grib_pbl.1hr grib2_pbl.1hr
    /nwprod/util/exec/cnvgrib -g12 -m0 -p32 grib_sfc.1hr grib2_sfc.1hr

    cp grib2_pbl.1hr ${COMOUT}/.
    cp grib2_sfc.1hr ${COMOUT}/.

    echo ' &NLCOPYGB IDS(164)=1, IBS(164)=-1 /' > smoke_scale
    /nwprod/util/exec/smoke_copygb -N smoke_scale -g227 -x grib_pbl.1hr grib_pbl.1hr_227
    /nwprod/util/exec/smoke_copygb -N smoke_scale -g227 -x grib_sfc.1hr grib_sfc.1hr_227

    /nwprod/util/exec/cnvgrib -g12 -m0 -p2 grib_pbl.1hr_227 grib2_pbl.1hr_227
    /nwprod/util/exec/cnvgrib -g12 -m0 -p2 grib_sfc.1hr_227 grib2_sfc.1hr_227

    cp grib2_pbl.1hr_227 ${COMOUT}/${RUN}.${cycle}.grib2_pbl.1hr_227
    cp grib2_sfc.1hr_227 ${COMOUT}/${RUN}.${cycle}.grib2_sfc.1hr_227

    ##############################
    # Create AWIPS GRIB data
    ##############################

    for type in pbl sfc
    do
        echo 0 > filesize
        export XLFRTEOPTS="unit_vars=yes"
        export XLFUNIT_11=grib2_${type}.1hr_227
        export XLFUNIT_12="filesize"
        export XLFUNIT_31=
        export XLFUNIT_51=smoke_${type}.1hr_227.grib2.temp
        /nwprod/util/exec/aqm_smoke < $PARMutil/grib2_smoke${type}.227

        echo `ls -l smoke_${type}.1hr_227.grib2.temp | awk '{print $5} '` > filesize
        export XLFRTEOPTS="unit_vars=yes"
        export XLFUNIT_11=smoke_${type}.1hr_227.grib2.temp
        export XLFUNIT_12="filesize"
        export XLFUNIT_31=
        export XLFUNIT_51=smoke_${type}.1hr_227.grib2
        /nwprod/util/exec/aqm_smoke < $PARMutil/grib2_smoke${type}.227

        ##############################
        # Post Files to PCOM
        ##############################

        if test "$SENDCOM" = 'YES'
        then
            cp smoke_${type}.1hr_227.grib2  $pcom/smoke_${type}.1hr_227.grib2.$job

            ##############################
            # Distribute Data
            ##############################

            if [ "$SENDDBN" = 'YES' ] ; then
               $DBNROOT/bin/dbn_alert $DBNALERT_TYPE $NET $job $pcom/smoke_${type}.1hr_227.grib2.$job
            else
               msg="File $pcom/smoke_${type}.1hr_227.grib2.$job not posted to db_net."
               postmsg "$jlogfile" "$msg"
            fi
        fi
    done
else
  #GSM another mail command
  echo "** HMShysplit file not found! No Smoke Run Today!"
  exit
fi