#!/bin/bash

CONFIG="$1"
CMD="$2"
JOBNAME="pbjelly-$3"
STDOUT="$4"
STDERR="$5"
shift 5

function from_config()
{
    local STAGE="$1"

    for VAR in PARTITION NUM_CORES TIME MEMORY; do
        eval $VAR="$(jq -r "(.__default__ + .$STAGE) | .${VAR,,}" "$CONFIG")"
    done
}

PARTITION="batch"
NUM_CORES="1"
TIME="01:00:00"
MEMORY="1G"

if [[ $(basename "$CMD") =~ ^([a-z]+)_ ]]; then
    from_config "${BASH_REMATCH[1]}"
else
    echo "unexpected \${CMD}: $CMD" >&2
    exit 1
fi

sed -i '
/#!\/bin\/bash/ a\
echo "jobid: \$SLURM_JOB_ID"
/SLURM_JOB_ID/ d
' "$CMD"

sbatch \
    -p "$PARTITION" \
    -c "$NUM_CORES" \
    --time="$TIME" \
    --mem="$MEMORY" \
    -J "$JOBNAME" \
    -o "$STDOUT" \
    -e "$STDERR" \
    "$CMD" 2>&1
