#!/bin/ksh 


set -eux 

## Defaults 


EXTDATE=19790101
EXPVER=1
FREQ=3
CLASS=ei
STREAM=oper
LAPSE=false
DSTORAGE="/xxxx" #"$SCRATCH"
EFOR=false

while getopts e:i:f:c:s:l:d:x:b:z: option
do
  case $option in
    e) EXTDATE=$OPTARG;;
    i) EXPVER=$OPTARG;;
    f) FREQ=$OPTARG;;
    c) CLASS=$OPTARG;;
    s) STREAM=$OPTARG;;
    l) LAPSE=$OPTARG;;
    x) DSTORAGE=$OPTARG;;
    b) EFOR=$OPTARG;;
    z) FCLEN=$OPTARG;;
    \?) exit 1;;
  esac
done
LECFS=true
if [[ $DSTORAGE = ${DSTORAGE#ec:} ]];then
  LECFS=false
fi

tag="${CLASS}_${EXPVER}_${STREAM}_${FREQ}_${EXTDATE}"
if [[ ! ${FORCINGLEV:-0} = 0 ]]; then
  tag="${CLASS}_${EXPVER}_${STREAM}_${FREQ}_${EXTDATE}_LEV${FORCINGLEV}"
fi 
FOUT=forcing_${tag}

if [[ $LECFS = true ]]; then
  etest -r $DSTORAGE/${FOUT}.tar.gz && ret=0 || ret=1
else
  test -r $DSTORAGE/${FOUT}.tar.gz && ret=0 || ret=1
fi

if [[ $ret = 0 ]]; then
  echo "file already exists... skipping"
  echo "${FOUT}.tar.gz"
  exit 0 
fi
echo "Working on: ${FOUT}.tar.gz"
  
DATADIR=${TMPDIR}/dd_${tag}
WDIR=${DATADIR}/work/

rm -rf $WDIR $DATADIR
mkdir -p $WDIR
cd $WDIR

set +e
if [[ $EFOR = true ]]; then
  if [[ $STREAM = enfo ]]; then
    extract_forcing_forecast_ens.ksh -e $EXTDATE -i $EXPVER -d $DATADIR -n $FREQ -c $CLASS -s $STREAM -z $FCLEN
  else
    extract_forcing_forecast.ksh -e $EXTDATE -i $EXPVER -d $DATADIR -f $FREQ -c $CLASS -s $STREAM -z $FCLEN
  fi
else
  extract_forcing.ksh -e $EXTDATE -i $EXPVER -d $DATADIR -f $FREQ -c $CLASS -s $STREAM -l $LAPSE 
fi 
if [[ $? -ne 0 ]] ;then 
  echo "Error extracting"
  cat $DATADIR/ext.log
  exit -1
fi
set -e 

cd $DATADIR
tar -cvf ${FOUT}.tar *.grb 
gzip ${FOUT}.tar  
if [[ $LECFS = true ]];then
  ecp -o ${FOUT}.tar.gz $DSTORAGE
  echmod 644 $DSTORAGE/${FOUT}.tar.gz
else
  cp -f ${FOUT}.tar.gz $DSTORAGE
  chmod 644 $DSTORAGE/${FOUT}.tar.gz
fi

rm -rf $WDIR $DATADIR
exit 0 
