#!/bin/bash
# This file is part of TALER
# Copyright (C) 2014-2024 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/>
#
# Testcase for #6912 and #8061

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
    echo -n "Testing for libeufin-bank"
    libeufin-bank --help >/dev/null </dev/null || exit_skip " MISSING"
    echo " FOUND"
    ACCOUNT="exchange-account-1"
    WIRE_METHOD="iban"
    BANK_FLAGS="-ns -d $WIRE_METHOD -u $ACCOUNT"
    BANK_URL="http://localhost:18082/"
fi


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

# Launch system.
setup -c "test_template.conf" \
      -r "merchant-exchange-default" \
      -em \
      $BANK_FLAGS
LAST_RESPONSE=$(mktemp -p "${TMPDIR:-/tmp}" test_response.conf-XXXXXX)
WALLET_DB=$(mktemp -p "${TMPDIR:-/tmp}" test_wallet.json-XXXXXX)
CONF="test_template.conf.edited"
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 "."
# 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
taler-exchange-wirewatch \
    -L "INFO" \
    -c "$CONF" \
    -t &> taler-exchange-wirewatch0.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 admin instance ..."
if [ 1 = "$USE_FAKEBANK" ]
then
    TOR_PAYTO="payto://x-taler-bank/localhost/tor?receiver-name=tor"
    GNUNET_PAYTO="payto://x-taler-bank/localhost/gnunet?receiver-name=gnunet"
    SURVEY_PAYTO="payto://x-taler-bank/localhost/survey?receiver-name=survey"
    TUTORIAL_PAYTO="payto://x-taler-bank/localhost/tutorial?receiver-name=tutorial"
else
    TOR_PAYTO=$(get_payto_uri tor x)
    GNUNET_PAYTO=$(get_payto_uri gnunet x)
    SURVEY_PAYTO=$(get_payto_uri survey x)
    TUTORIAL_PAYTO=$(get_payto_uri tutorial x)
fi
# create with 2 address

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":"'"$TOR_PAYTO"'"}' \
    -w "%{http_code}" -s -o /dev/null)

if [ "$STATUS" != "200" ]
then
    exit_fail "Expected 200 OK. 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":"'"$GNUNET_PAYTO"'"}' \
    -w "%{http_code}" -s -o /dev/null)

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

echo "OK"

echo -n "Configuring merchant test instance ..."
# create with 2 address

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":"test","name":"test","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/instances/test/private/accounts \
    -d '{"payto_uri":"'"$SURVEY_PAYTO"'","credit_facade_url":"http://localhost:8082/accounts/survey/taler-revenue/","credit_facade_credentials":{"type":"basic","username":"survey","password":"x"}}' \
    -w "%{http_code}" -s -o /dev/null)

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


