#!/bin/bash
set -e

# E2E test for background
# Setup: Point away from source to test background generation for time and
# event triggered readout.
# Output: event file for background comparison

# NOTE: running this script with the option -r runs it in reference mode,
# generating new reference data

### Setup
export SIXTE_USE_PSEUDO_RNG=1
. ./data/scripts/setup/setup_e2e.sh

# Test parameters
xml_dir=data/instruments/dummy/
xml_timemode=${xml_dir}/default_inst_sixtesim.xml
xml_eventmode=${xml_dir}/default_eventreadout_sixtesim.xml
# Point away from source
RA=3
Dec=3
exposure=1000
Seed=0
###

# get mode in which we're running
refmode=0
while getopts ":r" arg
do
  case "$arg" in
    r)
      refmode=1
  esac
done

if [ $refmode == 1 ]
then
  echo "Running in reference mode"
else
  echo "Running in test mode"
fi

mkdir -p ${output_dir}

xmllist=("$xml_timemode" "$xml_eventmode")
testlist=("pha_timemode" "pha_eventmode")

for ii in "${!xmllist[@]}"
do
  xmlfile="${xmllist[$ii]}"
  testname="${testlist[$ii]}"

  if [ $refmode == 1 ]
  then
    base="ref_background_e2e_${testname}"
  else
    base="background_e2e_${testname}"
  fi

  $SIXTE/bin/sixtesim \
    Simput=${simput_dir}/crab/mcrab_RA0.00Dec0.00.fits \
    XMLFile=${xmlfile} \
    RA=${RA} Dec=${Dec} \
    Exposure=${exposure} \
    Prefix=${output_dir} \
    EvtFile=${base}_evt.fits \
    Background=y \
    clobber=y \
    progressbar=y \
    chatter=3 \
    Seed=${Seed}

  # Comparison
  if [ $refmode == 0 ]
  then
    simdata_dir=./output/
    refdata_dir=./data/refdata/

    ftdiff \
      infile1=${simdata_dir}/${base}_evt.fits \
      infile2=${refdata_dir}/ref_${base}_evt.fits \
      cmpdata=yes caldsum=yes reltol=0 tolerance=0
  fi
done

unset SIXTE_USE_PSEUDO_RNG

### Test finished successfully
printf "\n%s executed successfully\n" "${0}"
exit 0