#!/bin/bash

if [[ "$1" == '-h' ]]; then
    echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ "
    echo "Usage: ./get_GFS_eavg.sh -h gives this brief help "
    echo " "	
    echo " -d=YYYYMMDD  :  date i.e. 20150621"
    echo " -r=HH        :  hour of run [00 06 12 18]"
    echo " -wl=DDD.DD   :  western  Longitude of area to extract"
    echo " -el=DDD.DD   :  eastern  Longitude of area to extract"
    echo " -sl=DDD.DD   :  southern Latitude of area to extract"
    echo " -nl=DDD.DD   :  northern Latitude of area to extract"
    echo "                 all in decimal degrees"
    echo "                 default lon [0 360], lat [-90 90]"
    echo " -st=HH       :  start time [0] of forecast"
    echo " -et=HH       :  end time [96]  of forecast"
    echo "                 0.5 GFS 3h => 96=10 days "
    echo " "
    echo " example      :  ./get_GFS_eavg.sh -d=20150620 -r=00 -wl=-10.5 -el=20.25 -nl=60.75 -sl=40.0"
    exit 0
fi

for i in "$@"
do
case $i in
    -d=*|--date=*)
    date="${i#*=}"
    ;;
    -r=*|--date=*)
    run="${i#*=}"
    ;;
    -wl=*)
    leftlon="${i#*=}"
    ;;
    -el=*)
    rightlon="${i#*=}"
    ;;
    -nl=*)
    toplat="${i#*=}"
    ;;
    -sl=*)
    bottomlat="${i#*=}"
    ;;
    -st=*)
    StartTime="${i#*=}"
    ;;
    -et=*)
    EndTime="${i#*=}"
    ;;
    -tmpdir=*)
    tmpdiri="${i#*=}"
    ;;
    -outdir=*)
    outdiri="${i#*=}"
    ;;
esac
done

# define default variables
if [[ "${date}" == "" ]]      ; then  param=FALSE; date=`date -u +%Y%m%d`; fi
if [[ "${run}" == "" ]] && [[ "${run}" != "00" ]] && [[ "${run}" && "06" ]] && [[ "${run}" != "12" ]] && [[ "${run}" != "18" ]]  ; then  param=FALSE; run="00"; fi
if [[ "${StartTime}" == "" ]] ; then  param=FALSE; StartTime=0 ; fi
if [[ "${EndTime}" == ""   ]] ; then  param=FALSE; EndTime=96 ; fi
if [[ "${leftlon}" == ""   ]] ; then  param=FALSE; leftlon="0" ; fi
if [[ "${rightlon}" == ""  ]] ; then  param=FALSE; rightlon="360" ; fi
if [[ "${toplat}" == ""    ]] ; then  param=FALSE; toplat="90" ; fi
if [[ "${bottomlat}" == "" ]] ; then  param=FALSE; bottomlat="-90" ; fi

echo "argument list:"
echo " "
echo date=${date}
echo run=${run}
echo StartTime=${StartTime}
echo EndTime=${EndTime}
echo leftlon=${leftlon}
echo rightlon=${rightlon}
echo toplat=${toplat}
echo bottomlat=${bottomlat}

TEMPDATAPATH=$tmpdiri
echo "~~~~~~~~~~~~~~~~~"
echo "temp folder:"
echo "$TEMPDATAPATH"
echo "~~~~~~~~~~~~~~~~~"

OUTDATAPATH=$outdiri
echo "~~~~~~~~~~~~~~~~~"
echo "output folder:"
echo "$OUTDATAPATH"
echo "~~~~~~~~~~~~~~~~~"

# change directory to runtime directory
cd $TEMPDATAPATH

# fix the substitution variables to fixed format 3 numbers
charNewHour=$(printf "%03d\n" $StartTime)
charStartTime=$(printf "%02d\n" $StartTime)
hour=$StartTime

# gfs  bias corrected
#URL="https://nomads.ncep.noaa.gov/cgi-bin/filter_gensbc.pl?file=geavg.t${run}z.pgrb2a.0p50_bcf${charNewHour}&lev_500_mb=on&var_HGT=on&subregion=&leftlon=${leftlon}&rightlon=${rightlon}&toplat=${toplat}&bottomlat=${bottomlat}&dir=%2Fgefs.${date}%2F${run}%2Fpgrb2ap5_bc"

# gfs normal -> para la hora 00 
URL="https://nomads.ncep.noaa.gov/cgi-bin/filter_gefs_atmos_0p50a.pl?file=geavg.t${run}z.pgrb2a.0p50.f${charNewHour}&lev_500_mb=on&var_HGT=on&subregion=&leftlon=${leftlon}&rightlon=${rightlon}&toplat=${toplat}&bottomlat=${bottomlat}&dir=%2Fgefs.${date}%2F${run}%2Fatmos%2Fpgrb2ap5"