# CREATE ORDER AND SELL IT
echo -n "Creating order to be paid..."
STATUS=$(curl 'http://localhost:9966/instances/test/private/orders' \
    -d '{"refund_delay":{"d_us":0}, "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/instances/test/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"

NOW=$(date +%s)
echo -n "Pay first order ..."
taler-wallet-cli \
    --no-throttle \
    --wallet-db="$WALLET_DB" \
    handle-uri "${PAY_URL}" \
    -y \
    2> wallet-pay1.err > wallet-pay1.log
NOW2=$(date +%s)
echo " OK (took $(( NOW2 - NOW )) secs)"

STATUS=$(curl "http://localhost:9966/instances/test/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

#
# WIRE TRANSFER TO MERCHANT AND NOTIFY BACKEND
#

#PAY_DEADLINE=$(jq -r .contract_terms.pay_deadline.t_s < "$LAST_RESPONSE")
WIRE_DEADLINE=$(jq -r .contract_terms.wire_transfer_deadline.t_s < "$LAST_RESPONSE")

NOW=$(date +%s)

TO_SLEEP=$((3600 + WIRE_DEADLINE - NOW ))
echo "waiting $TO_SLEEP secs for wire transfer"

echo -n "Perform wire transfers ..."
taler-exchange-aggregator -y -c $CONF -T ${TO_SLEEP}000000 -t -L INFO &> aggregator.log
taler-exchange-transfer -c $CONF -t -L INFO &> transfer.log
echo " DONE"

echo -n "Obtaining wire transfer details from bank..."

BANKDATA="$(curl 'http://localhost:8082/accounts/exchange/taler-wire-gateway/history/outgoing?delta=1' -s)"
WTID=$(echo "$BANKDATA" | jq -r .outgoing_transactions[0].wtid)
WURL=$(echo "$BANKDATA" | jq -r .outgoing_transactions[0].exchange_base_url)
CREDIT_AMOUNT=$(echo "$BANKDATA" | jq -r .outgoing_transactions[0].amount)
TARGET_PAYTO=$(echo "$BANKDATA" | jq -r .outgoing_transactions[0].credit_account)
TARGET=$(echo "$TARGET_PAYTO" | awk -F = '{print $2}')

# Figure out which account got paid, in order to
# resort the right (and complete: including the receiver-name)
# TARGET_PAYTO
if echo "$SURVEY_PAYTO" | grep -q "$TARGET" > /dev/null; then
  TARGET_PAYTO="$SURVEY_PAYTO";
fi
if echo "$SURVEY_PAYTO" | grep -q "$TARGET" > /dev/null; then
  TARGET_PAYTO="$SURVEY_PAYTO";
fi
if [ "$EXCHANGE_URL" != "$WURL" ]
then
    exit_fail "Wrong exchange URL in subject '$SUBJECT', expected $EXCHANGE_URL"
fi
echo " OK"

set +e

echo -n "Notifying merchant of correct wire transfer, but on wrong instance..."

#issue 6912
#here we are notifying the transfer into a wrong instance (admin) and the payto_uri of the admin instance
STATUS=$(curl 'http://localhost:9966/private/transfers' \
    -d "{\"credit_amount\":\"$CREDIT_AMOUNT\",\"wtid\":\"$WTID\",\"payto_uri\":\"$TOR_PAYTO\",\"exchange_url\":\"$WURL\"}" \
    -m 3 \
    -w "%{http_code}" \
    -s \
    -o "$LAST_RESPONSE")

if [ "$STATUS" != "204" ]
then
    jq . < "$LAST_RESPONSE"
    exit_fail "Expected response 204 no content, after providing transfer data. Got: $STATUS"
fi
echo " OK"


echo -n "Fetching wire transfers of ADMIN instance ..."

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

if [ "$STATUS" != "200" ]
then
    jq . < "$LAST_RESPONSE"
    exit_fail "Expected response 200 Ok. got: $STATUS"
fi

TRANSFERS_LIST_SIZE=$(jq -r '.transfers | length' < "$LAST_RESPONSE")

if [ "$TRANSFERS_LIST_SIZE" != "1" ]
then
    jq . < "$LAST_RESPONSE"
    exit_fail "Expected one transfer. got: $TRANSFERS_LIST_SIZE"
fi

echo "OK"

echo -n "Fetching running taler-merchant-reconciliation on bogus transfer ..."
taler-merchant-reconciliation \
    -c "$CONF" \
    -L INFO \
    -t &> taler-merchant-reconciliation0.log
echo "OK"

echo -n "Fetching wire transfers of 'test' instance ..."

STATUS=$(curl 'http://localhost:9966/instances/test/private/transfers' \
              -w "%{http_code}" \
              -s \
              -o "$LAST_RESPONSE")

if [ "$STATUS" != "200" ]
then
    jq . < "$LAST_RESPONSE"
    exit_fail "Expected response 200 Ok. got: $STATUS"
fi

TRANSFERS_LIST_SIZE=$(jq -r '.transfers | length' < "$LAST_RESPONSE")

if [ "$TRANSFERS_LIST_SIZE" != "0" ]
then
    jq . < "$LAST_RESPONSE"
    exit_fail "Expected non-empty transfer list size. got: $TRANSFERS_LIST_SIZE"
fi

echo "OK"

echo -n "Checking order status ..."
STATUS=$(curl "http://localhost:9966/instances/test/private/orders/${ORDER_ID}?transfer=YES" \
    -w "%{http_code}" -s -o "$LAST_RESPONSE")

if [ "$STATUS" != "200" ]
then
    jq . < "$LAST_RESPONSE"
    exit_fail "Expected 200 ok, after order inquiry. got: $STATUS"
fi

WAS_WIRED=$(jq -r .wired < "$LAST_RESPONSE")

if [ "$WAS_WIRED" == "true" ]
then
    jq . < "$LAST_RESPONSE"
    exit_fail ".wired is true, expected false"
fi

echo " OK"

echo -n "Notifying merchant of correct wire transfer in the correct instance..."
#this time in the correct instance so the order will be marked as wired...

echo -n "Running taler-merchant-wirewatch to check transfer ..."
taler-merchant-wirewatch \
    -c $CONF \
    -t \
    -L INFO &> taler-merchant-wirewatch1.log
echo " DONE"

echo -n "Post-check for exchange deposit ..."
taler-merchant-depositcheck \
    -c $CONF \
    -t \
    -e "http://localhost:8081/" \
    -T ${TO_SLEEP}000000 \
    -L INFO &> depositcheck1a.log
echo " DONE"

echo -n "Fetching running taler-merchant-reconciliation on good transfer ..."
taler-merchant-reconciliation \
    -c $CONF \
    -L INFO \
    -T ${TO_SLEEP}000000 \
    -t &> taler-merchant-reconciliation1.log
echo "OK"

echo -n "Fetching wire transfers of TEST instance ..."

STATUS=$(curl 'http://localhost:9966/instances/test/private/transfers' \
              -w "%{http_code}" \
              -s \
              -o "$LAST_RESPONSE")

if [ "$STATUS" != "200" ]
then
    jq . < "$LAST_RESPONSE"
    exit_fail "Expected response 200 Ok. got: $STATUS"
fi

TRANSFERS_LIST_SIZE=$(jq -r '.transfers | length' < "$LAST_RESPONSE")

if [ "$TRANSFERS_LIST_SIZE" != "1" ]
then
    jq . < "$LAST_RESPONSE"
    exit_fail "Expected one transfer. got: $TRANSFERS_LIST_SIZE"
fi

echo "OK"

echo -n "Checking order status ..."
STATUS=$(curl "http://localhost:9966/instances/test/private/orders/${ORDER_ID}" \
    -w "%{http_code}" -s -o "$LAST_RESPONSE")

if [ "$STATUS" != "200" ]
then
    jq . < "$LAST_RESPONSE"
    exit_fail "Expected 200 ok, after order inquiry. got: $STATUS"
fi

WAS_WIRED=$(jq -r .wired < "$LAST_RESPONSE")

if [ "$WAS_WIRED" != "true" ]
then
    jq . < "$LAST_RESPONSE"
    exit_fail ".wired false, expected true"
fi

echo " OK"


echo "================== 2nd order ====================== "



# CREATE ORDER AND SELL IT
echo -n "Creating 2nd order to be paid..."
STATUS=$(curl 'http://localhost:9966/instances/test/private/orders' \
    -d '{"refund_delay":{"d_us":0}, "order":{"amount":"TESTKUDOS:2","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/instances/test/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"

NOW=$(date +%s)
echo -n "Pay second order ..."
taler-wallet-cli \
    --no-throttle \
    --wallet-db="$WALLET_DB" \
    handle-uri "${PAY_URL}" \
    -y \
    2> wallet-pay2.err > wallet-pay2.log
NOW2=$(date +%s)
echo " OK (took $(( NOW2 - NOW )) secs)"

STATUS=$(curl "http://localhost:9966/instances/test/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

#
# WIRE TRANSFER TO MERCHANT AND NOTIFY BACKEND
#

#PAY_DEADLINE=$(jq -r .contract_terms.pay_deadline.t_s < "$LAST_RESPONSE")
WIRE_DEADLINE=$(jq -r .contract_terms.wire_transfer_deadline.t_s < "$LAST_RESPONSE")

NOW=$(date +%s)

TO_SLEEP=$((3600 + WIRE_DEADLINE - NOW ))
echo "waiting $TO_SLEEP secs for wire transfer"

echo -n "Pre-check for exchange deposit ..."
taler-merchant-depositcheck \
    -c $CONF \
    -t \
    -e "http://localhost:8081/" \
    -L INFO &> depositcheck1b.log
echo " DONE"

echo -n "Perform wire transfers ..."
taler-exchange-aggregator \
    -y \
    -c $CONF \
    -T ${TO_SLEEP}000000 \
    -t \
    -L INFO &> aggregator2.log
taler-exchange-transfer \
    -c $CONF \
    -t \
    -L INFO &> transfer2.log
echo " DONE"

echo -n "Post-check for exchange deposit ..."
taler-merchant-depositcheck \
    -c $CONF \
    -t \
    -e "http://localhost:8081/" \
    -T ${TO_SLEEP}000000 \
    -L INFO &> depositcheck1c.log
echo " DONE"


echo -n "Obtaining wire transfer details from bank..."

BANKDATA="$(curl 'http://localhost:8082/accounts/exchange/taler-wire-gateway/history/outgoing?delta=2' -s)"

WTID=$(echo "$BANKDATA" | jq -r .outgoing_transactions[1].wtid)
WURL=$(echo "$BANKDATA" | jq -r .outgoing_transactions[1].exchange_base_url)
CREDIT_AMOUNT=$(echo "$BANKDATA" | jq -r .outgoing_transactions[1].amount)
TARGET_PAYTO=$(echo "$BANKDATA" | jq -r .outgoing_transactions[1].credit_account)
TARGET=$(echo "$TARGET_PAYTO" | awk -F = '{print $2}')

# Figure out which account got paid, in order to
# resort the right (and complete: including the receiver-name)
# TARGET_PAYTO
if echo "$SURVEY_PAYTO" | grep -q "$TARGET" > /dev/null; then
  TARGET_PAYTO="$SURVEY_PAYTO";
fi
if echo "$SURVEY_PAYTO" | grep -q "$TARGET" > /dev/null; then
  TARGET_PAYTO="$SURVEY_PAYTO";
fi
if [ "$EXCHANGE_URL" != "$WURL" ]
then
    exit_fail "Wrong exchange URL in subject '$SUBJECT', expected $EXCHANGE_URL"
fi
echo " OK"

echo -n "Running taler-merchant-wirewatch to check transfer ..."
taler-merchant-wirewatch \
    -c $CONF \
    -t \
    -L INFO &> taler-merchant-wirewatch2.log
echo " DONE"

echo -n "Fetching running taler-merchant-reconciliation on good transfer ..."
taler-merchant-reconciliation \
    -c $CONF \
    -L INFO \
    -T ${TO_SLEEP}000000 \
    -t &> taler-merchant-reconciliation2.log
echo "OK"

echo -n "Fetching wire transfers of TEST instance ..."

STATUS=$(curl 'http://localhost:9966/instances/test/private/transfers' \
              -w "%{http_code}" \
              -s \
              -o "$LAST_RESPONSE")

if [ "$STATUS" != "200" ]
then
    jq . < "$LAST_RESPONSE"
    exit_fail "Expected response 200 Ok. got: $STATUS"
fi

TRANSFERS_LIST_SIZE=$(jq -r '.transfers | length' < "$LAST_RESPONSE")

if [ "$TRANSFERS_LIST_SIZE" != "2" ]
then
    jq . < "$LAST_RESPONSE"
    exit_fail "Expected two transfers. got: $TRANSFERS_LIST_SIZE"
fi

echo "OK"

echo -n "Checking order status ..."
STATUS=$(curl "http://localhost:9966/instances/test/private/orders/${ORDER_ID}" \
    -w "%{http_code}" -s -o "$LAST_RESPONSE")

if [ "$STATUS" != "200" ]
then
    jq . < "$LAST_RESPONSE"
    exit_fail "Expected 200 ok, after order inquiry. got: $STATUS"
fi

WAS_WIRED=$(jq -r .wired < "$LAST_RESPONSE")

if [ "$WAS_WIRED" != "true" ]
then
    jq . < "$LAST_RESPONSE"
    exit_fail ".wired false, expected true"
fi

echo " OK"

echo "================== 3rd order ====================== "

# CREATE ORDER AND SELL IT
echo -n "Creating 3rd order to be paid..."
STATUS=$(curl 'http://localhost:9966/instances/test/private/orders' \
    -d '{"refund_delay":{"d_us":0}, "order":{"amount":"TESTKUDOS:3","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/instances/test/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"

NOW=$(date +%s)
echo -n "Pay third order ..."
taler-wallet-cli \
    --no-throttle \
    --wallet-db="$WALLET_DB" \
    handle-uri "${PAY_URL}" \
    -y \
    2> wallet-pay2.err > wallet-pay2.log
NOW2=$(date +%s)
echo " OK (took $(( NOW2 - NOW )) secs)"

STATUS=$(curl "http://localhost:9966/instances/test/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

#
# WIRE TRANSFER TO MERCHANT AND NOTIFY BACKEND
#

#PAY_DEADLINE=$(jq -r .contract_terms.pay_deadline.t_s < "$LAST_RESPONSE")
WIRE_DEADLINE=$(jq -r .contract_terms.wire_transfer_deadline.t_s < "$LAST_RESPONSE")

NOW=$(date +%s)

TO_SLEEP=$((1200 + WIRE_DEADLINE - NOW ))
echo "waiting $TO_SLEEP secs for wire transfer"

echo -n "Perform wire transfers for 3rd order..."
taler-exchange-aggregator \
    -y \
    -c $CONF \
    -T ${TO_SLEEP}000000 \
    -t \
    -L INFO &> aggregator3.log
taler-exchange-transfer \
    -c $CONF \
    -t \
    -L INFO &> transfer3.log
echo " DONE"

echo -n "Running taler-merchant-wirewatch to check transfer ..."
taler-merchant-wirewatch \
    -c $CONF \
    -t \
    -L INFO &> taler-merchant-wirewatch3.log
echo " DONE"

echo -n "Post-wirewatch check for exchange deposit ..."
taler-merchant-depositcheck \
    -c $CONF \
    -t \
    -e "http://localhost:8081/" \
    -T ${TO_SLEEP}000000 \
    -L INFO &> depositcheck1d.log
echo " DONE"

echo -n "Fetching wire transfers of TEST instance ..."

STATUS=$(curl 'http://localhost:9966/instances/test/private/transfers' \
              -w "%{http_code}" \
              -s \
              -o "$LAST_RESPONSE")

if [ "$STATUS" != "200" ]
then
    jq . < "$LAST_RESPONSE"
    exit_fail "Expected response 200 Ok. got: $STATUS"
fi

TRANSFERS_LIST_SIZE=$(jq -r '.transfers | length' < "$LAST_RESPONSE")

if [ "$TRANSFERS_LIST_SIZE" != "3" ]
then
    jq . < "$LAST_RESPONSE"
    exit_fail "Expected three transfers. got: $TRANSFERS_LIST_SIZE"
fi

echo "OK"

echo -n "Fetching running taler-merchant-reconciliation on good transfer ..."
taler-merchant-reconciliation \
    -c $CONF \
    -L INFO \
    -T ${TO_SLEEP}000000 \
    -t &> taler-merchant-reconciliation3.log
echo "OK"

echo -n "Checking order status ..."
STATUS=$(curl "http://localhost:9966/instances/test/private/orders/${ORDER_ID}" \
    -w "%{http_code}" -s -o "$LAST_RESPONSE")

if [ "$STATUS" != "200" ]
then
    jq . < "$LAST_RESPONSE"
    exit_fail "Expected 200 ok, after order inquiry. got: $STATUS"
fi

WAS_WIRED=$(jq -r .wired < "$LAST_RESPONSE")

if [ "$WAS_WIRED" != "true" ]
then
    jq . < "$LAST_RESPONSE"
    exit_fail ".wired false, expected true"
fi

echo " OK"


exit 0
