#! /bin/ksh
###################################################################################
# hwrf_prep_hybrid.sh
##########################
#
# MAIN SCRIPTS TO (HORIZONTAL AND VERTICAL) INTERPOLATE THE GLOBAL SPECTRAL DATA 
# (SIGMA FILES) TO THE BOUNDARY POINTS OF THE HWRF DOMAIN.
#
# THIS SCRIPTS IS ORIGINATED FROM exndas_mkbnd_cntrl.sh.sms_new CODED BY ERIC RODGERS 
#      AND MATT PYLE
#
# 09-2006    Written by YOUNG C. KWON
# 04-2007    Revised for operations by VIJAY TALLAPRAGADA and BILL O'CONNOR 
# Jun 2009 Revised for HWRF 2009 implementation, Vijay Tallapragada
# Mar 2011 Revised for HWRF 2011 implementation, Sam Trahan
#
####################################################################################
set -x

max_wait_time=300 # max seconds to wait for a GFS sigma file

export HPSS_PFTPC_PORT_RANGE=ncacn_ip_tcp[38000-38999]
export HPSS_NDCG_SERVERS=10.198.22.5/8001
######## GET THE INPUT VARIABLES #################
if [ $# -eq 5 ]
    then
    export STORM=$1
    export CDATE=$2
    STORMLAT=$3
    STORMLON=$4
    args=$5
    
    echo 'STORM     = ' ${STORM}
    echo 'CDATE     = ' ${CDATE}
    echo 'STORMLAT  = ' ${STORMLAT}
    echo 'STORMLON  = ' ${STORMLON}  
    echo 'args      = ' ${args}
else
    echo 'Usage: sh hwrf_prep_hybrid.sh STORM CDATE STORMLAT STORMLON arglist'
    echo 'NEED FIVE INPUT VARIABLES'
    echo 'SCRIPT WILL EXIT' 
    sh ${utilscript}/setup.sh
    err=911
    err_exit "NEED FIVE INPUT VARIABLES"
fi

##################################################
# set up working directories
PREP_DATA=${CSTREAM}/PREP/DATA 
#/bin/rm -rf $PREP_DATA
$USHhwrf/hwrf_mkdirp.sh $PREP_DATA
cd $PREP_DATA
pwd

export EXPT=hwrf
export ERRSCRIPT=${ERRSCRIPT:-'eval [[ $err = 0 ]]'}
DOMNAM=sigma
DOM=${DOMNAM}${EXPT}

echo 'CSTREAM   = ' ${CSTREAM}  
echo 'PREP_DATA = ' ${PREP_DATA}
echo 'EXPT      = ' ${EXPT}
echo 'ERRSCRIPT = ' ${ERRSCRIPT}
echo 'DOMNAM    = ' ${DOMNAM}
echo 'DOM       = ' ${DOM}   


PDY=`echo $CDATE | cut -c1-8`
yyyy=`echo $CDATE | cut -c1-4`
mm=`echo $CDATE | cut -c5-6`
dd=`echo $CDATE | cut -c7-8`
hh=`echo $CDATE | cut -c9-10`

echo 'PDY   = ' ${PDY}
echo 'yyyy  = ' ${yyyy}
echo 'mm    = ' ${mm}
echo 'dd    = ' ${dd} 
echo 'hh    = ' ${hh}  

## STATIC FILE DIRECTORY
SDIR=${CSTREAM}/NMMWPS/
echo 'SDIR = ' ${SDIR}  

tmmark=tm00
tmval=`echo $tmmark | cut -c3-4`

if [ ${PARAFLAG} = 'YES' ]
    then

    if [[ $yyyy -lt 2005 ]]; then
        echo "Hybrid GFS not available for years before 2005"
        echo "Use GFS or AVN sigma files and run hwrf_prep.sh"
        echo "to create Boundary Condition"
        echo "this script will now exit"
        sh ${utilscript}/setup.sh
        err=911
        err_exit "Cannot run storms before 2005 season"
    fi
fi

# Assume we're on CCS running a forecast:
filepre=${ATMOS_INPUT:-$COMINGFS}/gfs.t${hh}z.sf
filepost=''

## LINK TO THE SPECTRAL FILES

linkcount=0
for linkindex in $args ; do
    linkhour=$(( linkindex * 6 ))
    hour00=$( printf "%02d" $linkhour ) # zero-pad to two digits
    localfile=./gfsbc$linkindex.tm00
    gfsfile=$filepre$hour00$filepost
    ln -sf $gfsfile $localfile
    echo Wait for hour $hour00 file $gfsfile ...
    if ( ! $USHhwrf/hwrf_file_complete.pl -w "$max_wait_time" -S 10 -o 30 -s 1 -v "$gfsfile" ) ; then
        echo "GFS BCs not properly copied. Check pathnames for GFS Sigma Files"
        echo "this script will now exit"
        sh ${utilscript}/setup.sh
        err=911
        err_exit "GFS Boundary Conditions (sigma files) not properly linked (gave up at hour $hour00)"
    fi
    echo Have $hour00 file $gfsfile now.
    let 'linkcount=linkcount+1'

    if [[ $linkcount == 1 ]] ; then
      first_index=$linkindex
    fi
done

## WAIT FOR THE STATIC DATA TO BE READY

if [[ "$IO_FORM" == 1 ]] ; then
    GEOFILE=${SDIR}/geo_nmm.d01.int
else
    GEOFILE=${SDIR}/geo_nmm.d01.nc
fi

ic=0
if ( ! $USHhwrf/hwrf_file_complete.pl -w 3600 -S 10 -o 10 -s 1 -v "$GEOFILE" ) ; then
    echo 'WPS static (geogrid) is not completed for 60 min'
    echo 'check the geogrid.log and fix it, now exiting'
    sh ${utilscript}/setup.sh
    err=911
    err_exit "WPS static (geogrid) is not completed for 60min"
fi

## EXTRACT LATERAL BOUNDARY DATA FOR HWRF

if [[ "$PARAFLAG" == YES ]] ; then
    $USHhwrf/hwrf_port_cachesync.sh -p
fi

# Remove the old "done" files:
dones=''
for piece in $args ; do
    donefile=$PREP_DATA/mkbnddone.$piece
    rm -f $donefile
    dones="$dones $donefile"
done

if [[ "$PARAFLAG" == YES ]] ; then
    $USHhwrf/hwrf_port_cachesync.sh -p
fi

# Generate the poe command file:
commandfile=ph_poefile_f${first_index}_n${linkcount}
rm -f "$commandfile"
if [[ "$PARAFLAG" == YES ]] ; then
    $USHhwrf/hwrf_port_cachesync.sh
fi

for piece in $args ; do
  echo "${USHhwrf}/hwrf_mkbnd.sh $piece $DOM $tmmark $CDATE $STORM $STORMLAT $STORMLON $CSTREAM $GEOFILE" >> "$commandfile"
  if [[ "$PARAFLAG" == YES ]] ; then
      $USHhwrf/hwrf_port_cachesync.sh
  fi
done
chmod 775 $commandfile
sh ${utilscript}/setup.sh
if [[ "$PARAFLAG" == YES ]] ; then
    $USHhwrf/hwrf_port_cachesync.sh -p
fi

#
# Execute the script.
$USHhwrf/hwrf_run.sh -mpiwrap -mpmd -cmdfile $(pwd)/$commandfile
export err=$?
if [ $err -ne 0 ]; then
    err_exit "HYBRID PREP failed - aborting"
fi

## WAIT FOR PREP_HYBRID TO FINISH
waittime=900
if [[ "$PARAFLAG" == YES ]] ; then
    waittime=3600
fi
if ( ! $USHhwrf/hwrf_file_complete.pl -w $waittime -S 20 -s 1 -o 3 -v $dones ) ; then
    sh ${utilscript}/setup.sh
    err=911
    err_exit "PREP_HYBRID TOOK TOO LONG.  ABORTING."
fi

exit 0  # DO NOT REMOVE THIS LINE
