#!/bin/sh
###############################################################################
#                                                                             #
# This script generates the GRIB file for the MWW3 forecast model             #
# It is run as a child scipt interactively by the postprocessor.              #
#                                                                             #
# Remarks :                                                                   #
# - The necessary files are retrieved by the mother script.                   #
# - This script generates it own sub-directory 'grib_*'.                      # 
# - See section 0.b for variables that need to be set.                        # 
#                                                                             #
#                                                               March, 2007   #
# Last update : 02-29-2012                                                    #
#                                                                             #
###############################################################################
#
# --------------------------------------------------------------------------- #
# 0.  Preparations
# 0.a Basic modes of operation

  # set execution trace prompt.  ${0##*/} adds the script's basename
  PS4=" \${SECONDS} ${0##*/} L\${LINENO} + "
  set -x

  # Use LOUD variable to turn on/off trace.  Defaults to YES (on).
  export LOUD=${LOUD:-YES}; [[ $LOUD = yes ]] && export LOUD=YES
  [[ "$LOUD" != YES ]] && set +x

  cd $DATA
#  postmsg "$jlogfile" "Making GRIB Files."   # commented to reduce unnecessary output to jlogfile


  grdID=$1  
  rm -rf grib1_$grdID
  mkdir grib1_$grdID
  err=$?
  if [ "$err" != '0' ]
  then
    set +x
    echo ' '
    echo '******************************************************************************* '
    echo '*** FATAL ERROR : ERROR IN multiwavegrib1 (COULD NOT CREATE TEMP DIRECTORY) *** '
    echo '******************************************************************************* '
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    ../postmsg "$jlogfile" "FATAL ERROR : ERROR IN multiwavegrib1 (Could not create temp directory)"
    exit 1
  fi

  cd grib1_$grdID

# 0.b Define directories and the search path.
#     The tested variables should be exported by the postprocessor script.

  dtgrib=$2
  ngrib=$3
  GRIDNR=$4
  MODNR=$5
  gribflags=$6

  set +x
  echo ' '
  echo '+--------------------------------+'
  echo '!         Make GRIB files        |'
  echo '+--------------------------------+'
  echo "   Model ID         : $modID"
  [[ "$LOUD" = YES ]] && set -x

  if [ -z "$YMDH" ] || [ -z "$cycle" ] || [ -z "$EXECcode" ] || \
     [ -z "$COMOUT" ] || [ -z "$modID" ] || [ -z "$SENDCOM" ] || \
     [ -z "$dtgrib" ] || [ -z "$ngrib" ] || [ -z "$gribflags" ] || \
     [ -z "$GRIDNR" ] || [ -z "$MODNR" ] || [ -z "$SENDDBN" ]
  then
    set +x
    echo ' '
    echo '***************************************************'
    echo '*** EXPORTED VARIABLES IN postprocessor NOT SET ***'
    echo '***************************************************'
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    ../postmsg "$jlogfile" "EXPORTED VARIABLES IN postprocessor NOT SET"
    exit 1
  fi

# 0.c Starting time for output

  ymdh=$YMDH
  tstart="`echo $ymdh | cut -c1-8` `echo $ymdh | cut -c9-10`0000"

  set +x
  echo "   Starting time    : $tstart"
  echo "   Time step        : $dtgrib"
  echo "   Number of times  : $ngrib"
  echo "   GRIB field flags : $gribflags"
  echo ' '
  [[ "$LOUD" = YES ]] && set -x

# 0.d sync important files

#  $utilexec/fsync_file ${DATA}/mod_def.$grdID
#  $utilexec/fsync_file ${DATA}/out_grd.$grdID
#  $utilexec/fsync_file ${DATA}/multiwavesgrib1.inp.tmpl

# 0.e Links to working directory

  ln -s ../mod_def.$grdID mod_def.ww3
  ln -s ../out_grd.$grdID  out_grd.ww3 

