#!/bin/bash
# This file is part of TALER
# Copyright (C) 2014-2023 Taler Systems SA
#
# TALER is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3, or
# (at your option) any later version.
#
# TALER is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with TALER; see the file COPYING.  If not, see
# <http://www.gnu.org/licenses/>
#
set -eu

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

# Cleanup to run whenever we exit
function my_cleanup()
{
    for n in $(jobs -p)
    do
        kill "$n" 2> /dev/null || true
    done
    wait
    if [ -n "${LAST_RESPONSE+x}" ]
    then
        rm -f "${LAST_RESPONSE}"
    fi
}

echo -n "Testing for robocop "
robocop -h > /dev/null 2> /dev/null || exit_skip "robocop required"
echo "FOUND"

. setup.sh


setup -c test_sanctions.conf \
      -e \
      -u "exchange-account-exchange"


CONF="test_sanctions.conf.edited"
LAST_RESPONSE=$(mktemp -p "${TMPDIR:-/tmp}" test_response.conf-XXXXXX)

KYC_URL=$(taler-exchange-kyc-trigger -c "$CONF" -b EUR:5 | tail -n1 | awk '{print $4}')

echo $KYC_URL

KYC_ACCESS=$(echo "$KYC_URL" | tr / ' ' | awk '{print $4}')

echo $KYC_ACCESS

echo -n "Creating order to test auth is ok..." >&2
STATUS=$(curl -H "Content-Type: application/json" \
    "http://localhost:8081/kyc-info/$KYC_ACCESS" \
    -w "%{http_code}" -s -o "$LAST_RESPONSE")

if [ "$STATUS" != "200" ]
then
    cat "$LAST_RESPONSE" >&2
    exit_fail "Expected 200, KYC information returned. got: $STATUS"
fi

ID=$(jq -r .requirements[0].id < "$LAST_RESPONSE")

echo -n "Submitting KYC form..." >&2
STATUS=$(curl -H "Content-Type: application/json" -X POST \
    "http://localhost:8081/kyc-upload/$ID" \
    -d '{"FULL_NAME":"Bob","DATE_OF_BIRTH":"5.7.1980"}' \
    -w "%{http_code}" -s -o "$LAST_RESPONSE")
echo $STATUS

if [ "$STATUS" != "204" ]
then
    cat "$LAST_RESPONSE" >&2
    exit_fail "Expected 204, KYC data submitted. got: $STATUS"
fi

taler-exchange-sanctionscheck \
    -L INFO \
    -c test_sanctions.conf.edited \
    --reset \
    --test

PROP=$(echo 'SELECT jproperties FROM exchange.legitimization_outcomes WHERE is_active;' | psql talercheck -Aqt)

MATCH=$(echo "$PROP" | jq -r .SANCTION_LIST_BEST_MATCH)

if [ "$MATCH" != "1" ]
then
    exit_fail "Sanction checker failed to find Bob"
fi

echo "Test PASSED"

exit 0
