#!/bin/bash
# Create a fresh demo GOA withdraw for landing QR (no python — runs in bank container).
# Writes under LANDING_DIR (default /var/www/bank-landing).
#
# Inside container:
#   /usr/local/bin/refresh-demo-withdraw.sh
# Host:
#   podman exec taler-hacktivism-bank /usr/local/bin/refresh-demo-withdraw.sh
set -euo pipefail

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

if [ -z "$PASS" ]; then
  for f in "/root/bank-${USER}-password.txt" /root/bank-explorer-password.txt; do
    if [ -f "$f" ]; then PASS=$(tr -d '\n' <"$f"); break; fi
  done
fi
[ -n "$PASS" ] || { echo "Set BANK_PASS or /root/bank-explorer-password.txt" >&2; exit 1; }

BANK="${BANK%/}"
TOK=$(curl -sS -m 12 -u "${USER}:${PASS}" \
  -H 'Content-Type: application/json' \
  -d '{"scope":"readwrite","refreshable":true}' \
  "${BANK}/accounts/${USER}/token")
TOKEN=$(printf '%s' "$TOK" | sed -n 's/.*"access_token"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')
[ -n "$TOKEN" ] || { echo "token fail: $TOK" >&2; exit 1; }

WD=$(curl -sS -m 15 \
  -H "Authorization: Bearer ${TOKEN}" \
  -H 'Content-Type: application/json' \
  -d "{\"suggested_amount\":\"${AMOUNT}\"}" \
  "${BANK}/accounts/${USER}/withdrawals")
URI=$(printf '%s' "$WD" | sed -n 's/.*"taler_withdraw_uri"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')
WID=$(printf '%s' "$WD" | sed -n 's/.*"withdrawal_id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')
[ -n "$URI" ] || { echo "no URI from: $WD" >&2; exit 1; }
[ -n "$WID" ] || WID=$(basename "$URI")

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"
echo "$WID" >>"$LANDING_DIR/withdraw-watch.ids"
sort -u "$LANDING_DIR/withdraw-watch.ids" -o "$LANDING_DIR/withdraw-watch.ids" 2>/dev/null || true

echo "URI=$URI"
echo "WID=$WID"

if [ -x /usr/local/bin/landing-stats.sh ]; then
  LANDING_DIR="$LANDING_DIR" /usr/local/bin/landing-stats.sh || true
fi
