#!/bin/bash
# Create a demo GOA withdrawal for user explorer and write QR assets under LANDING_DIR.
# Run on koopa (host) with bank on 127.0.0.1:9012.
set -euo pipefail

BANK="${BANK_URL:-http://127.0.0.1:9012}"
USER="${BANK_USER:-explorer}"
PASS="${BANK_PASS:-}"
AMOUNT="${AMOUNT:-GOA:10}"
LANDING_DIR="${LANDING_DIR:-/var/www/bank-landing}"

if [ -z "$PASS" ]; then
  if [ -f /root/bank-explorer-password.txt ]; then
    PASS=$(tr -d '\n' </root/bank-explorer-password.txt)
  elif [ -f /tmp/bank-caddy-wire.log ]; then
    PASS=$(grep -E '^explorer=' /tmp/bank-caddy-wire.log | tail -1 | cut -d= -f2-)
  fi
fi
if [ -z "$PASS" ]; then
  echo "Set BANK_PASS or put password in /root/bank-explorer-password.txt" >&2
  exit 1
fi

WORKDIR=$(mktemp -d)
trap 'rm -rf "$WORKDIR"' EXIT

echo "{\"scope\":\"readwrite\",\"refreshable\":true}" >"$WORKDIR/tok.json"
curl -sS -m 15 -u "${USER}:${PASS}" \
  -H "Content-Type: application/json" \
  -d @"$WORKDIR/tok.json" \
  "${BANK}/accounts/${USER}/token" >"$WORKDIR/tok.out"

TOKEN=$(python3 - "$WORKDIR/tok.out" <<'PY'
import json,sys
d=json.load(open(sys.argv[1]))
print(d.get("access_token",""))
PY
)
if [ -z "$TOKEN" ]; then
  echo "token failed:" >&2
  cat "$WORKDIR/tok.out" >&2
  exit 1
fi

echo "{\"suggested_amount\":\"${AMOUNT}\"}" >"$WORKDIR/wd.json"
curl -sS -m 15 \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d @"$WORKDIR/wd.json" \
  "${BANK}/accounts/${USER}/withdrawals" >"$WORKDIR/wd.out"

URI=$(python3 - "$WORKDIR/wd.out" <<'PY'
import json,sys
d=json.load(open(sys.argv[1]))
print(d.get("taler_withdraw_uri") or "")
if not d.get("taler_withdraw_uri"):
    sys.stderr.write(open(sys.argv[1]).read()+"\n")
    sys.exit(1)
print(d.get("withdrawal_id",""), file=sys.stderr)
PY
)

mkdir -p "$LANDING_DIR"
printf '%s\n' "$URI" >"$LANDING_DIR/withdraw.uri"
printf '%s\n' "$AMOUNT" >"$LANDING_DIR/withdraw.amount"
date -u +%Y-%m-%dT%H:%MZ >"$LANDING_DIR/withdraw.created"
# track id for auto-confirm-withdrawals.sh
WID=$(basename "$URI")
echo "$WID" >>"$LANDING_DIR/withdraw-watch.ids"
sort -u "$LANDING_DIR/withdraw-watch.ids" -o "$LANDING_DIR/withdraw-watch.ids"
echo "watch_id=$WID (auto-confirm when wallet selects)"

# QR as SVG (no external deps) via python qrcode if present, else pure matrix via segno/qrcode
python3 - "$URI" "$LANDING_DIR/withdraw-qr.svg" <<'PY'
import sys
uri, out = sys.argv[1], sys.argv[2]
try:
    import qrcode
    import qrcode.image.svg
    img = qrcode.make(uri, image_factory=qrcode.image.svg.SvgPathImage)
    img.save(out)
    print("qrcode lib ok")
except Exception as e:
    # minimal fallback: write HTML with data attribute for client-side QR
    open(out, "w").write(
        f'<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg" width="8" height="8">'
        f'<!-- QR_FALLBACK uri={uri} --></svg>\n'
    )
    open(out + ".uri", "w").write(uri)
    print("fallback:", e)
PY

# Also PNG if pillow/qrcode available
python3 - "$URI" "$LANDING_DIR/withdraw-qr.png" <<'PY' || true
import sys
uri, out = sys.argv[1], sys.argv[2]
import qrcode
img = qrcode.make(uri, box_size=8, border=2)
img.save(out)
print("png ok", out)
PY

echo "URI=$URI"
echo "wrote under $LANDING_DIR"
ls -la "$LANDING_DIR"/withdraw* 2>/dev/null || true

# Refresh public stats.json when landing-stats is available (in-container path)
if [ -x /usr/local/bin/landing-stats.sh ]; then
  LANDING_DIR="$LANDING_DIR" /usr/local/bin/landing-stats.sh || true
elif [ -x "$(dirname "$0")/landing-stats.sh" ]; then
  LANDING_DIR="$LANDING_DIR" "$(dirname "$0")/landing-stats.sh" || true
fi
