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

set -eu

. setup.sh


# Replace with 0 for nexus...
USE_FAKEBANK=1
if [ 1 = "$USE_FAKEBANK" ]
then
    ACCOUNT="exchange-account-2"
    WIRE_METHOD="x-taler-bank"
    BANK_FLAGS="-f -d $WIRE_METHOD -u $ACCOUNT"
    BANK_URL="http://localhost:8082/"
else
    ACCOUNT="exchange-account-1"
    WIRE_METHOD="iban"
    BANK_FLAGS="-ns -d $WIRE_METHOD -u $ACCOUNT"
    BANK_URL="http://localhost:18082/"
    echo -n "Testing for libeufin-bank"
    libeufin-bank --help >/dev/null </dev/null || exit_skip " MISSING"
    echo " FOUND"

fi

echo -n "Testing for taler-harness"
taler-harness --help >/dev/null </dev/null || exit_skip " MISSING"
echo " FOUND"

# Launch exchange, merchant and bank.
setup -c "test_template.conf" \
      -r "merchant-exchange-default" \
      -em \
      $BANK_FLAGS
LAST_RESPONSE=$(mktemp -p "${TMPDIR:-/tmp}" test_response.conf-XXXXXX)
CONF="test_template.conf.edited"
WALLET_DB=$(mktemp -p "${TMPDIR:-/tmp}" test_wallet.json-XXXXXX)
EXCHANGE_URL="http://localhost:8081/"


echo -n "First, prepare wallet with coins..."
rm -f "$WALLET_DB"
taler-wallet-cli \
    --no-throttle \
    --wallet-db="$WALLET_DB" \
    api \
    --expect-success 'withdrawTestBalance' \
  "$(jq -n '
    {
        amount: "TESTKUDOS:99",
        corebankApiBaseUrl: $BANK_URL,
        exchangeBaseUrl: $EXCHANGE_URL
    }' \
    --arg BANK_URL "${BANK_URL}" \
    --arg EXCHANGE_URL "$EXCHANGE_URL"
  )" 2>wallet-withdraw-1.err >wallet-withdraw-1.out
echo -n "."
if [ 1 = "$USE_FAKEBANK" ]
then
    # Fakebank is instant...
    sleep 0
else
    sleep 10
    # NOTE: once libeufin can do long-polling, we should
    # be able to reduce the delay here and run wirewatch
    # always in the background via setup
fi
echo -n "."
taler-exchange-wirewatch \
    -L "INFO" \
    -c "$CONF" \
    -t \
    &> taler-exchange-wirewatch.out
echo -n "."

taler-wallet-cli \
    --wallet-db="$WALLET_DB" \
    run-until-done \
    2>wallet-withdraw-finish-1.err \
    >wallet-withdraw-finish-1.out
echo " OK"

#
# CREATE INSTANCE FOR TESTING
#

echo -n "Configuring merchant instance ..."
if [ 1 = "$USE_FAKEBANK" ]
then
    FORTYTHREE="payto://x-taler-bank/localhost/fortythree?receiver-name=fortythree"
else
    FORTYTHREE=$(get_payto_uri fortythree x)
fi

STATUS=$(curl -H "Content-Type: application/json" -X POST \
    -H 'Authorization: Bearer secret-token:super_secret' \
    "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" : 50000000},"default_pay_delay":{"d_us": 60000000}}' \
    -w "%{http_code}" -s -o /dev/null)

if [ "$STATUS" != "204" ]
then
    exit_fail "Expected 204, instance created. got: $STATUS"
fi

STATUS=$(curl -H "Content-Type: application/json" -X POST \
    -H 'Authorization: Bearer secret-token:super_secret' \
    http://localhost:9966/private/accounts \
    -d '{"payto_uri":"'"$FORTYTHREE"'"}' \
    -w "%{http_code}" -s -o /dev/null)

if [ "$STATUS" != "200" ]
then
    exit_fail "Expected '200 OK' response. Got instead $STATUS"
fi