# --------------------------------------------------------------------------- #
# 1.  Generate GRIB file with all data
# 1.a Generate input file for multiwavegrib1
#     Template copied in mother script ...

  set +x
  echo "   Generate input file for multiwavegrib1"
  [[ "$LOUD" = YES ]] && set -x

  sed -e "s/TIME/$tstart/g" \
      -e "s/DT/$dtgrib/g" \
      -e "s/NT/$ngrib/g" \
      -e "s/GRIDNR/$GRIDNR/g" \
      -e "s/MODNR/$MODNR/g" \
      -e "s/FLAGS/$gribflags/g" \
                               ../multiwavegrib1.inp.tmpl > multiwavegrib1.inp

# 1.b Run GRIB packing program

  set +x
  echo "   Run multiwavegrib1"
  echo "   $EXECcode/multiwavegrib1"
  [[ "$LOUD" = YES ]] && set -x

  ln -s ../$modID.$grdID.$cycle.grib gribfile
  $EXECcode/multiwavegrib1
  err=$?

  if [ "$err" != '0' ]
  then
    set +x
    echo ' '
    echo '********************************************* '
    echo '*** FATAL ERROR : ERROR IN multiwavegrib1 *** '
    echo '********************************************* '
    echo ' '
    [[ "$LOUD" = YES ]] && set -x
    ../postmsg "$jlogfile" "FATAL ERROR : ERROR IN multiwavegrib1"
    exit 3
  fi

# 1.c Clean up

  rm -f multiwavegrib1.inp
  rm -f mod_def.ww3
  rm -f out_grd.ww3

# 1.d Save in /com

  if [ "$SENDCOM" = 'YES' ]
  then
    set +x
    echo "   Saving GRIB file as $COMOUT/$grdID.$cycle.grib"
    [[ "$LOUD" = YES ]] && set -x
    cp gribfile $COMOUT/$grdID.$cycle.grib

    if [ ! -f $COMOUT/$grdID.$cycle.grib ]
    then
      echo ' '
      echo '********************************************* '
      echo '*** FATAL ERROR : ERROR IN multiwavegrib2 *** '
      echo '********************************************* '
      echo ' '
      echo " Error in moving grib file $grdID.$cycle.grib to com"
      echo ' '
      [[ "$LOUD" = YES ]] && set -x
      ../postmsg "$jlogfile" "FATAL ERROR : ERROR IN multiwavegrib1"
      exit 4
    fi

    $utilexec/cnvgrib -g12 -p40 gribfile grib2file
    $utilexec/wgrib2 -s grib2file >grib2file.idx
    mv grib2file $COMOUT/$grdID.$cycle.grib.grib2
    mv grib2file.idx $COMOUT/$grdID.$cycle.grib.grib2.idx

    if [ "$SENDDBN" = 'YES' ]
    then
      set +x
      echo "   Alerting GRIB2 file as $COMOUT/$grdID.$cycle.grib.grib2"
      [[ "$LOUD" = YES ]] && set -x
      # add optional tag to dbn_alert subtyp (to distinguish from standard prod alerts)
      if [ "$envir" = 'prod' ]; then
        DBNtag=${DBNtag:-""}
      else
        DBNtag=${DBNtag:="_PARA"}  # '=' used instead of '-' to ensure to use the non-prod alert type for non-prod jobs
      fi
      $DBNROOT/bin/dbn_alert MODEL WAVE_GRIB_GB2${DBNtag} $job $COMOUT/$grdID.$cycle.grib.grib2
      $DBNROOT/bin/dbn_alert MODEL WAVE_GRIB_GB2_WIDX${DBNtag} $job $COMOUT/$grdID.$cycle.grib.grib2.idx
    fi
  fi 

# --------------------------------------------------------------------------- #
# 3.  Clean up the directory

  set +x
  echo "   Removing work directory after success."
  [[ "$LOUD" = YES ]] && set -x

  cd ..
  rm -rf grib1_$grdID

  set +x
  echo ' '
  echo "End of multiwavegrib1.sh at"
  date

# End of multiwavegrib1.sh -------------------------------------------------- #
