#!/bin/bash
#
# gen_sim_smear.sh - combines the initial steps of event generation using genr8
#                    with simulation using hdgeant4 and smearing with mcsmear.
#
# author: richard.t.jones at uconn.edu
# version: may 31, 2022

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

runno=50986
nevents=100
nthreads=1
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://nod28.phys.uconn.edu/Gluex/simulation/omega3pi"
wget="wget --ca-directory /etc/grid-security/certificates"

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

random_number=$(echo $outfile | md5sum)
rseed1=$(echo $random_number | python -c 'import sys; print(int("0x" + sys.stdin.read().split()[0], 0) % 37930909)')
rseed2=$(echo $random_number | python -c 'import sys; print(int("0x" + sys.stdin.read().split()[0], 0) % 710947765)')
rseed3=$(echo $random_number | python -c 'import sys; print(int("0x" + sys.stdin.read().split()[0], 0) % 1458260021)')

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

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

source setup.sh || exit_with_error

genr8 -s$random_number -r$runno -M$nevents -Agenr8.ascii < genr8.config || exit_with_error $? "genr8 crashed"
genr8_2_hddm genr8.ascii || exit_with_error $? "genr8_2_hddm crashed"
rm genr8.ascii

sed -i "s/^RNDM.*/RNDM $rseed2 $rseed3/" control.in || exit_with_error $? "RNDM card not found in control.in"
sed -i "s/^RUN[NG].*/RUNNO $runno/" control.in || exit_with_error $? "RUN card not found in control.in"
sed -i "s/^INFI.*/INFILE 'genr8.hddm'/" control.in || exit_with_error $? "INFI card not found in control.in"
sed -i "s/^OUTF.*/OUTFILE '$outfile'/" control.in || exit_with_error $? "OUTF card not found in control.in"
sed -i "s/^TRIG.*/TRIG $nevents/" control.in || exit_with_error $? "TRIG card not found in control.in"

#export CCDB_CONNECTION="sqlite:////cvmfs/oasis.opensciencegrid.org/gluex/private/ccdb_2020-12-07.sqlite"
export JANA_CALIB_URL=$CCDB_CONNECTION
export JANA_GEOMETRY_URL="ccdb://GEOMETRY/main_HDDS.xml"
export JANA_CALIB_CONTEXT="variation=mc"
#export JANA_CALIB_CONTEXT="variation=fdcwires_test"

time hdgeant4 -t $nthreads || exit_with_error $? "hdgeant4 crashed"
rm control.in setup.sh genr8.hddm

noises=$(ls root://nod25.phys.uconn.edu/Gluex/rawdata/random_triggers/recon-2018_08-ver02 | grep run0509[567])
randoms=""
for noise in $noises; do
    randoms="$randoms root://nod25.phys.uconn.edu/Gluex/rawdata/random_triggers/recon-2018_08-ver02/$noise:1"
done

echo mcsmear -d -Pprint -PJANA:BATCH_MODE=$BATCH_MODE -PTHREAD_TIMEOUT_FIRST_EVENT=3600 -PTHREAD_TIMEOUT=600 $outfile $randoms
mcsmear -d -Pprint -PJANA:BATCH_MODE=$BATCH_MODE -PNTHREADS=$nthreads -PEVENTS_TO_KEEP=$nevents -PTHREAD_TIMEOUT_FIRST_EVENT=3600 -PTHREAD_TIMEOUT=600 $outfile $randoms

smearedfile=$(echo $outfile | sed 's/.hddm$/_smeared.hddm/')
gfal-copy -f file:///`pwd`/$smearedfile $httpsURL/$smearedfile || \
gfal-copy -f file:///`pwd`/$smearedfile $gridftpURL/$smearedfile || \
gfal-copy -f file:///`pwd`/$smearedfile $xrootdURL/$smearedfile || \
exit_with_error $? "failed to save output"
rm -f *.hddm *.root *.ascii genr8.config control.in setup.sh
