#!/bin/bash

set +xv


# ARGUMENTS
date_beg=$1
date_end=$2
nbday=$(( ($(date -d "${date_end}H00 + 1 day" +%s) - $(date -d "${date_beg}H00" +"%s") )/(60*60*24) ))
if [ -n "$3" ]; then var_name=$3; fi


for d in $(seq -f "%02g" 0 $((nbday-1))); do

  # TIME
  date=$(date -d "${date_beg}H00 + ${d} days" +"%C%y%m%d")
  ym=${date:0:6}

  # DIRECTORIES & FILES
  p2D="${SCRATCH_DIR}/NC_${GRID/N/F}/${ym}/surf2D_L1_${BASE_NAME}_${date}.nc"
  p3D="${SCRATCH_DIR}/NC_${GRID/N/F}/${ym}/inst3D_${VLEVEL}_${BASE_NAME}_${date}.nc"
  pmsk="${SCRATCH_DIR}/NC_${GRID/N/F}/${ym}/mask0_${BASE_NAME%_ana*}_NNint_20120101.nc"
  f2D=$(basename $p2D)   ; d2D=$(dirname $p2D)
  f3D=$(basename $p3D)   ; d3D=$(dirname $p3D)
  fmsk=$(basename $pmsk) ; dmsk=$(dirname $pmsk)
  fabl=${f3D/inst3D/abl} ; fabl=${fabl/${VLEVEL}/L50Z10}
  fhpg=${f3D/inst3D/hpg}

  if [ ! -s ${d2D}/${var_name:+"${var_name}_"}${fabl} ]; then
  
    if [[ -s ${p2D} && -s ${p3D} ]] && [[ -s ${d2D}/${fhpg} || -n "${var_name}" ]]; then
      while [ $(squeue -u $USER -h -t pending,running -r | wc -l) -ge 90 ]; do echo "sleeping..."; sleep 10; done
      sbatch --job-name=ablvint${var_name:+"_${var_name}"}_${date} --export=SCRATCH_DIR=${SCRATCH_DIR},VLEVEL=${VLEVEL},BASE_NAME=${BASE_NAME},DIR_NEMO=${DIR_NEMO},GRID=${GRID} ${DIR_SRC}/job_ablvint.sbatch ${date} ${var_name}
    else
      echo "ABL_VINT ERROR: input files not found"; exit 1
    fi
  
  fi
  
  while [[ ${date} -eq ${date_end} && $(squeue -u $USER -h -t pending,running -r -o '%20j' | grep ablvint${var_name:+"_${var_name}"}_${ym} | wc -l) -gt 0 ]]; do echo "sleeping..."; sleep 10; done
  
  if [ ${date} -eq ${date_end} ]; then
    file_nb=$( eval "ls ${d2D}/${var_name:+"${var_name}_"}${fabl/${date}.nc/${ym}{${date_beg:6:2}..${date_end:6:2}}}.nc 2>/dev/null" | wc -l )
    if [ ${nbday} -eq ${file_nb} ]; then
      echo "-ABL_VINT: OK"
    else 
      echo "-ABL_VINT: ERROR"
      exit 1
    fi
  fi

done


exit 0
