#!/bin/bash
  
set +xv


# args
date_beg=$1
if [[ $2 =~ '^[0-9]+$' ]]; then
  date_end=$2
else
  var_name=$2
fi
if [ -n "$3" ]; then
  var_name=$3
fi


# date range
if [ -z "${date_end}" ]; then
  date_end=${date_beg}
fi

if [[ ${#date_beg} -eq 6 || ${#date_end} -eq 6 ]]; then
  date_beg=${date_beg:0:6}01
  date_end=$(date -d "${date_beg} + 1 month - 1 day" +"%C%y%m%d" )
fi

if [[ ${#date_beg} -eq 4 || ${#date_end} -eq 4 ]]; then
  date_beg=${date_beg:0:6}0101
  date_end=$(date -d "${date_beg} + 1 year - 1 day" +"%C%y%m%d" )
fi

echo -e "\n${var_name:+"-${var_name}: "}${date_beg}->${date_end}\n"


# directories
export DIR_SRC="/home/ar0s/PROD_ERA5_ABL"
export DIR_SAVE="/ec/res5/project/mercator/ATMO_FORCINGS/ERA5_ABL50_F320_v1/daily/1h/TPOTL1"
export DIR_NEMO="/home/ar0s/SRC/NEMO/main/tools/ABL_TOOLS"
export SCRATCH_DIR=${SCRATCHDIR}
export VLEVEL="L107-137"   # L107-137
export GRID=$(sed -rn "s/^ +grid += +([[:graph:]]+),.*/\1/p" ${DIR_SRC}/mars_inst3D_ana.req.base)
export BASE_NAME="ERA5_GLO_TLAUTO_IGNONE_G${GRID/N/F}_ana01h"
echo "-SCRATCH_DIR: ${SCRATCHDIR}"


# scripts
./check_if_done.sh   ${date_beg} ${date_end} ${var_name}; [ $? -eq 0 ] && exit 0
./subjob_mars.sh     ${date_beg} ${date_end}            ; [ $? -eq 1 ] && exit 1
./subjob_cdogrid.sh  ${date_beg} ${date_end}            ; [ $? -eq 1 ] && exit 1
if [[ -z "${var_name}" || ${var_name} =~ "hpg" ]]; then
  ./subjob_ablhpg.sh ${date_beg} ${date_end}            ; [ $? -eq 1 ] && exit 1
fi
./subjob_ablvint.sh  ${date_beg} ${date_end} ${var_name}; [ $? -eq 1 ] && exit 1
if [ -z "${var_name}" ]; then
  ./subjob_cdosplit.sh ${date_beg} ${date_end}          ; [ $? -eq 1 ] && exit 1
fi
./subjob_cdomiss.sh  ${date_beg} ${date_end} ${var_name}; [ $? -eq 1 ] && exit 1
./subjob_ncochunk.sh ${date_beg} ${date_end} ${var_name}; [ $? -eq 1 ] && exit 1
./move_to_perm.sh    ${date_beg} ${date_end} ${var_name}; [ $? -eq 1 ] && exit 1


exit 0
