#!/bin/bash
# script sending slurm script to queue for the specified times. 
# Fina Fix
#
##########################
printf "* loading cdo\n"
module purge
module load cdo/2.1.0-gcc-12.2.0-b72jy3p   

OUTDIR="/outdir/" #SPECIFY
INDIR="/era5_indir/"
INDIR2="/era5_indir_interpBLH/"

STARTYEAR=2022
ENDYEAR=2022
STARTMONTH=5
ENDMONTH=12
counter=0


# loop through all wanted years
for YEAR in $(seq $STARTYEAR $ENDYEAR); do
	# check for leap year
	if (( ($YEAR % 4 == 0 && $YEAR % 100 != 0) || ($YEAR % 400 == 0) )); then
                leap_year=0  # Leap year
        else
                leap_year=1  # Not a leap year
        fi
	# loop through all months
        for MONTH in $(seq $STARTMONTH $ENDMONTH); do
		# find number of days in month
                if [[ ${MONTH} -eq 1 || ${MONTH} -eq 3 || ${MONTH} -eq 5 || ${MONTH} -eq 7 || ${MONTH} -eq 8 || ${MONTH} -eq 10 || ${MONTH} -eq 12 ]]; then
                        days_in_month=31
                elif [[ ${MONTH} -eq 4 || ${MONTH} -eq 6 || ${MONTH} -eq 9 || ${MONTH} -eq 11 ]]; then
                        days_in_month=30
		else
                        # Check for February
                        if [[ $leap_year -eq 0 ]]; then
                                days_in_month=29
                        else
                                days_in_month=28
                        fi
                fi
		# for each day in month send slurm scrut to scheduler
		if [ ${counter} == 0 ]; then
			printf " * calling prepare_data.slurm for ${YEAR}-${MONTH} days: ${days_in_month}\n"
	          	msg=`sbatch --array=1-${days_in_month} 01_prepare_data.slurm ${YEAR} ${MONTH} ${OUTDIR} ${INDIR} ${INDIR2}`
	          	jid=`echo $msg | grep -oP '\d+$'`
		else
		   	printf " * calling prepare_data.slurm for ${YEAR}-${MONTH} days: ${days_in_month}\n"
	           	msg=`sbatch --array=1-${days_in_month} --dependency=afterok:${jid}  01_prepare_data.slurm ${YEAR} ${MONTH} ${OUTDIR} ${INDIR} ${INDIR2}`
	           	jid=`echo $msg | grep -oP '\d+$'`
		fi
		let counter=$counter+1

	done
done	
