#!/bin/bash
########################################################################
# cet_test
#
# Test wrapper to ensure clean working directory.
#
########################################################################

####################################
# Useful variables and defaults.
prog=${0##*/}
fill=${prog//?/ }

# Should we clean the working directory first?
(( want_clean = 1 ))

####################################
# Useful functions.

function realdir() {
  local dir="${1:-.}"
  ( cd "$dir" && pwd -P )
}

function usage() {
  cat 1>&2<<EOF
usage: $prog [--datafiles <files>] [--dirty] [--remove-on-failure <files>] \\
       $fill [--required-files <files>] [--wd <test-working-dir>] [--] \\
       $fill <cmd> [<args>...]

Multiple <files> should be separated with semicolons (;).
EOF
  exit ${1:-1}
}

declare -a datafiles
function set_datafiles() {
  local IFS=';'
  for i in ${1}; do datafiles+=("$(basename "$i")"); done
}

########################################################################
# Main.
########################################################################

getopt -T >/dev/null 2>&1
if (( $? != 4 )); then
  echo "ERROR: GNU getopt required! Check SETUP_GETOPT and PATH." 1>&2
  exit 1
fi

TEMP=`getopt -n "$prog" --long datafiles:,debug,dirty-workdir,remove-on-failure:,required-files:,skip-return-code:,wd: -o + -- "${@}"`
eval set -- "$TEMP"

while true; do
  case $1 in
    --datafiles) set_datafiles "$2"; shift;;
    --debug) vopt="v";;
    --dirty-workdir) unset want_clean;;
    --remove-on-failure)
      old_IFS="${IFS}"; IFS=';'; removeOnFailure=($2); IFS=${old_IFS}
      shift;;
    --required-files)
      old_IFS="${IFS}"; IFS=';'; requiredfiles=($2); IFS=${old_IFS}
      shift;;
    --skip-return-code) (( skip_code = ${2} )); shift;;
    --wd) wd="$2"; shift;;
    --) shift; break;;
    *) echo "Bad argument $1" 1>&2; usage 1
  esac
  shift
done

if [[ -z "$wd" ]]; then
  echo "Compulsory argument --wd missing." 1>&2
  usage 1
elif [[ "$(realdir "$wd")" != "$(realdir)" ]]; then
  echo "$prog must be executed from the working directory \"$(realdir "$wd")\" (currently \"$(realdir)\") for the test invoking $1" 1>&2
  usage 1
fi

if [[ -z "$1" ]]; then
  echo "$prog needs a command to execute!" 1>&2
  usage 1
fi

# Clean the current working directory of everything except what we know
# we want to keep.
if (( want_clean )); then
  shopt -s nullglob
  for i in *; do
    (( found = 0 ))
    for j in "${datafiles[@]}"; do
      if [[ "$i" == "$j" ]]; then
        (( found = 1 ))
        break;
      fi
    done

    if ! (( ${found:-0} )); then
      rm -rv${vopt} "${i}"
    fi
  done
fi

shopt -s nocasematch
(( CET_DEBUG_TEST_ENVIRONMENT > 0 )) || \
  { [ -n "$CET_DEBUG_TEST_ENVIRONMENT" ] && \
  [[ "$CET_DEBUG_TEST_ENVIRONMENT" =~ ^([yt]|yes|true|on) ]]; } && \
  printenv | sort 1>&2
shopt -u nocasematch

# Make sure required files exist.
declare -a missingfiles
for i in "${requiredfiles[@]}" "${datafiles[@]}"; do
  if [[ ! -e "$i" ]]; then
    missingfiles+=("${i}")
  fi
done

if (( ${#missingfiles[@]} )); then
  echo "Required files missing from ${wd} for test: ${missingfiles[@]}" 1>&2
  exit ${skip_code:-247}
else
  # Execute command in now-clean environment.
  "$@"
  status=$?
  if (( ${status} != 0 )) && (( ${#removeOnFailure[@]} > 0 )); then
    echo "Removing due to failed execution: ${removeOnFailure[@]}" 1>&2
    rm -rf "${removeOnFailure[@]}"
  fi
  exit ${status}
fi