NOW=$(date +%s)
IN_TEN_SECS=$(( NOW + 10 ))

echo -n "Creating order to be claimed..."
STATUS=$(curl 'http://localhost:9966/private/orders' \
    -d '{"order":{"amount":"TESTKUDOS:1","summary":"payme","pay_deadline": {"t_s":'"$IN_TEN_SECS"'}}}' \
    -w "%{http_code}" -s -o "$LAST_RESPONSE")

if [ "$STATUS" != "200" ]
then
    cat "$LAST_RESPONSE"
    exit_fail "Expected 200 ok, order created. got: $STATUS"
fi

ORDER_ID=$(jq -e -r .order_id < "$LAST_RESPONSE")
TOKEN=$(jq -e -r .token < "$LAST_RESPONSE")

STATUS=$(curl "http://localhost:9966/private/orders/${ORDER_ID}" \
    -w "%{http_code}" -s -o "$LAST_RESPONSE")

if [ "$STATUS" != "200" ]
then
    cat "$LAST_RESPONSE"
    exit_fail "Expected 200 ok, getting order info before claming it. got: $STATUS"
fi

PAY_URL=$(jq -e -r .taler_pay_uri < "$LAST_RESPONSE")

echo "Ok (order $ORDER_ID)"

NOW=$(date +%s)

echo -n "Claim the order but do not pay it ..."
taler-wallet-cli \
    --no-throttle \
    --wallet-db="$WALLET_DB" \
    advanced pay-prepare \
    "${PAY_URL}" \
    2> wallet-claim1.err > wallet-claim1.log

STATUS=$(curl "http://localhost:9966/private/orders/${ORDER_ID}" \
    -w "%{http_code}" -s -o "$LAST_RESPONSE")

if [ "$STATUS" != "200" ]
then
    cat "$LAST_RESPONSE"
    exit_fail "Expected 200 ok, after pay. got: $STATUS"
fi

ORDER_STATUS=$(jq -r .order_status < "$LAST_RESPONSE")

if [ "$ORDER_STATUS" != "claimed" ]
then
    cat "$LAST_RESPONSE"
    exit_fail "Expected 'paid'. got: $ORDER_STATUS"
fi
NOW2=$(date +%s)
echo " OK (took $(( NOW2 - NOW)) secs)"

echo "Wait 8 secs ..."
sleep 8

echo -n "Trying to get the list of orders..."
STATUS=$(curl "http://localhost:9966/private/orders" \
    -w "%{http_code}" -s -o "$LAST_RESPONSE")

if [ "$STATUS" != "200" ]
then
    cat "$LAST_RESPONSE"
    exit_fail "Expected 200 ok. got: $STATUS"
fi
echo "ok"

echo -n "Creating a new order that will trigger the db cleanup..."
STATUS=$(curl 'http://localhost:9966/private/orders' \
    -d '{"order":{"amount":"TESTKUDOS:1","summary":"payme"}}' \
    -w "%{http_code}" -s -o "$LAST_RESPONSE")

if [ "$STATUS" != "200" ]
then
    cat "$LAST_RESPONSE"
    exit_fail "Expected 200 ok, order created. got: $STATUS"
fi

ORDER_ID=$(jq -e -r .order_id < "$LAST_RESPONSE")
TOKEN=$(jq -e -r .token < "$LAST_RESPONSE")

STATUS=$(curl "http://localhost:9966/private/orders/${ORDER_ID}" \
    -w "%{http_code}" -s -o "$LAST_RESPONSE")

if [ "$STATUS" != "200" ]
then
    cat "$LAST_RESPONSE"
    exit_fail "Expected 200 ok, getting order info before claming it. got: $STATUS"
fi

PAY_URL=$(jq -e -r .taler_pay_uri < "$LAST_RESPONSE")

echo "Ok (order $ORDER_ID)"

echo -n "Trying to get the list of orders (issue #7025)..."
STATUS=$(curl "http://localhost:9966/private/orders" \
    -w "%{http_code}" -s -o "$LAST_RESPONSE")

