#!/usr/bin/env bash

###############################################################################
# $1: the ctest directory
# $2: whether to run the test (TEST) or generate ref data (GENERATE_REF)
# $3: the current test's name
# $4: the current test's parameter file
# $5: the current test's sequence file (if any)
# $6: end generation
# $7: the aevol_create binary (used to generate the test's input)
# $8: the aevol_run binary (used to generate the test's input)
# $9: the aevol_post_lineage binary to be tested
###############################################################################

CTEST_DIR=$1
TEST_OR_GENERATE=$2
CUR_TEST_FULL_NAME=$3
CUR_TEST_PARAM_FILE=$4
CUR_TEST_SEQ_FILE=$5
END_GENER=$6
AEVOL_CREATE=$7
AEVOL_RUN=$8
AEVOL_EXTRACT_GENOMES=$9

CUR_TEST_DIR=$CTEST_DIR/$CUR_TEST_FULL_NAME
CUR_TEST_INPUT_DIR="test_input"

# cd into the test's directory (create if not exists)
if [ ! -e "$CUR_TEST_DIR" ]; then mkdir "$CUR_TEST_DIR" || exit 1; fi
cd "$CUR_TEST_DIR" || exit 1

# If we're generating the reference data, we first need to generate the input
# of the test (if any)
if [ "$TEST_OR_GENERATE" = "GENERATE_REF" ]; then
  # make sure there is an empty $CUR_TEST_INPUT_DIR and cd into it
  rm -rf "${CUR_TEST_INPUT_DIR:?}/"
  mkdir "$CUR_TEST_INPUT_DIR" || exit 1
  cd "$CUR_TEST_INPUT_DIR" || exit 1

  # run $AEVOL_CREATE
  CMD="$AEVOL_CREATE $CUR_TEST_PARAM_FILE"
  echo "running $CMD from $PWD..."
  $CMD || exit 1

  # run $AEVOL_RUN
  CMD="$AEVOL_RUN -p -1 -b 0 -e $END_GENER"
  echo "running $CMD from $PWD..."
  $CMD || exit 1

  # cd back into the test's directory
  cd "$CUR_TEST_DIR" || exit 1
fi

if [ "$TEST_OR_GENERATE" = "TEST" ]; then
  RESDIR="res"
elif [ "$TEST_OR_GENERATE" = "GENERATE_REF" ]; then
  RESDIR="ref"
else
  echo "passed \"$TEST_OR_GENERATE\"; should be either \"TEST\" or \
      \"GENERATE_REF\""
  exit 1
fi

# make sure there is an empty $RESDIR
rm -rf "${RESDIR:?}/"
mkdir "$RESDIR" || exit 1

# copy test_input data in $RESDIR
cp -r $CUR_TEST_INPUT_DIR/* $RESDIR/

# cd into $RESDIR
cd "$RESDIR" || exit 1

# run test
CMD="$AEVOL_EXTRACT_GENOMES -b 0 -e $END_GENER"
echo "running $CMD from $PWD..."
$CMD || exit 1

# cd back into the test's directory
cd "$CUR_TEST_DIR" || exit 1

if [ "$TEST_OR_GENERATE" = "TEST" ]; then
  # check results vs ref
  fail=0

  for file in ref/genomes_best_*; do
    echo "checking file $(basename $file)"
    if ! diff -q ref/$(basename $file) res/$(basename $file); then
      fail=1
    fi
  done

  if test $fail -ne 0; then exit 1; fi
fi

exit 0
