#!/bin/bash
# -*- mode: sh; c-basic-offset: 4; tab-width: 8; indent-tabs-mode: nil -*-
# vi: set shiftwidth=4 tabstop=8 softtabstop=4 expandtab:
# :indentSize=4:tabSize=8:noTabs=true:
# vim: filetype=sh

# ---- error handling
set -o errexit;
set -o posix;
set -o pipefail;
set -o errtrace;
unexpected_error() {
    local errstat=$?
    echo "${g_prog:-$(basename "$0")}: Error! Encountered unexpected error at 'line $(caller)', bailing out..." 1>&2
    exit $errstat;
}
trap unexpected_error ERR;

# Force the path to only what we need, saving off the original path
PATH_ORIG=$PATH;
PATH=/usr/bin:/bin

g_prog=$(basename "$0");
g_progdir=$(dirname "$0");
g_progdir_abs=$(dirname "$(readlink -f "$0")");

# ---- global env

. "$g_progdir_abs/../../private/runtime-common/lib/globalenv.ish"


g_eid_subread_dataset="$1"

# ---- error functions
merror() {
    echo "$g_prog: Error! ""$@" 1>&2;
    exit 1;
}
minterror() {
    echo "$g_prog: Internal Error! ""$@" 1>&2;
    exit 1;
}
mwarn() {
    echo "$g_prog: Warning! ""$@" 1>&2;}

# ---- globals

rootdir="$g_progdir/../../../.."
rootdir_abs="$g_progdir_abs/../../../.."

g_canneddata_dir="$rootdir_abs/current/bundles/smrtinub/current/private/pacbio/canneddata"

g_pbcromwell_exe="$rootdir_abs/current/bundles/smrttools/current/smrtcmds/bin/pbcromwell"

g_cromwell_cli_conf="$rootdir_abs/userdata/generated/config/cromwell_cli.conf"

g_eid_ref_dataset="$g_canneddata_dir/referenceset/lambdaNEB/referenceset.xml"

# ---- main

if [[ -z "$g_eid_subread_dataset" ]]; then
    echo "Using default canned data SubreadSet..."
    g_eid_subread_dataset="$g_canneddata_dir/lambdaTINY/m54026_181219_010936_tiny.subreadset.xml"
fi

datestamp=$(date --iso-8601=seconds --utc)
outdir="local_sat_output_${datestamp}"

echo
echo "Running local tiny-lambda SAT test..."
# use the cromwell_cli.conf to pick up user settings for nproc, maxchunks,...
cmdline="\"$g_pbcromwell_exe\" run pb_sat --config \"$g_cromwell_cli_conf\" -e \"$g_eid_subread_dataset\" -e \"$g_eid_ref_dataset\" --backend Local --output-dir \"$outdir\""
echo "  Executing: $cmdline"
stat=0
eval "$cmdline" || stat=$?

if [[ $stat -eq 0 ]]; then
    echo "Job successful."
else
    merror "job failed with exit code ${stat}"
fi

exit 0
