#!/bin/ksh -x
#
#
# Verifica se foi passado algum parametro
hostname
export hh=${1}
if (($#<4)) ; then
export Run_Date=`date "+"%Y%m%d"`${hh}
else
export Run_Date=${4}${hh}
fi

# VARIAVEIS
export FInitBC=eta_01km
export Dir_home=`pwd`
export Dir_wrk=${Dir_home}/../dados/${FInitBC}
export Dir_scr=${Dir_home}
export Dir_util=${Dir_home}/../util
export Fct=${2}
export InitBC=${3}


cd ${Dir_scr}

typeset -Z3 ifct ftime Fct

ifct=000
ihora=`echo ${Run_Date} |cut -c 9-10`

export data_grib=${Dir_wrk}

export yyyy=`echo ${Run_Date} | cut -c1-4`
export mm=`echo ${Run_Date} | cut -c5-6`
export dd=`echo ${Run_Date} | cut -c7-8`
export hh=`echo ${Run_Date} | cut -c9-10`


echo "${FInitBC} DATA  " ${Run_Date}


#http://ftp1.cptec.inpe.br/modelos/tempo/Eta/ams_08km/brutos/2022/01/13/00/
    
datadir=modelos/tempo/Eta/rjsp_01km/brutos/${yyyy}/${mm}/${dd}/${hh}
server=http://ftp1.cptec.inpe.br
    
fpref=${FInitBC}_${Run_Date}
ftime=${ifct}

if [ ! -d ${data_grib}/${Run_Date}} ] ; then
  mkdir -p  ${data_grib}/${Run_Date}
else
  rm -f ${data_grib}/${Run_Date}/wget_${FInitBC}.list 
fi

cd ${data_grib}/${Run_Date}

echo "$server/${datadir}/${fpref}.ctl"       >> ${data_grib}/${Run_Date}/wget_${FInitBC}.list
echo "$server/${datadir}/${fpref}.gmp"       >> ${data_grib}/${Run_Date}/wget_${FInitBC}.list

    
while ((ftime<=${Fct})) ; do
  datefct=`${Dir_util}/caldate.3.0 ${Run_Date} + ${ftime}hr 'yyyymmddhh'`
  ifile=${fpref}+${datefct} 
  if [[ ! -s ${data_grib}/${Run_Date}/${ifile}.grb ]] ; then
    echo $server/${datadir}/${ifile}
    echo "$server/${datadir}/${ifile}.ctl"       >> ${data_grib}/${Run_Date}/wget_${FInitBC}.list
    echo "$server/${datadir}/${ifile}.gmp"       >> ${data_grib}/${Run_Date}/wget_${FInitBC}.list
    echo "$server/${datadir}/${ifile}.grb"       >> ${data_grib}/${Run_Date}/wget_${FInitBC}.list
  fi
  let ftime=$ftime+$InitBC
done

cd ${data_grib}/${Run_Date}
print "Current file : wget_${FInitBC}.list"
cat ${data_grib}/${Run_Date}/wget_${FInitBC}.list  | xargs -n 1 -P 10 wget -q -c -t 3
exit 
   
   
