#!/bin/ksh -x

#VARIAVEIS
export Run_Date=2014112912
export Eta_conf=${Eta_home}/eta/MGClima/configuracao
export Conf=MGClima
export Fct=2952
export Fcts=000
export IntFct=24
export FInitBC=cfs
export InitBC=6
export TInitBC=1

export Eta_run=/home/jorge/CEMIG/CFS
export data_grib=/home/jorge/CEMIG/CFS
mkdir -p ${data_grib}/${Run_Date}
cd ${Eta_run}
Get_Date=`echo ${Run_Date}|cut -c 1-8`
hh=`echo ${Run_Date}|cut -c 9-10`
FctCont=000000
cont=0
CondicoesOK="False"
typeset -Z4 Fct FctCont
typeset -Z4 FctCont2
FctCont2=${FctCont}
 
mkdir -p ${data_grib}/${Run_Date}

while [ "${CondicoesOK}" != "True" ] ; do


dir_cfs=http://nomads.ncep.noaa.gov/pub/data/nccf/com/cfs/prod/cfs/cfs.${Get_Date}/${hh}/6hrly_grib_01
flxf_get=`./caldate.3.0 ${Run_Date} + ${FctCont}h 'flxfyyyymmddhh.01.YYYYMMDDHH.grb2'`
ocnf_get=`./caldate.3.0 ${Run_Date} + ${FctCont}h 'ocnfyyyymmddhh.01.YYYYMMDDHH.grb2'`
pgbf_get=`./caldate.3.0 ${Run_Date} + ${FctCont}h 'pgbfyyyymmddhh.01.YYYYMMDDHH.grb2'`

  if [ ! -s ${data_grib}/${Run_Date}/${flxf_get} ] ; then
     cd  ${data_grib}/${Run_Date}
     echo "ARQ1"${flxf_get} >> ${Eta_run}/cond$Run_Date  
     wget -c ${dir_cfs}/${flxf_get}
# salva as condicoes 
  fi

  if [ ! -s ${data_grib}/${Run_Date}/${flxf_get}.idx ] ; then
     cd  ${data_grib}/${Run_Date}
     echo "ARQ1"${flxf_get}.idx >> ${Eta_run}/cond$Run_Date  
     wget -c ${dir_cfs}/${flxf_get}.idx
# salva as condicoes 
  fi

  if [ ! -s ${data_cfs}/${Run_Date}/${ocnf_get} ] ; then
     cd  ${data_cfs}/${Run_Date}
     echo "ARQ1"${ocnf_get} >> ${Eta_run}/cond$Run_Date  
     wget -c ${dir_cfs}/${ocnf_get}
# salva as condicoes 
  fi

  if [ ! -s ${data_grib}/${Run_Date}/${ocnf_get}.idx ] ; then
     cd  ${data_grib}/${Run_Date}
     echo "ARQ1"${ocnf_get}.idx >> ${Eta_run}/cond$Run_Date  
     wget -c ${dir_cfs}/${ocnf_get}.idx
# salva as condicoes 
  fi

  if [ ! -s ${data_grib}/${Run_Date}/${pgbf_get} ] ; then
     cd  ${data_grib}/${Run_Date}
     echo "ARQ1"${pgbf_get} >> ${Eta_run}/cond$Run_Date  
     wget -c ${dir_cfs}/${pgbf_get}
# salva as condicoes 
  fi

  if [ ! -s ${data_grib}/${Run_Date}/${pgbf_get}.idx ] ; then
     cd  ${data_grib}/${Run_Date}
     echo "ARQ1"${pgbf_get}.idx >> ${Eta_run}/cond$Run_Date  
     wget -c ${dir_cfs}/${pgbf_get}.idx
# salva as condicoes 
  fi

  if ((${cont}>=100)); then
    echo "cont1"=$cont
    exit 
  fi
  
  if [ -s ${data_grib}/${Run_Date}/${pgbf_get}  ] ; then
    cd ${Eta_run}
    cont=0
     if [ "${FctCont}" == "${Fct}" ] ; then
      CondicoesOK="True"
      exit
    fi  
    let FctCont=${FctCont}+${InitBC}
    FctCont2=${FctCont}
  else
   sleep 15
   let cont=$cont+1  
  fi
done

