#!/usr/bin/env bash
# This file is in the public domain.
#
# Unit test for the database-name derivation in contrib/challenger-dbconfig.
# That value is passed to 'dropdb' when challenger-dbconfig is run with '-r',
# so getting it wrong is destructive.  Needs neither a daemon nor a database:
# the snippet under test is lifted out of the real script and evaluated here
# against a table of representative connection strings.

set -eu

# Exit, with status code "skip" (no 'real' failure)
function exit_skip() {
    echo " SKIP: $1"
    exit 77
}

# Exit, with error message (hard failure)
function exit_fail() {
    echo " FAIL: $@"
    exit 1
}

# challenger-dbconfig as configured into the build directory; fall back to an
# installed one.
DBCONFIG="../../contrib/challenger-dbconfig"
if [ ! -f "$DBCONFIG" ]
then
    DBCONFIG=$(command -v challenger-dbconfig) \
        || exit_skip "challenger-dbconfig required"
fi

# Lift the 'DBNAME=$(echo "$DBPATH" | sed ...)' snippet out of the script,
# so that this test cannot drift away from the code it checks.
SNIPPET=$(sed -n '/^DBNAME=\$(echo/,/)$/p' "$DBCONFIG")
if [ -z "$SNIPPET" ]
then
    exit_fail "Could not find the DBNAME derivation in ${DBCONFIG}"
fi

# Derive the database name from $1 the way challenger-dbconfig does.
function dbname_of() {
    local DBPATH="$1"
    local DBNAME

    eval "$SNIPPET"
    echo "$DBNAME"
}

function check() {
    local GOT

    GOT=$(dbname_of "$1")
    echo -n "Deriving database name from '$1' ..."
    if [ "$GOT" != "$2" ]
    then
        exit_fail "expected '$2', got '$GOT'"
    fi
    echo " OK"
}

# The shipped default.
check "postgres:///challenger" "challenger"
# The standard socket-path form in Taler configurations: the slashes in the
# query string must not be mistaken for the end of the authority part.
check "postgres:///challenger?host=/var/run/postgresql" "challenger"
check "postgres:///challenger?host=/var/run/postgresql&connect_timeout=5" "challenger"
# TCP forms, with and without credentials, port and options.
check "postgres://user@host/challenger?sslmode=require" "challenger"
check "postgres://user:pw@host:5432/challenger" "challenger"
check "postgres://localhost/challenger" "challenger"

exit 0
