#!/usr/bin/env bash
# This file is in the public domain.
#
# Tests the diagnostics of challenger-admin.  Needs a database, but no daemon.
#
# The interesting case is '-m' with a CLIENT_REDIRECT_URI that another client
# already uses: that violates clients_uri_key, which GNUnet reports as
# SUCCESS_NO_RESULTS -- the very same status as "no such client".  Reporting
# it as "Client not found" tells the operator (and any deployment script) the
# wrong thing.

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
}

# Cleanup to run whenever we exit
function cleanup()
{
    rm -f "$LAST_OUTPUT"
}

LAST_OUTPUT=$(mktemp adminXXXXXX.log)

# Install cleanup handler (except for kill -9)
trap cleanup EXIT

export PATH="$PATH:."

echo -n "Testing for challenger-admin ..."
challenger-admin -h > /dev/null || exit_skip "challenger-admin required"
echo " FOUND"

CONF="test-challenger.conf"
URI_A="http://client-a.example.com/"
URI_B="http://client-b.example.com/"
URI_C="http://client-c.example.com/"
CLIENT_SECRET="secret-token:secret"

echo -n "Initialize challenger database ..."
challenger-dbinit -r -c "${CONF}" &> dbinit.log
echo " OK"

echo -n "Add two challenger clients ..."
ID_A=$(challenger-admin -c "${CONF}" -q -a "${CLIENT_SECRET}" "${URI_A}")
ID_B=$(challenger-admin -c "${CONF}" -q -a "${CLIENT_SECRET}" "${URI_B}")
if [ "${ID_A}" = "${ID_B}" ]
then
    exit_fail "Expected two distinct client IDs, got ${ID_A} twice"
fi
echo " OK (${ID_A}, ${ID_B})"

echo -n "Modifying client ${ID_B} to the URI of client ${ID_A} ..."
if challenger-admin -c "${CONF}" -m "${ID_B}" "${URI_A}" &> "$LAST_OUTPUT"
then
    exit_fail "Expected failure, but the modification succeeded: $(cat "$LAST_OUTPUT")"
fi
if grep -q "not found" "$LAST_OUTPUT"
then
    exit_fail "URI collision was misreported as a missing client: $(cat "$LAST_OUTPUT")"
fi
if ! grep -qi "already in use" "$LAST_OUTPUT"
then
    exit_fail "Expected an error about the URI being in use, got: $(cat "$LAST_OUTPUT")"
fi
echo " OK"

echo -n "Modifying a client that does not exist ..."
if challenger-admin -c "${CONF}" -m 999999 "${URI_C}" &> "$LAST_OUTPUT"
then
    exit_fail "Expected failure, but the modification succeeded: $(cat "$LAST_OUTPUT")"
fi
if ! grep -q "not found" "$LAST_OUTPUT"
then
    exit_fail "Expected 'not found', got: $(cat "$LAST_OUTPUT")"
fi
echo " OK"

echo -n "Modifying client ${ID_B} to an unused URI ..."
challenger-admin -c "${CONF}" -m "${ID_B}" "${URI_C}" &> "$LAST_OUTPUT" \
    || exit_fail "Expected success, got: $(cat "$LAST_OUTPUT")"
echo " OK"

echo -n "Re-using the now free URI for client ${ID_A} ..."
challenger-admin -c "${CONF}" -m "${ID_A}" "${URI_B}" &> "$LAST_OUTPUT" \
    || exit_fail "Expected success, got: $(cat "$LAST_OUTPUT")"
echo " OK"

exit 0
