#!/bin/bash
#
# Get GFS analysis files 
#

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

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 "~~~~~~~~~~~~~~~~~"


cd $OUTDATAPATH
rm *

cd $TEMPDATAPATH
rm *

for i in $(seq 1 1 1)
do

ym=`date --date=${i}" days ago" +%Y%m`
d=`date --date=${i}" days ago" +%d`
y=`date --date=${i}" days ago" +%Y`
m=`date --date=${i}" days ago" +%m`

URL="https://thredds.ucar.edu/thredds/ncss/grid/grib/NCEP/GFS/Global_0p5deg_ana/GFS_Global_0p5deg_ana_" 

for hracb in 00 06 12 18
do

echo "start download...."
#curl "${URL}${ym}${d}_${hracb}00.grib2?var=Geopotential_height_isobaric&north=${toplat}&west=${leftlon}&east=${rightlon}&south=${bottomlat}&disableProjSubset=on&horizStride=1&time_start=${y}-${m}-${d}T${hracb}%3A00%3A00Z&time_end=${y}-${m}-${d}T${hracb}%3A00%3A00Z&timeStride=1&vertCoord=50000&accept=netcdf" -o gfs.${y}${m}${d}_${hracb}.nc

curl "${URL}${ym}${d}_${hracb}00.grib2?var=Geopotential_height_isobaric&north=90&west=0&east=360&south=-90&horizStride=1&time_start=${y}-${m}-${d}T${hracb}%3A00%3A00Z&time_end=${y}-${m}-${d}T${hracb}%3A00%3A00Z&timeStride=1&vertCoord=50000&accept=netcdf" -o gfs.${y}${m}${d}_${hracb}.nc

done
done

find . -name "gfs*" -type 'f' -size -160k -delete

cdo mergetime gfs* analysis_1_days_before_primero.nc
cdo -sellonlatbox,0,360,-70,15 analysis_1_days_before_primero.nc analysis_1_days_before.nc

rm gfs*
rm analysis_1_days_before_primero.nc

mv analysis_1_days_before.nc $OUTDATAPATH

echo "get_GFS_ana.sh finished"
echo " "

