#!/bin/bash -x
# author wbarrett -- modified from query_database script

pwd

echo 'Reprocessing AIM CIPS IDL'

# kill idl if script is aborted 
function trap_handler
{
    echo "cleaning up idl after SIGTERM"
    kill -9 $idlpid
    exit 0
}
trap 'trap_handler' SIGTERM

# Enable the script that sets the environment variables for the machine that we
#   are on, and then execute it. Most of the variables like IDL_DIR, JAVA, SYBASE,
#   etc. are exactly what we want for our test environment.
# Some however must be changed below.
chmod +x $WORKSPACE/sds/common/scripts/setup_science_data_system.sh
source $WORKSPACE/sds/common/scripts/setup_science_data_system.sh

# This verifies that the script ./sds/common/scripts/setup_science_data_system.sh has
#   correctly defined IDL_DIR -- if not everything forward will fail.
# IDL_DIR determines what version of IDL is being used
if [ -z ${IDL_DIR} ]; then
  echo "killing build because IDL_DIR is not set"
  exit
fi

# Run the IDL setup script for the version we are using
source $IDL_DIR/bin/idl_setup.bash
echo "IDL_DIR = $IDL_DIR"

# ./sds/common/scripts/setup_science_data_system.sh sets things correctly for production
# The next line is very important because it defines a commonly used path relative to the Jenkins
#  build rather than in absolute terms
aimsds=$WORKSPACE/sds
echo "aimsds = $aimsds"
# Redefine the environment variables that must be different for test purposes
IDL_PATH="<IDL_DEFAULT>:+.:+${aimsds}:+/data_systems/tools/idl_libraries/datetime:+/data_systems/tools/idl_libraries/misc:+/data_systems/tools/IdlDbInterface/idl"
echo "IDL_PATH = $IDL_PATH"
# And since the path $aimsds has changed, IDL_DLM_PATH must also change
if [ "$IDL_DLM_PATH"X = "X" ]; then
   export IDL_DLM_PATH=\<IDL_DEFAULT\>
fi
echo "IDL_DLM_PATH = $IDL_DLM_PATH"

# Now run the tests
mkdir -p ./logs
$IDL_DIR/bin/idl <./test/idl/run_level_1a_reprocessing >>./logs/reprocessing.log 2>&1 &

pid=$!
idlpid=`pgrep -P $pid`
wait $pid
