#!/bin/bash

# Driver script for tests of LALApps CW codes in lalapps/src/pulsar/
set -e
echo "--- Test compiler is $0 ---"
echo

# Parse command line
skip_longtest="$1"
shift
echo "skip_longtest=${skip_longtest}"
script_extn="$1"
echo "script_extn=${script_extn}"
shift
test_extra_files="$1"
echo "test_extra_files=${test_extra_files}"
shift
test_script_runner="$1"
echo "test_script_runner=${test_script_runner}"
shift
flags=""
while [ "X$2" != X ]; do
    flags="${flags} '$1'"
    shift
done
test="$1"
echo "flags=${flags}"
echo "test=${test}"
echo

# Check for required environment variables
if [ "X${LAL_TEST_SRCDIR}" = X ]; then
  echo "LAL_TEST_SRCDIR is not set"
  exit 1
fi
if [ "X${LAL_TEST_BUILDDIR}" = X ]; then
  echo "LAL_TEST_BUILDDIR is not set"
  exit 1
fi

# Fix path to test script runner
case "${test_script_runner}" in
    /*)
        ;;
    *)
        test_script_runner="../${test_script_runner}"
        ;;
esac

# Test script name, location, and extension
script_name=$(expr "X${test}" : "X.*/\(test[^/]*\)\.${script_extn}$")
if [ "X${script_name}" = X ]; then
  echo "Could not parse name of test script from '${test}'"
  exit 1
fi
script="${LAL_TEST_SRCDIR}/${script_name}.${script_extn}"
if [ ! -f "${script}" ]; then
  echo "Test script '${script}' does not exist"
  exit 1
fi
if [ -x "${script}" ]; then
  echo "Test script '${script}' should not be executable"
  exit 1
fi
case "${script_extn}" in
    sh)
        cmdline="time ${test_script_runner} /bin/bash ${flags} -c 'set -e; source ${script}'"
        ;;
    py)
        cmdline="time ${test_script_runner} ${PYTHON} ${flags} '${script}'"
        ;;
    *)
        echo "Test script '${script}' does not have a recognised extension"
        exit 1
        ;;
esac

## Check whether to skip long test
if [ "X${skip_longtest}" != X ]; then
    echo "Skipping long test '${script_name}'; LONGTESTS must be defined to run test"
    exit 77
fi

# Create directory for test; removes old directory unless NONEWTESTDIR is set
testdir="${LAL_TEST_BUILDDIR}/${script_name}.testdir"
if [ "X${NONEWTESTDIR}" = X ]; then
    rm -rf "${testdir}"
    if [ -d "${testdir}" ]; then
        echo "Could not remove test directory '${testdir}'"
        exit 1
    fi
fi
mkdir -p "${testdir}"

# Extract any reference results, and check validity (unless NONEWTESTDIR is set)
reftarball="${LAL_TEST_SRCDIR}/${script_name}.tar.gz"
if [ -f ${reftarball} ]; then
    echo "Extracting reference tarball ${reftarball}"
    cd "${testdir}"
    tar xf ${reftarball}
    for file in $(find . -type f); do
        [ "X${NONEWTESTDIR}" = X ] && (
            case "${file}" in
                *.txt)
                    grep UNCLEAN "${file}"
                    ;;
                *.fits)
                    "${LAL_TEST_BUILDDIR}/../FITSTools/lalpulsar_fits_header_list" "${file}" | grep UNCLEAN
                    ;;
                *)
                    exit 1
                    ;;
            esac
        ) && {
            echo "File '${file}' appears to have been built from a git checkout of LALSuite with uncommitted changes, and therefore is not reproducible"
            exit 1
        }
    done
    cd "${LAL_TEST_BUILDDIR}"
else
    echo "No reference tarball ${reftarball}"
fi
echo

# Create stubs to any executables in lalapps/src/pulsar/ used by test script, and set PATH
tested_logfile="${LAL_TEST_BUILDDIR}/.tested_log_${script_name}.log"
echo "# ${tested_logfile}" > "${tested_logfile}"
for execfile in $(find "${LAL_TEST_BUILDDIR}/.." "${LAL_TEST_SRCDIR}/.." -maxdepth 2 -type f -perm -u+x); do
    execname=$(expr "X${execfile}" : "X.*/\([^/]*\)$")
    stubfile="${testdir}/${execname}"
    div_regex='[^A-Za-z0-9_]'
    if cat "${script}" | sed 's/#.*$//g;s/^/ /;s/$/ /' | grep -q "${div_regex}${execname}${div_regex}"; then

        # Stub script logs that this executable has been called from a test script
        echo "#!/bin/sh" > "${stubfile}"
        echo "case \"\$@\" in" >> "${stubfile}"
        echo "--help|-h|--version|-v) ;;" >> "${stubfile}"
        echo "*) echo 'tested ${execname}' >> '${tested_logfile}' ;;" >> "${stubfile}"
        echo "esac" >> "${stubfile}"
        echo "exec '${execfile}' \"\$@\"" >> "${stubfile}"
        chmod +x "${stubfile}"

    fi
done
export PATH="${testdir}:${PATH}"
echo "PATH=${PATH}"
echo

# Create links to any extra files
for extrafile in ${test_extra_files}; do
    linkfile="${testdir}/${extrafile}"
    [ -h "${linkfile}" ] || ln -s "${LAL_TEST_SRCDIR}/${extrafile}" "${linkfile}"
done

# List contents of test directory
echo "--- Running test in directory ${testdir} ---"
echo
ls -l "${testdir}"
echo

# Run test in test directory
echo "--- Running test ${test}: ${cmdline} ---"
echo
cd "${testdir}"
set +e
(
    export LAL_TEST_SRCDIR=/dev/null/
    export LAL_TEST_BUILDDIR=/dev/null/
    export srcdir=/dev/null/
    export builddir=/dev/null/
    eval ${cmdline}
)
status=$?
set -e
cd "${LAL_TEST_BUILDDIR}"
echo
case $status in
    0)
        echo "--- Test ${test} ran successfully ---"
        ;;
    77)
        echo "--- Test ${test} was skipped ---"
        ;;
    *)
        echo "--- Test ${test} exited with status ${status} ---"
        NOCLEANUP=1
        ;;
esac
echo

# Move any junit XML files out of test directory
for junitxml in `find ${testdir} -name 'junit-*.xml'`; do
    mv -f "${junitxml}" "${LAL_TEST_BUILDDIR}"
done

# Remove test directory, unless NOCLEANUP is set
if [ "X${NOCLEANUP}" = X ]; then
    echo "--- Removing directory ${testdir} ---"
    echo
    rm -rf "${testdir}"
fi

# Return test script exit status
exit ${status}