#URL="https://nomads.ncep.noaa.gov/cgi-bin/filter_gensbc.pl?file=geavg.t${run}z.pgrb2a.0p50_bcf${charNewHour}&lev_500_mb=on&var_HGT=on&subregion=&leftlon=${leftlon}&rightlon=${rightlon}&toplat=${toplat}&bottomlat=${bottomlat}&dir=%2Fgefs.${date}%2F${run}%2Fpgrb2ap5_bc"

#URL="https://nomads.ncep.noaa.gov/cgi-bin/filter_gensbc.pl?file=geavg.t${run}z.pgrb2a.0p50_bcf${charNewHour}&lev_500_mb=on&var_HGT=on&subregion=&leftlon=${leftlon}&rightlon=${rightlon}&toplat=${toplat}&bottomlat=${bottomlat}&dir=%2Fgefs.${date}%2F${run}%2Fpgrb2ap5_bc"

#URL="https://nomads.ncep.noaa.gov/cgi-bin/filter_gefs_atmos_0p50a.pl?file=geavg.t${run}z.pgrb2a.0p50.f${charNewHour}&lev_500_mb=on&var_HGT=on&subregion=&leftlon=${leftlon}&rightlon=${rightlon}&toplat=${toplat}&bottomlat=${bottomlat}&dir=%2Fgefs.${date}%2F${run}%2Fatmos%2Fpgrb2ap5"


#URL="https://nomads.ncep.noaa.gov/cgi-bin/filter_gens_0p50.pl?file=geavg.t${run}z.pgrb2a.0p50.f${charNewHour}&lev_500_mb=on&var_HGT=on&subregion=&leftlon=${leftlon}&rightlon=${rightlon}&toplat=${toplat}&bottomlat=${bottomlat}&dir=%2Fgefs.${date}%2F${run}%2Fpgrb2ap5"

# first we check if the file exist
echo "check if data is available...."
if [[ `curl -k --head $URL 2>&1 | grep 'HTTP/2 200'` ]]
 then
    curl -k "$URL" -o gfs.t${run}z.pgrb2.0p25.f000
	file_size_00=`du -k "gfs.t${run}z.pgrb2.0p25.f000" | cut -f1`
	# start loop over all time slots NOTE GFS 0.5 has a 3 hours cycle
	while [ $hour -le $EndTime ]
	do
		# loop setup the url
    	URL="https://nomads.ncep.noaa.gov/cgi-bin/filter_gensbc.pl?file=geavg.t${run}z.pgrb2a.0p50_bcf${charNewHour}&lev_500_mb=on&var_HGT=on&subregion=&leftlon=${leftlon}&rightlon=${rightlon}&toplat=${toplat}&bottomlat=${bottomlat}&dir=%2Fgefs.${date}%2F${run}%2Fpgrb2ap5_bc"
		echo "start download...."
        if [ ! -f gfs.t${run}z.pgrb2.0p25.f${charNewHour} ]; then
          curl -k "$URL" -o gfs.t${run}z.pgrb2.0p25.f${charNewHour}
        else
		  file_size_run=`du -k "gfs.t${run}z.pgrb2.0p25.f${charNewHour}" | cut -f1`
          comp=$(echo "$file_size_00" | awk '{printf("%d\n",$file_size_00 * 0.2 +$file_size_00)}')
		  if (( $file_size_run < $file_size_00 )) ; then
		  echo "HALLO"
    		  # then we get the data via cURL
	    	  curl -k "$URL" -o gfs.t${run}z.pgrb2.0p25.f${charNewHour}
          elif (( $file_size_run > comp)) ; then
              curl -k "$URL" -o gfs.t${run}z.pgrb2.0p25.f${charNewHour}

		  fi
		fi
		# INCREMENT timeslot
		hour=$(($hour + 6))
		# correct time format for substitution
        charNewHour=$(printf "%03d\n" $hour)
	done
else
	echo "-----------------------------------------------"
	echo "Currently the requested Data is NOT available."
	echo "Please check the date of the request. "
	echo "Note: GFS 0.5 files have about a 7 hours delay."
	exit
fi

# merge all grib2 files to one
cdo -O mergetime gfs.t${run}z.pgrb2.0p25.f* gfs.t${run}z.pgrb2.0p25.${date}_${charStartTime}_${EndTime}.grb

# grib2 to netcdf
cdo -f nc copy gfs.t${run}z.pgrb2.0p25.${date}_${charStartTime}_${EndTime}.grb forecast_16_days_after_eavg.nc

# remove single files
rm -r gfs.t${run}z.pgrb2.0p25.${date}_${charStartTime}_${EndTime}.grb
rm -r gfs.t${run}z.pgrb2.0p25.f???

mv forecast_16_days_after_eavg.nc $OUTDATAPATH

echo "get_GFS_eavg.sh finished"
echo " "
