#!/bin/bash
# Minimal script for testing, creates a first template
# that would work in combination with 'test.conf'.
# Run after starting taler-merchant-httpd and
# *before* starting paivana-httpd.
#
# This is a developer convenience, not part of `make check' --
# nothing in meson.build refers to it, and it needs a merchant
# backend already listening on localhost:9966.

# Report the failure and exit non-zero.  (The comment here used to
# claim this was a "skip", which is a different exit status and not
# what the body does: a merchant that will not take these calls is a
# real failure.)
function exit_fail() {
    echo "$@" >&2
    exit 1
}

for tool in curl jq;
do
    if ! command -v "$tool" >/dev/null 2>&1;
    then
        exit_fail "$tool is required but not installed"
    fi
done

LAST_RESPONSE=$(mktemp /tmp/last-response-XXXXXX.json)
# ...and is removed again however we leave, including through
# exit_fail, which used to leave one behind on every run.
trap 'rm -f "$LAST_RESPONSE"' EXIT

echo -n "Configuring merchant instance ..."

STATUS=$(curl -H "Content-Type: application/json" -X POST \
    -H 'Authorization: Bearer secret-token:sandbox' \
    http://localhost:9966/management/instances \
    -d '{"auth":{"method":"external"},"id":"admin","name":"default","user_type":"business","address":{},"jurisdiction":{},"use_stefan":true,"default_wire_transfer_delay":{"d_us" : 50000000000},"default_pay_delay":{"d_us": 60000000000}}' \
    -w "%{http_code}" \
    -s \
    -o "$LAST_RESPONSE")

if [ "$STATUS" != "204" ]
then
    jq < "$LAST_RESPONSE"
    exit_fail "Expected '204 No content' response. Got instead $STATUS"
fi
echo "OK"

echo -n "Configuring merchant bank account ..."

PAYTO="payto://x-taler-bank/bank.demo.taler.net/fortythree?receiver-name=43"
# add bank account address
STATUS=$(curl -H "Content-Type: application/json" \
              -X POST \
              -H 'Authorization: Bearer secret-token:sandbox' \
              http://localhost:9966/private/accounts \
              -d '{"payto_uri":"'"$PAYTO"'"}' \
              -w "%{http_code}" \
              -s \
              -o "$LAST_RESPONSE")

if [ "$STATUS" != "200" ]
then
    jq < "$LAST_RESPONSE"
    exit_fail "Expected '200 OK' response. Got instead $STATUS"
fi
echo "Ok"

echo -n "Creating Paivana template..."
TID="paivana"
STATUS=$(curl -H "Content-Type: application/json" \
              -X POST \
              'http://localhost:9966/private/templates' \
              -H 'Authorization: Bearer secret-token:sandbox' \
              -d '{"template_id":"paivana","template_description":"A Paivana template","template_contract":{"template_type":"paivana","summary":"The summary","website_regex":".*","choices":[{"amount":"KUDOS:1"}]}}' \
              -w "%{http_code}" \
              -s \
              -o "$LAST_RESPONSE")

if [ "$STATUS" != "204" ]
then
    jq < "$LAST_RESPONSE"
    exit_fail "Expected 204, template created. got: $STATUS"
fi

echo "OK"
