#!/bin/bash

# Usage statement
if [[ ( $@ == "--help") || $@ == "-h" ]]; then
  echo "Usage: $0 <path_to_recipe> <path_to_script>"
  exit 0
fi

# Check recipe and script
recipe=$1
script=$2
# recipe=recipes/tests/recipe_seasonal_example.yml
# script=modules/test_parallel_workflow.R

if [ ! -f "$recipe" ]; then
  echo "Could not file recipe file: $recipe"
  exit 0
fi

if [ ! -f "$script" ]; then
  echo "Could not find script file: $script"
  exit 0
fi

# Define tmp file to store necessary information
tmpfile=$(mktemp ${TMPDIR-/tmp}/SUNSET.XXXXXX)

# Create outdir and split recipes
source MODULES
Rscript split.R ${recipe} --tmpfile $tmpfile
codedir=$( head -1 $tmpfile | tail -1 )
outdir=$( head -2 $tmpfile | tail -1 )

rm $tmpfile

# Create directory for slurm output
# logdir=${TMPDIR-/tmp}/SUNSET_slurm_logs_$(whoami)/
logdir=${codedir}/out-logs/slurm_logs/
mkdir -p $logdir
echo "Slurm job logs will be stored in $logdir"

# Launch one job per atomic recipe
cd $codedir
job_number=0
for atomic_recipe in ${outdir}/logs/recipes/atomic_recipe_??.yml; do
  # sbatch example_scripts/slurm_templates/run_parallel_workflow.sh ${script} ${atomic_recipe}
  job_number=$(($job_number + 1))
  job_name=$(basename $outdir)_$(printf %02d $job_number)
  outfile=${logdir}/run-${job_name}.out
  errfile=${logdir}/run-${job_name}.err
  sbatch --output=$outfile --error=$errfile example_scripts/slurm_templates/run_parallel_workflow.sh ${script} ${atomic_recipe}
done
