#!/bin/sh
# This file is in the public domain.
#
# Driver for the src/exchangedb/ regression tests.  It provisions a scratch
# database of its own, runs ./test_regressions against it and removes the
# database again.  No pre-existing database is ever touched: the name is
# derived from the PID and is deliberately *not* taken from the environment.
set -eu

# Where the build tree lives; meson passes this, the fallback is for
# running the script by hand from its build directory.
BUILD_ROOT="${TALER_BUILD_ROOT:-$(cd ../../.. && pwd)}"
SQL_DIR="${TALER_SQL_DIR:-${BUILD_ROOT}/src/exchangedb/sql-schema}"

# Skip (77) rather than fail if there is no usable PostgreSQL around.
command -v createdb > /dev/null 2>&1 || exit 77
command -v dropdb > /dev/null 2>&1 || exit 77
psql -l < /dev/null > /dev/null 2>&1 || exit 77

DBNAME="taler_exdb_reg_$$"
CONF="test_regressions_$$.conf"

# The freshly built libraries must outrank any installed copy, as
# LD_LIBRARY_PATH beats the build tree's RUNPATH.
for d in "${BUILD_ROOT}"/src/*/; do
    LD_LIBRARY_PATH="${d%/}${LD_LIBRARY_PATH:+:}${LD_LIBRARY_PATH:-}"
done
export LD_LIBRARY_PATH

cleanup ()
{
    dropdb --if-exists "$DBNAME" > /dev/null 2>&1 || true
    rm -f "$CONF"
}
trap cleanup EXIT

cat > "$CONF" <<EOF
[exchange]
CURRENCY = EUR
BASE_URL = http://localhost/
[exchangedb-postgres]
CONFIG = postgres:///${DBNAME}
SQL_DIR = ${SQL_DIR}/
[exchangedb]
MAX_AML_PROGRAM_RUNTIME = 1 minute
IDLE_RESERVE_EXPIRATION_TIME = 4 weeks
LEGAL_RESERVE_EXPIRATION_TIME = 7 years
AGGREGATOR_SHIFT = 1s
DEFAULT_PURSE_LIMIT = 1
EOF

createdb "$DBNAME" > /dev/null 2>&1 || exit 77

RET=0
./test_regressions -c "$CONF" "$@" || RET=$?
exit $RET
