#!/bin/bash
#
# This script creates plots of IMERG precip analyses over a 
# specified geographical subset region.
#
# Author: Jonathan Case
# Originally written: 19 OCT 2011
# Revised for grads: 10 Feb 2016
# Also added 6-h accumulation plots on 10 Feb 2016
# Revised for SMAPDA East-Africa d01 and d02 modeling domain on 8 Nov 2018
#

TOPDIR=/usr/people/casejl
NOBACKUP=/raid1/sport/people/casejl
RT=/raid2/sport/people/casejl
DATA=/raid1/sport/data
SRCDIR="${TOPDIR}/scripts/IMERG"
DATADIR="${DATA}/IMERG"
SHAPEDIR="${DATA}/SHAPEFILES"
export GADDIR="/data/sport/people/casejl/WRF/UEMS371/uems/util/grads/data"
GRADSDIR="${TOPDIR}/GRADSCRP"
GRADSEXE="/data/sport/people/casejl/WRF/UEMS371/uems/util/grads/bin/grads -a 0.97 -bc"
CONVERT=/usr/bin/convert
xpix=1000 ; ypix=800
xlint=2 ; ylint=2

prodlist="imergf"
#prodlist="imergl"
#
#
domlist="eastafrica kenya"
accumList="1 3 6 12 24"
doscp=n
  scpCmd="scp -q -o ConnectTimeout=5 -o ConnectionAttempts=1"
  user="webload"
  server="weather"

