#!/bin/bash
# Install + start demo-withdraw API + auto-confirm loop inside bank container.
# Host:
#   ./scripts/taler-bank/install-demo-withdraw-api.sh
set -euo pipefail
ROOT=$(cd "$(dirname "$0")" && pwd)
CTR="${BANK_CONTAINER:-taler-hacktivism-bank}"

podman cp "$ROOT/demo-withdraw-api.py" "$CTR:/usr/local/bin/demo-withdraw-api.py"
podman cp "$ROOT/auto-confirm-withdrawals.sh" "$CTR:/usr/local/bin/auto-confirm-withdrawals.sh"
podman cp "$ROOT/refresh-demo-withdraw.sh" "$CTR:/usr/local/bin/refresh-demo-withdraw.sh"
podman exec -u root "$CTR" chmod 755 \
  /usr/local/bin/demo-withdraw-api.py \
  /usr/local/bin/auto-confirm-withdrawals.sh \
  /usr/local/bin/refresh-demo-withdraw.sh

# nginx: proxy demo-withdraw.json
NGX=/etc/nginx/sites-available/bank-landing
podman exec -u root "$CTR" bash -lc '
set -e
f=/etc/nginx/sites-available/bank-landing
if ! grep -q demo-withdraw.json "$f"; then
  # insert before location /intro/
  python3 - <<PY
from pathlib import Path
p=Path("/etc/nginx/sites-available/bank-landing")
t=p.read_text()
block="""    location = /intro/demo-withdraw.json {
        proxy_pass http://127.0.0.1:19096/demo-withdraw.json;
        proxy_http_version 1.1;
        proxy_set_header Host \$host;
        add_header Cache-Control "no-store" always;
        add_header Access-Control-Allow-Origin * always;
    }
"""
if "demo-withdraw.json" not in t:
    t=t.replace("    location /intro/ {", block+"    location /intro/ {", 1)
    p.write_text(t)
    print("nginx location added")
else:
    print("nginx already has demo-withdraw")
if "auto-account.json" not in t:
    t=p.read_text()
    block2="""    location = /intro/auto-account.json {
        proxy_pass http://127.0.0.1:19096/auto-account.json;
        proxy_http_version 1.1;
        proxy_set_header Host \$host;
        add_header Cache-Control "no-store" always;
        add_header Access-Control-Allow-Origin * always;
    }
"""
    t=t.replace("    location /intro/ {", block2+"    location /intro/ {", 1)
    p.write_text(t)
    print("nginx auto-account location added")
else:
    print("nginx already has auto-account")
PY
  nginx -t && nginx -s reload || true
else
  echo "nginx already configured"
fi
'

# start/restart API
podman exec -u root "$CTR" bash -lc '
pkill -f "demo-withdraw-api.py" 2>/dev/null || true
nohup python3 /usr/local/bin/demo-withdraw-api.py \
  >>/var/log/demo-withdraw-api.log 2>&1 </dev/null &
echo "api pid $!"
# auto-confirm loop
pkill -f "auto-confirm-withdrawals.sh --loop" 2>/dev/null || true
nohup /usr/local/bin/auto-confirm-withdrawals.sh --loop 4 \
  >>/var/log/auto-confirm-withdrawals.log 2>&1 </dev/null &
echo "auto-confirm pid $!"
sleep 1
curl -sS -m 8 http://127.0.0.1:19096/demo-withdraw.json | head -c 300; echo
'

echo "OK: demo-withdraw API + auto-confirm in $CTR"
echo "Public: https://bank.hacktivism.ch/intro/demo-withdraw.json"
