#!/bin/bash
# Local machine: withdraw GOA via bank-integrated QR1 URI (explorer demo account).
# Requires: monorepo wallet, ssh koopa, auto-confirm on host.
set -euo pipefail
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
SCRATCH="${ROOT}/.tmp/session-withdraw-$(date -u +%Y%m%d-%H%M%S)"
mkdir -p "$SCRATCH"
MONO="${MONO:-/Users/newkamek/src/taler/taler-typescript-core/packages/taler-wallet-cli/bin/taler-wallet-cli.mjs}"
WDB="${WDB:-$SCRATCH/wallet.sqlite3}"
EX="${EXCHANGE_URL:-https://exchange.hacktivism.ch/}"
URI="${1:-}"

wcli() { node "$MONO" --wallet-db="$WDB" --no-throttle --skip-defaults "$@"; }

echo "scratch=$SCRATCH"
echo "=== add + accept ToS for $EX ==="
wcli exchanges add "$EX" 2>&1 | tee "$SCRATCH/ex-add.out" || true
wcli exchanges update "$EX" 2>&1 | tee "$SCRATCH/ex-upd.out" || true
wcli exchanges tos "$EX" 2>&1 | tee "$SCRATCH/ex-tos.out" || true
wcli exchanges accept-tos "$EX" 2>&1 | tee "$SCRATCH/ex-accept-tos.out"

if [ -z "$URI" ]; then
  URI=$(ssh -o BatchMode=yes koopa 'tr -d "\n" </var/www/bank-landing/withdraw.uri')
fi
echo "URI=$URI"
echo "$URI" >"$SCRATCH/withdraw.uri"

echo "=== withdraw accept-uri ==="
wcli withdraw accept-uri --exchange "$EX" "$URI" 2>&1 | tee "$SCRATCH/accept-uri.out"

WID=$(basename "$URI")
echo "=== ensure watch + auto-confirm on koopa ==="
ssh -o BatchMode=yes koopa "echo $WID >> /var/www/bank-landing/withdraw-watch.ids; sort -u /var/www/bank-landing/withdraw-watch.ids -o /var/www/bank-landing/withdraw-watch.ids"
# one-shot confirm as root via ssh if hernani can sudo? usually not — use screen later
# public status
curl -sS "https://bank.hacktivism.ch/taler-integration/withdrawals/${WID}" 2>/dev/null | head -c 500 || true
echo

for round in 1 2 3 4 5 6 7 8; do
  echo "=== run-until-done round $round ==="
  wcli run-until-done &
  PID=$!
  ( sleep 20; kill $PID 2>/dev/null ) &
  wait $PID 2>/dev/null || true
  wcli balance 2>&1 | tee "$SCRATCH/bal-$round.out"
  wcli transactions 2>&1 | tee "$SCRATCH/tx-$round.out" | head -80
  if grep -qE '"available": "GOA:[1-9]' "$SCRATCH/bal-$round.out"; then
    echo "OK coins received"
    exit 0
  fi
  sleep 3
done
echo "FAIL no balance" >&2
exit 1
