#!/bin/bash

# Main Job submission script for RNA seq analysis
# If it succeeds it will return exit code 0
# Fails with exit code 1

if [ "$#" -ne 1 ] ; then
	echo "Usage: gs_submit <config-file>"
	exit 1
fi

tmpfile1=$(mktemp /tmp/slurm_idx_job.XXXXXX)
tmpfile2=$(mktemp /tmp/slurm_stsal_job.XXXXXX)
echo "Creating job file: $tmpfile"
output=$(python3 -m globalsearch.control.gs_prepare $1)

if [ $? == 0 ] ; then
    algo=$(echo "$output" | tail -1)
    if [ $algo == 'star_salmon' ]; then
	echo "Running STAR/Salmon workflow"
        python3 -m globalsearch.rnaseq.make_star_idx_job $1 > $tmpfile1 && RES1=$(sbatch --parsable $tmpfile1) && \
            python3 -m globalsearch.rnaseq.make_star_salmon_job $1 > $tmpfile2 && RES2=$(sbatch --dependency=afterok:$RES1 --parsable $tmpfile2) && \
	    sbatch -o "/tmp/%j.out" --dependency=afterany:$RES2 --wrap "python3 -m globalsearch.rnaseq.post_star_salmon $1"
    elif [ $algo == 'kallisto' ]; then
	echo "Running Kallisto workflow"
        python3 -m globalsearch.rnaseq.make_kallisto_job $1 > $tmpfile2 && RES=$(sbatch --parsable $tmpfile2) && echo $RES
    else
	echo "UNSUPPORTED ALGORITHM: $algo"
	exit 1
    fi
else
    echo "ERROR WHILE PREPARING"
    echo "$output"
    exit 1
fi

#rm -f $tmpfile1 $tmpfile2