if [ $# -lt 1 ] ; then
  realtime=y
  echo "Setting date to default: current date minus 2 days."
  yyyymmdd_start=`date -u --date="2 days ago" +%Y%m%d`
  yyyymmdd_end=`date -u +%Y%m%d`
else
  strlen=`echo $1 | awk '{
	num=length($1)
	print num}'`
  if [ $strlen -ne 8 ] ; then
    echo "USAGE: makegifs_imerg_EAF_grads.bash YYYYMMDD"
    echo "where YYYYMMDD is the desired date."
    exit
  fi
  realtime=n
  yyyymmdd_start=$1
  yyyymmdd_end=$1
fi

yyyymmdd=${yyyymmdd_start}

while [ $yyyymmdd -le ${yyyymmdd_end} ] ; do

  cc=`echo $yyyymmdd | cut -c1-2`
  yy=`echo $yyyymmdd | cut -c3-4`
  mm=`echo $yyyymmdd | cut -c5-6`
  dd=`echo $yyyymmdd | cut -c7-8`
  yymmdd=$yy$mm$dd
  yymmddm1=`${TOPDIR}/bin/dayadd -1 $yymmdd`
  yyyymmddm1=${cc}${yymmddm1}
  yymmm1=`echo $yymmddm1 | cut -c1-4`
  yymmddp1=`${TOPDIR}/bin/dayadd  1 $yymmdd`

  WORKDIR="${RT}/servir/imerg/${cc}${yy}${mm}"
  OUTDIR=${WORKDIR}
  if [ ! -d $WORKDIR ] ; then
    mkdir -p $WORKDIR
  fi
  cd $WORKDIR

# Link in applicable grads files
  ln -fs ${GRADSDIR}/cbar.gs ./ >& /dev/null
  ln -fs ${GRADSDIR}/cbar_smlabel.gs ./ >& /dev/null
  ln -fs ${GRADSDIR}/environ.ch ./ >& /dev/null
  ln -fs ${GRADSDIR}/environ_shaded.ch ./ >& /dev/null
  ln -fs ${GRADSDIR}/rgbset.gs ./ >& /dev/null

#  REMDIRh="incoming/servir_modeling/eastAfrica/precip"
#  REMDIRa="incoming/servir_modeling/kenya/precip"

  for prod in $prodlist ; do
    case $prod in
	imerge) latency=6 ;;
	imergl) latency=18 ;;
	imergf) latency=9999 ;;
    esac
    for dom in $domlist ; do
      if [ $dom = "kenya" ] ; then
        ln -fs ${SHAPEDIR}/Kenya_admin_2014_WGS84* ./ >& /dev/null
      else
        rm -f Kenya_admin_2014_WGS84*
      fi
      case $dom in
        eastafrica) latll="-13.20" ; latur="13.20" ; 
                    lonll="23.64" ; lonur="50.36" ; 
                    id="eaf" ; REMDIR="incoming/servir_modeling/eastAfrica/precip" ;;
        kenya)      latll="-9.02" ; latur="8.46" ; 
                    lonll="27.69" ; lonur="45.26" ;
                    id="ken" ; REMDIR="incoming/servir_modeling/kenya/precip" ;;
      esac

      for accum in $accumList ; do
        maxloop=`expr 2*${accum}`
        if [ $accum -lt 10 ] ; then
          acchr="0"${accum}
        else
          acchr=${accum}
        fi
        case $accum in
		1) hhlist="01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 00" ;;
		3) hhlist="03 06 09 12 15 18 21 00" ;;
		6) hhlist="03 06 09 12 15 18 21 00" ;;
		12) hhlist="06 12 18 00" ;;
		24) hhlist="06 12 18 00" ;;
        esac

        for hh in $hhlist ; do
          doit=y
          if [ $hh = "00" ] ; then
            outfile="${prod}${acchr}h_${id}_${cc}${yymmddp1}_${hh}00Z.gif"
            yyyymmddwork=${cc}${yymmddp1}
            mmwork=`echo $yymmddp1 | cut -c3-4`
          else
            outfile="${prod}${acchr}h_${id}_${yyyymmdd}_${hh}00Z.gif"
            yyyymmddwork=${yyyymmdd}
            mmwork=`echo $yymmdd | cut -c3-4`
          fi
          vyyyymmdd=$yyyymmddwork
          vyyyy=`echo $vyyyymmdd | cut -c1-4`
          vmm=`echo $vyyyymmdd | cut -c5-6`
          vdd=`echo $vyyyymmdd | cut -c7-8`
          case $vmm in
		01) vmon="Jan" ;;
		02) vmon="Feb" ;;
		03) vmon="Mar" ;;
		04) vmon="Apr" ;;
		05) vmon="May" ;;
		06) vmon="Jun" ;;
		07) vmon="Jul" ;;
		08) vmon="Aug" ;;
		09) vmon="Sep" ;;
		10) vmon="Oct" ;;
		11) vmon="Nov" ;;
		12) vmon="Dec" ;;
          esac
          # determine if we'll process images at this hour for real-time production,
          # based on the imerg product latency defined above.
          if [ $realtime = "y" ] ; then
            yyyymmddrt=`date -u +%Y%m%d`
            hhrt=`date -u +%H`
            hhrt=`expr $hhrt - $latency`
            if [ $hhrt -lt 0 ] ; then
              hhrt=`expr $hhrt + 24`
              yyyymmddrt=`date -u +%Y%m%d -d "${yyyymmddrt}-1 days"`
            fi
            if [ $hhrt -lt 10 ] ; then
              hhrt="0"$hhrt
            fi
            if [ $vyyyymmdd -gt $yyyymmddrt ] ; then
              doit=n
            fi
            if [ $vyyyymmdd -eq $yyyymmddrt ] ; then
              if [ $hh -ge $hhrt ] ; then
                doit=n
              fi
            fi
          fi

          echo "PROD VYYYYMMDD HH YYYYMMDDRT HHRT REALTIME DOIT: $prod $vyyyymmdd $hh $yyyymmddrt $hhrt $realtime $doit"

          if [ $doit = "y" ] ; then
        # Establish start time for imerg grads control file.
            yyyywork=`echo $yyyymmddwork | cut -c1-4`
            mmwork=`echo $yyyymmddwork | cut -c5-6`
            ddwork=`echo $yyyymmddwork | cut -c7-8`
        # IMERG data are valid for the 30 min FOLLOWING the timestamp of the file.
        #    hhwork=`expr $hh - $accum + 1`
            hhwork=`expr $hh - $accum`
            if [ $hhwork -lt 0 ] ; then
              hhwork=`expr $hhwork + 24`
              yyyymmddwork=`date -u +%Y%m%d -d "${yyyymmddwork}-1 days"`
              yyyywork=`echo $yyyymmddwork | cut -c1-4`
              mmwork=`echo $yyyymmddwork | cut -c5-6`
              ddwork=`echo $yyyymmddwork | cut -c7-8`
            fi
            if [ $hhwork -lt 10 ] ; then
              hhwork="0"$hhwork
            fi
            case $mmwork in
		01) mon="Jan" ;;
		02) mon="Feb" ;;
		03) mon="Mar" ;;
		04) mon="Apr" ;;
		05) mon="May" ;;
		06) mon="Jun" ;;
		07) mon="Jul" ;;
		08) mon="Aug" ;;
		09) mon="Sep" ;;
		10) mon="Oct" ;;
		11) mon="Nov" ;;
		12) mon="Dec" ;;
            esac

