#!/bin/bash
#
# hd_react.sh - runs a standard omega(3pi) ReactionFilter analysis
#               over reconstructed simulation data.
#
# author: richard.t.jones at uconn.edu
# version: may 31, 2022

function usage() {
    echo "Usage: ./hd_react.sh <inputfile.hddm>"
    echo "   where <inputfile.hddm> is the name of the input hddm file."
    exit 1
}

nthreads=8
nskip=0
nevents=1000000000
httpURL="http://grinch.phys.uconn.edu:2880/Gluex/simulation/omega3pi"
httpsURL="https://grinch.phys.uconn.edu:2843/Gluex/simulation/omega3pi"
gridftpURL="gsiftp://nod29.phys.uconn.edu/Gluex/simulation/omega3pi"
xrootdURL="root://nod29.phys.uconn.edu/Gluex/simulation/omega3pi"
wget="wget --ca-directory /etc/grid-security/certificates"
BATCH_MODE=0

if [ $# = 1 ]; then
    if echo $1 | grep -q '.hddm$'; then
        infile=$1
    else
        usage
    fi
else
   echo usage
fi

function exit_with_error() {
    echo "Quitting after error, code=$1"
    if [[ "x$2" != "x" ]]; then
        echo "Reason: $2"
    fi
    ls -l
    rm -f *.hddm *.astate *.root *.config setup.sh
	exit $1
}

$wget $httpURL/setup.sh 2>/dev/null || exit_with_error $? "cannot fetch setup.sh from web server"
$wget $httpURL/hd_react.config 2>/dev/null || exit_with_error $? "cannot fetch hd_react.config from web server"

#source setup.sh || exit_with_error $? "setup.sh script failed"
#export JANA_CALIB_CONTEXT="variation=mc calibtime=2021-05-01"

if [ 1 = 0 ]; then
gfal-copy -f $httpURL/$infile file:///`pwd`/$infile || \
gfal-copy -f $gridftpURL/$infile file:///`pwd`/$infile || \
gfal-copy -f $xrootdURL/$infile file:///`pwd`/$infile || \
exit_with_error $? "failed to fetch input file $infile"
fi

hd_root="hd_root --config=hd_react.config \
                 -PJANA:BATCH_MODE=$BATCH_MODE \
                 -PNTHREADS=$nthreads \
                 -PEVENTS_TO_SKIP=$nskip \
                 -PEVENTS_TO_KEEP=$nevents \
                 -PTHREAD_TIMEOUT_FIRST_EVENT=3600 \
                 -PTHREAD_TIMEOUT=600 \
                 --nthreads=$nthreads"
#                 -PCOMBO:DEBUG_LEVEL=99 \
#valgrind --error-limit=no --suppressions=valgrind.supp --gen-suppressions=all $hd_root $1
#valgrind --vgdb=yes --vgdb-error=0 --error-limit=no --suppressions=valgrind.supp $hd_root $1
#valgrind --error-limit=no --gen-suppressions=all $hd_root $1

$hd_root $* || exit_with_error $? "hd_root crashed"
exit 0;

prefix=$(echo $infile | sed 's/rest.hddm$//') || exit_with_error $? "cannot form output filename"
for rootout in $(ls *.root); do
    outfile=$(echo $rootout | sed "s/^/$prefix/")
    gfal-copy -f file:///`pwd`/$rootout $httpsURL/$outfile || \
    gfal-copy -f file:///`pwd`/$rootout $gridftpURL/$outfile || \
    gfal-copy -f file:///`pwd`/$rootout $xrootdURL/$outfile || \
    exit_with_error $? "failed to save output file $outfile"
done
rm -f *.hddm *.astate *.root *.config setup.sh
