#!/usr/bin/env bash
# This file is in the public domain

# Script to be inlined into the main test scripts. Defines function 'setup()'
# which wraps around 'taler-unified-setup.sh' to launch GNU Taler services.
# Call setup() with the arguments to pass to 'taler-unified-setup'. setup()
# will then launch GNU Taler, wait for the process to be complete before
# returning. The script will also install an exit handler to ensure the GNU
# Taler processes are stopped when the shell exits.

set -eu

unset XDG_DATA_HOME
unset XDG_CONFIG_HOME


# Cleanup to run whenever we exit
function exit_cleanup()
{
    if [ ! -z ${SETUP_PID+x} ]
    then
        echo "Killing taler-unified-setup ($SETUP_PID)" >&2
        kill -TERM "$SETUP_PID" 2> /dev/null || true
        wait "$SETUP_PID" 2> /dev/null || true
    fi
}

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

function setup()
{
    echo "Starting test system ..." >&2
    # Create a named pipe in a temp directory we own.
    FIFO_DIR=$(mktemp -p "${TMPDIR:-/tmp}" -d fifo-XXXXXX)
    FIFO_OUT=$(echo "$FIFO_DIR/out")
    mkfifo "$FIFO_OUT"
    # Open pipe as FD 3 (RW) and FD 4 (RO)
    exec 3<> "$FIFO_OUT" 4< "$FIFO_OUT"
    rm -rf "$FIFO_DIR"
    # We require '-W' for our termination logic to work.
    taler-unified-setup.sh -W "$@" >&3 &
    SETUP_PID=$!
    # Close FD3
    exec 3>&-
    # Pass the setup's output through until it announces READY:.  Note that
    # reaching end-of-pipe is NOT success: that is what happens when
    # taler-unified-setup.sh dies during startup, and continuing then makes
    # the test fail much later against a system that was never brought up,
    # hiding the actual error.  So insist on having seen the marker.
    SETUP_READY=0
    while IFS= read -r line <&4
    do
        printf '%s\n' "$line"
        case "$line" in
            *READY:*)
                SETUP_READY=1
                break
                ;;
        esac
    done
    # Close FD4
    exec 4>&-
    if [ "1" != "$SETUP_READY" ]
    then
        exit_fail "taler-unified-setup.sh failed to start the test system"
    fi
    echo "Test system ready" >&2
}

# Exit, with status code "skip" (no 'real' failure)
function exit_fail() {
    echo "$@" >&2
    exit 1
}

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

function get_payto_uri() {
    libeufin-bank create-account -u "$1" -p "$2" --name "$1" 2> /dev/null
}

echo -n "Checking for curl ..."
curl --version 2> /dev/null > /dev/null || exit_skip " no curl"
echo " OK"
echo -n "Checking for jq ..."
jq --version 2> /dev/null > /dev/null || exit_skip " no jq"
echo " OK"
