#!/bin/bash
# Offline: download future keys from local exchange, sign, upload. Restore public BASE_URL.
# Run as root inside taler-hacktivism-exchange-ansible.
set -euo pipefail
CONF=/etc/taler-exchange/taler-exchange.conf
OV=/etc/taler-exchange/exchange-overrides.conf
PUBLIC='https://exchange.hacktivism.ch/'
LOCAL='http://127.0.0.1:9011/'

[ "$(id -u)" -eq 0 ] || { echo "root only"; exit 1; }

sed -i "s|^BASE_URL = .*|BASE_URL = ${LOCAL}|" "$OV"
echo "BASE_URL=$(grep '^BASE_URL' "$OV")"

echo "=== download ==="
if ! runuser -u taler-exchange-offline -- \
  taler-exchange-offline -c "$CONF" -L INFO download > /tmp/future-keys.json 2>/tmp/dl.err; then
  echo "download failed:"; cat /tmp/dl.err
  # still show size
fi
echo "dl_err:"; cat /tmp/dl.err | tail -30
echo "dl_size=$(wc -c </tmp/future-keys.json 2>/dev/null || echo 0)"
head -c 400 /tmp/future-keys.json 2>/dev/null; echo

if [ ! -s /tmp/future-keys.json ]; then
  echo "empty download — check secmod connectivity / management API"
  sed -i "s|^BASE_URL = .*|BASE_URL = ${PUBLIC}|" "$OV"
  exit 1
fi

echo "=== sign ==="
runuser -u taler-exchange-offline -- \
  taler-exchange-offline -c "$CONF" -L INFO sign < /tmp/future-keys.json > /tmp/signed-keys.json 2>/tmp/sg.err
echo "sg_err:"; cat /tmp/sg.err | tail -20
echo "sg_size=$(wc -c </tmp/signed-keys.json)"

echo "=== upload ==="
runuser -u taler-exchange-offline -- \
  taler-exchange-offline -c "$CONF" -L INFO upload < /tmp/signed-keys.json 2>/tmp/up.err
echo "up_err:"; cat /tmp/up.err | tail -20

sed -i "s|^BASE_URL = .*|BASE_URL = ${PUBLIC}|" "$OV"
echo "BASE_URL restored=$(grep '^BASE_URL' "$OV")"

echo "=== /keys probe ==="
sleep 1
# wake suspended handlers with a tiny delay
for i in 1 2 3 4 5 6; do
  code=$(curl -sS -m 12 -o /tmp/keys.json -w '%{http_code}' http://127.0.0.1:9011/keys || true)
  sz=$(wc -c </tmp/keys.json 2>/dev/null || echo 0)
  echo "try $i code=$code size=$sz"
  if [ "$code" = "200" ] && [ "$sz" -gt 200 ]; then
    echo KEYS_OK
    head -c 300 /tmp/keys.json; echo
    grep -oE '"master_public_key"[[:space:]]*:[[:space:]]*"[^"]+"' /tmp/keys.json | head -1 || true
    exit 0
  fi
  sleep 2
done
echo KEYS_FAIL
tail -25 /var/log/taler-exchange/taler-exchange-httpd-*.log 2>/dev/null | tail -25
exit 1
