#!/bin/bash

# set -vx

# 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 /tmp/test_split.XXXXXX)

# Create outdir and split recipes
source MODULES
Rscript split.R ${recipe} | tee $tmpfile
outdir=$( tail -n 1 $tmpfile | sed 's/"//g' )
outdir=($outdir)

rm $tmpfile

# Create directory for slurm output
logdir=/esarchive/scratch/$(whoami)/tmp/auto-s2s-logs
mkdir -p $logdir
echo "Slurm job logs will be stored in $logdir"

# Launch one job per atomic recipe
for atomic_recipe in ${outdir[1]}/logs/recipes/atomic_recipe_??.yml; do
  sbatch example_scripts/slurm_templates/run_parallel_workflow.sh ${script} ${atomic_recipe}
done
