#!/bin/bash

set -e
set -u

# when invoked under DEBUG_SHELL=1 then provide
# interactive shell before exiting
if [ -n "${DEBUG_SHELL:-}" ] ; then
  bailout() { bash; exit 1; }
else
  bailout() { exit 1; }
fi

testsuite="$(dirname "${PWD}/$0")"
export testsuite

TMPDIR="$(mktemp -d)"
echo "Switching to temporary directory $TMPDIR"
cd "$TMPDIR"
cp -a "${testsuite}"/* .

export FUNCTIONS="$testsuite/../functions/"
export HELPER="$testsuite/../helper/"
export HOOKS="$testsuite/../hooks/"
export SCRIPTS="$testsuite/../scripts/"

echo -n "Testing ngcpcfg without any arguments: "
if "$testsuite"/../sbin/ngcpcfg 2>&1 | grep -q "^Usage:$" ; then
  echo OK
else
  echo "Error with executing ngcpcfg without any arguments" >&2
  bailout
fi

echo -n "Testing ngcpcfg --help: "
if "$testsuite"/../sbin/ngcpcfg --help 2>&1 | grep -q "^Usage:$" ; then
  echo OK
else
  echo "Error with executing ngcpcfg --help" >&2
  bailout
fi

echo -n "Testing ngcpcfg --version: "
if "$testsuite"/../sbin/ngcpcfg --version 2>&1 | grep -q "version" ; then
  echo OK
else
  echo "Error with executing ngcpcfg --version" >&2
  bailout
fi

echo "Testing ngcpcfg build:"
"$testsuite"/../sbin/ngcpcfg build > build.log

while IFS= read -r line ; do
  case "$line" in
    Generating\ testsuite/*OK) echo generation OK ;;
    Executing\ postbuild\ for\ testsuite/*) echo postbuild OK;;
    chgrp\ www-data\ testsuite/ngcp-ossbss/logging.conf) echo postbuild OK;;
    DEBUG:*) ;; # support running under "--debug"
  *)
     echo "Error caught: $line" >&2
     bailout
     ;;
  esac
done < build.log

# test main tt2 processing
if [[ $(cat testsuite/testtemplate) == "foo" ]] ; then
  echo "template test is OK"
else
  echo "Error with [ngcp-config/templates/]testsuite/testtemplate.tt2" >&2
  bailout
fi

# test precedence of files
if [[ $(cat testsuite/precedence/all/test) == "test.custom.tt2" ]] ; then
  echo "precedence test is OK"
else
  echo "Error with [ngcp-config/templates/]testsuite/precedence/all/*" >&2
  bailout
fi

rm -rf "$TMPDIR"

echo "Everything seems to be ok."

# EOF