# Create grads control file for imerge, imergl, or imergf
            sed 's;00:30ZDDMONYYYY;'${hhwork}':00Z'${ddwork}''${mon}''${yyyywork}';g' ${SRCDIR}/${prod}.ctl.sed > ${prod}.ctl
#            cat ${prod}.ctl
#            exit

            echo "Processing ${prod} ${accum}h for vyyyymmdd ${vyyyymmdd} hour ${hh}z and domain ${dom}"

            if [ $accum -lt 12 ] ; then
              sed 's;HH;'${hh}';g' ${SRCDIR}/${prod}.gs.sed |\
                sed 's;ACCUM;'${accum}';g'                  |\
                sed 's;MAXLOOP;'${maxloop}';g'              |\
                sed 's;CLEVS; 1  2  5 10 15 20 25 50 75 100 125 150;g'  |\
                sed 's;CCOLS;0 33 35 37 39 43 45 47 49 53 55  57  59;g' |\
                sed 's;YYYYMMDD;'${vyyyymmdd}';g'          |\
                sed 's;YYYY;'${vyyyy}';g'                  |\
                sed 's;MON;'${vmon}';g'                    |\
                sed 's;DD;'${vdd}';g'                      |\
                sed 's;XPIX;'${xpix}';g'                   |\
                sed 's;YPIX;'${ypix}';g'                   |\
                sed 's;XLINT;'${xlint}';g'                 |\
                sed 's;YLINT;'${ylint}';g'                 |\
                sed 's;LATLL;'${latll}';g'                 |\
                sed 's;LATUR;'${latur}';g'                 |\
                sed 's;LONLL;'${lonll}';g'                 |\
                sed 's;LONUR;'${lonur}';g'  > ${prod}${accum}h.gs
            else
              sed 's;HH;'${hh}';g' ${SRCDIR}/${prod}.gs.sed |\
                sed 's;ACCUM;'${accum}';g'                  |\
                sed 's;MAXLOOP;'${maxloop}';g'              |\
                sed 's;CLEVS; 1  2  5 10 15 20 25 50 75 100 125 150 200 250 300;g'  |\
                sed 's;CCOLS;0 33 35 37 39 43 45 47 49 53 55  57  59  65  67  69;g' |\
                sed 's;YYYYMMDD;'${vyyyymmdd}';g'          |\
                sed 's;YYYY;'${vyyyy}';g'                  |\
                sed 's;MON;'${vmon}';g'                    |\
                sed 's;DD;'${vdd}';g'                      |\
                sed 's;XPIX;'${xpix}';g'                   |\
                sed 's;YPIX;'${ypix}';g'                   |\
                sed 's;XLINT;'${xlint}';g'                 |\
                sed 's;YLINT;'${ylint}';g'                 |\
                sed 's;LATLL;'${latll}';g'                 |\
                sed 's;LATUR;'${latur}';g'                 |\
                sed 's;LONLL;'${lonll}';g'                 |\
                sed 's;LONUR;'${lonur}';g'  > ${prod}${accum}h.gs
            fi

            ${GRADSEXE} "run ${prod}${accum}h.gs" >& grads_${prod}${accum}h.out
            pngFile="${prod}${accum}h.png"
            ${CONVERT} ${pngFile} ${OUTDIR}/${outfile}

            if [ $doscp = "y" ] ; then
              echo "scping ${OUTDIR}/${outfile} to weather server"
              $scpCmd ${OUTDIR}/${outfile} ${user}@${server}:${REMDIR}
            fi
          fi ## doit flag

        done ## hh loop
      done ## accumList loop
    done ## dom loop
  done ## prod loop
  yyyymmdd=`date -u +%Y%m%d -d "${yyyymmdd}+1 days"`
done ## yyyymmdd loop

exit
