#!/bin/bash
#
# dselector.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: ./dselector.sh <inputfile.root>"
    echo "   where <inputfile.root> is the name of the input ROOT tree file."
    exit 1
}

nthreads=1
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=1

if [ $# = 1 ]; then
    if echo $1 | grep -q '.root$'; then
        infile=$1
    else
        usage
    fi
else
   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"

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

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"

./dselector.py $infile || exit_with_error $? "hd_root crashed"

outfile=$(echo $infile | sed "s/_tree_.*.root/dselector.root/") || exit_with_error $? "cannot form output filename"
gfal-copy -f file:///`pwd`/dselector.root $httpsURL/$outfile || \
gfal-copy -f file:///`pwd`/dselector.root $gridftpURL/$outfile || \
gfal-copy -f file:///`pwd`/dselector.root $xrootdURL/$outfile || \
exit_with_error $? "failed to save output file $outfile"
rm -f *.hddm *.astate *.root *.config setup.sh
