#!/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

for action in values get ; do
  echo "Testing ngcpcfg ${action} database.dbhost"
  value=$("$testsuite"/../sbin/ngcpcfg "${action}" database.dbhost)
  if [ "${value}" != "localhost" ] ; then
    echo "Error caught: database.dbhost != 'localhost' (action '${action}')"
    bailout
  fi

  echo "Testing ngcpcfg ${action} ossbss.provisioning.database.user"
  value=$("$testsuite"/../sbin/ngcpcfg "${action}" ossbss.provisioning.database.user)
  if [ "${value}" != "soap" ] ; then
    echo "Error caught: ossbss.provisioning.database.user != 'soap' (action '${action}')"
    bailout
  fi


  echo "Testing ngcpcfg ${action} www_admin.fees_csv.element_order"
  value=$("$testsuite"/../sbin/ngcpcfg "${action}" www_admin.fees_csv.element_order)
  if [ "${value}" != "destination zone zone_detail onpeak_init_rate \
  onpeak_init_interval onpeak_follow_rate onpeak_follow_interval \
  offpeak_init_rate offpeak_init_interval offpeak_follow_rate \
  offpeak_follow_interval use_free_time" ] ;
  then
    echo "Error caught: www_admin.fees_csv.element_order != expected value (action '${action}')"
    bailout
  fi
done

rm -rf "$TMPDIR"

echo "Everything seems to be ok."

# EOF
