#!/bin/bash

set +xv

date=$1
day_end=$( date -d "${date:4:2}/1 + 1 month - 1 day" +"%d" )
date_end=${date:0:6}${day_end}
ym=${date:0:6}
day_nb=$(( ($(date -d "${date_end}H00 + 1 day" +%s) - $(date -d "${ym}01H00" +"%s") )/(60*60*24) ))

p2D="/ec/res4/scratch/ar0s/ERA5/NC_F320/${ym}/surf2D_ERA5_L1_GLO_TLAUTO_IGNONE_GF320reg_ana01h_${date}.nc"
p3D="/ec/res4/scratch/ar0s/ERA5/NC_F320/${ym}/inst3D_ERA5_L107-137_GLO_TLAUTO_IGNONE_GF320reg_ana01h_${date}.nc"
pmsk="/ec/res4/scratch/ar0s/ERA5/NC_F320/${ym}/mask0_ERA5_GLO_TLAUTO_IGNONE_GF320_NNint_20120101.nc"
ln -sf /ec/res4/scratch/ar0s/ERA5/NC_F320/mask0_ERA5_GLO_TLAUTO_IGNONE_GF320_NNint_20120101.nc /ec/res4/scratch/ar0s/ERA5/NC_F320/${ym}/.

f2D=$(basename $p2D)   ; d2D=$(dirname $p2D)
f3D=$(basename $p3D)   ; d3D=$(dirname $p3D)
fmsk=$(basename $pmsk) ; dmsk=$(dirname $pmsk)
fabl=${f3D/inst3D/abl} ; fabl=${fabl/L107-137/L50Z10}

if [ ! -s ${d2D}/${fabl} ]; then
  while [ $(squeue -u $USER -h -t pending,running -r | wc -l) -eq 100 ]; do echo "sleeping..."; sleep 10; done 
  if [ ${date} -eq ${date_end} ]; then echo "wait..."; w="--wait"; fi
  sbatch ${w} --job-name=ablvint_${date} /home/ar0s/PROD_ERA5_ABL/job_ablvint.sbatch $p2D $p3D $pmsk
  if [ -n "${w}" ]; then
    file_nb=$( eval "ls ${d2D}/${fabl/${date}/${ym}??} 2>/dev/null" | wc -l )
    if [ ${day_nb} -eq ${file_nb} ]; then exit 0; else echo "ERROR"; exit 1; fi
  fi
fi