if [ "$STATUS" != "200" ]
then
    cat "$LAST_RESPONSE"
    exit_fail "Expected 200 ok. got: $STATUS"
fi
echo "OK"

# set -x

echo -n "Now paying this order..."
taler-wallet-cli \
    --no-throttle \
    --wallet-db="$WALLET_DB" \
    handle-uri "${PAY_URL}"\
    -y \
    2> wallet-pay1.err > wallet-pay1.log

STATUS=$(curl "http://localhost:9966/private/orders/${ORDER_ID}" \
    -w "%{http_code}" -s -o "$LAST_RESPONSE")

if [ "$STATUS" != "200" ]
then
    cat "$LAST_RESPONSE"
    exit_fail "Expected 200 ok, after pay. got: $STATUS"
fi

ORDER_STATUS=$(jq -r .order_status < "$LAST_RESPONSE")

if [ "$ORDER_STATUS" != "paid" ]
then
    cat "$LAST_RESPONSE"
    exit_fail "Expected 'paid'. got: $ORDER_STATUS"
fi
NOW2=$(date +%s)
echo " OK (took $(( NOW2 - NOW)) secs )"


echo -n "Trying to get the list of orders..."
STATUS=$(curl "http://localhost:9966/private/orders" \
    -w "%{http_code}" -s -o "$LAST_RESPONSE")

if [ "$STATUS" != "200" ]
then
    cat "$LAST_RESPONSE"
    exit_fail "Expected 200 ok. got: $STATUS"
fi
echo ok


echo -n "Finally, create another order..."
STATUS=$(curl 'http://localhost:9966/private/orders' \
    -d '{"order":{"amount":"TESTKUDOS:1","summary":"payme"}}' \
    -w "%{http_code}" -s -o "$LAST_RESPONSE")

if [ "$STATUS" != "200" ]
then
    cat "$LAST_RESPONSE"
    exit_fail "Expected 200 ok, order created. got: $STATUS"
fi

ORDER_ID=$(jq -e -r .order_id < "$LAST_RESPONSE")
TOKEN=$(jq -e -r .token < "$LAST_RESPONSE")

STATUS=$(curl "http://localhost:9966/private/orders/${ORDER_ID}" \
    -w "%{http_code}" -s -o "$LAST_RESPONSE")

if [ "$STATUS" != "200" ]
then
    cat "$LAST_RESPONSE"
    exit_fail "Expected 200 ok, getting order info before claiming it. got: $STATUS"
fi

PAY_URL=$(jq -e -r .taler_pay_uri < "$LAST_RESPONSE")

echo "Ok (order $ORDER_ID)"

echo -n "Now paying this order..."
taler-wallet-cli \
    --no-throttle \
    --wallet-db="$WALLET_DB" \
    handle-uri \
    "${PAY_URL}" \
    -y \
    2> wallet-pay1.err > wallet-pay1.log

STATUS=$(curl "http://localhost:9966/private/orders/${ORDER_ID}" \
    -w "%{http_code}" -s -o "$LAST_RESPONSE")

if [ "$STATUS" != "200" ]
then
    cat "$LAST_RESPONSE"
    exit_fail "Expected 200 ok. got: $STATUS"
fi

ORDER_STATUS=$(jq -r .order_status < "$LAST_RESPONSE")

if [ "$ORDER_STATUS" != "paid" ]
then
    cat "$LAST_RESPONSE"
    exit_fail "Expected 'paid'. got: $ORDER_STATUS"
fi
NOW2=$(date +%s)
echo " OK (took $( echo -n $(($NOW2 - $NOW)) ) secs )"

echo -n "Trying to get the list of orders..."
STATUS=$(curl "http://localhost:9966/private/orders" \
    -w "%{http_code}" -s -o "$LAST_RESPONSE")

if [ "$STATUS" != "200" ]
then
    cat "$LAST_RESPONSE"
    exit_fail "Expected 200 ok. got: $STATUS"
fi
echo "ok"

echo "Test PASSED"

exit 0
