#!/usr/bin/perl
#
# This script takes in the original IMERG-E/L/FNL satellite precip 
# estimates and outputs a GRIB2 file on the Hindu-Kush Himalayan geographical subset.
#
# Author: Jonathan Case and Jayanthi Srikishen
# **Major update** 2/22/2016 to use python script to generate GRIB2 files
# instead of legacy method invoking F90 and GEMPAK programs.
#
# Here we go!
#


# Pragmas
use strict;             # Forces us to define all variables with "my" or "our".
use warnings;           # Same as -w after /usr/bin/perl

# Modules
use Date::Manip;        # For date manipulations.
use File::Path;         # For mkdir tests.
use File::Copy;         # For copy command.
use Net::FTP;           # For ftp-ing data.

#################################
# User inputs (for now, anyway)
#################################

my $realtime   = "n";		## will process data from two days ago
my $beginDate  = "20190901";	## used if not realtime
my $endDate    = "20190903";	## used if not realtime
my $download   = "n";		## Downloads handled in make_precipplot_compare_realtime.sh script
my $replaceGrib = "y";		## Re-generate and replace GRIB files if already present.
my $makeimages = "y";		## Create images for Mesoamerica web page
  my $subsetName = "hkh";	## name assigned to GRIB subset file
  my $lonll =   50.0;		## lower left longitude
  my $lonur =  122.0;		## upper right longitude
  my $latll =    2.0;		## lower left latitude
  my $latur =   50.0;		## upper right latitude 

######################################
# END OF USER INPUT
######################################

my $startDate;
my $stopDate;
my $output;
my $prod;

if ($realtime =~ "y")
{
  $startDate = `date -u --date="1 day ago" +%Y%m%d`;
  chomp($startDate);
  $stopDate  = `date -u +%Y%m%d`;
}
else
{
  $startDate  = $beginDate;
  $stopDate   = $endDate;
}

print "STARTDATE: $startDate\n";
print " STOPDATE: $stopDate\n";

my $TOPDIR  = "/usr/people/casejl";
my $SRCDIR  = "${TOPDIR}/scripts/IMERG";
my $WORKDIR = "/raid2/sport/people/casejl/DATA/IMERG";
my $LOGDIR = "/raid2/sport/people/casejl/LOG";
$output = chdir(${WORKDIR}) or die "Could not change directory to ${WORKDIR}.\n";

my $yyyymmdd = $startDate;
while ($yyyymmdd <= $stopDate)
{

my $yyyy = substr $yyyymmdd, 0, 4;
my $yy   = substr $yyyymmdd, 2, 2;
my $mm   = substr $yyyymmdd, 4, 2;
my $dd   = substr $yyyymmdd, 6, 2;

#my @productList = ("early","late","final");
my @productList = ("final");

foreach $prod (@productList) {
  
my @hhlist = ("00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23");
foreach (@hhlist)
{
  my $hh = $_;
  print "***************************************************************************\n";
  print "Start processing IMERG2GRB for ${yyyymmdd}${hh} at " . `date -u`;
#  print "***************************************************************************\n";
  print "\n";

# J.Case (5/25/2016) -- Need to configure to obtain FINAL IMERG datafiles in the future.
  my $imergFile;

#################################
# Step (1): Download IMERG data
#################################

  if ($download =~ "y")
  {
# Download IMERG from server.
    print "**In imerg download**\n";
    if (! -d "${WORKDIR}/${yyyy}${mm}") {
      $output = mkdir ("${WORKDIR}/${yyyy}${mm}",0755) or die "Cannot create directory ${WORKDIR}/${yyyy}${mm}";
    }
    $output = chdir("${WORKDIR}/${yyyy}${mm}") or die "Cannot change directory to ${WORKDIR}/${yyyy}${mm}";
    my $remoteFile = "${imergFile}.Z";
    my $ftp = Net::FTP->new("ftp.cpc.ncep.noaa.gov",Passive => 1);
    $ftp->login("anonymous","Jonathan.Case-1\@nasa.gov");
    $ftp->binary();
    $ftp->cwd("precip/global_CMORPH/30min_8km") or die "Cannot change remot directory to precip/global_CMORPH/30min_8km", $ftp->message;
    $ftp->get($remoteFile) or warn "Cannot download $remoteFile", $ftp->message;
    $ftp->quit();
# J.Case (12/7/2015) -- rename CMORPH file to old convention to support LIS.
    my $localFile = "advt-8km-interp-prim-sat-spat-2lag-2.5+5dovlp8kmIR-${yyyymmdd}${hh}.Z";
    print "Downloaded $remoteFile ; renamed to $localFile \n";
    $output = rename($remoteFile,$localFile);
    $output = chdir("${WORKDIR}") or die "Cannot change directory to ${WORKDIR}";
  }

#############################################################
# Step (2): Generate GRIB2 files via imerg_hdf2grb.py script
#############################################################
  
  print "** imerg_hdf2grb.py processing **\n";
  my $args = "$yyyy $mm $dd $hh $lonll $lonur $latll $latur $subsetName $prod";
  print "Running ${SRCDIR}/imerg_hdf2grb.py $args \n";
  $output = `${SRCDIR}/imerg_hdf2grb.py $args`;
  print "$output \n";

#  print "\n***************************************************************************\n";
  print " End  processing IMERG2GRB for ${yyyymmdd}${hh} at " . `date -u`;
  print "***************************************************************************\n";

} ## end of @hhlist loop

my $graphicsScript;
if ($makeimages =~ "y")
{
  print "Generating IMERG $prod images on WRF-HKH model domains for ${yyyymmdd} \n";
  $graphicsScript = "${SRCDIR}/makegifs_imerg_HKH_grads_archive.bash";
  $output = `${graphicsScript} ${yyyymmdd} >& ${LOGDIR}/imerg_HKH_grads_archive.log`;
}

} ## end of @productList loop

$yyyymmdd = substr(DateCalc($yyyymmdd, "1 day later"), 0, 8);

} ## end of while loop through dates

exit;

