#!/bin/bash
# Pin public GOA hostnames inside Taler containers (pasta often has no useful DNS).
# Required so wirewatch can reach https://bank.hacktivism.ch/... wire-gateway.
#
# Run on koopa (host):
#   ./pin-container-hosts.sh           # apply + show resolve
#   ./pin-container-hosts.sh --check   # only show
#   PIN_IP=212.51.151.254 ./pin-container-hosts.sh
set -euo pipefail

CHECK_ONLY=0
[ "${1:-}" = "--check" ] && CHECK_ONLY=1

DOMAINS=(bank.hacktivism.ch exchange.hacktivism.ch taler.hacktivism.ch)
CONTAINERS=(
  taler-hacktivism-bank
  taler-hacktivism-exchange-ansible
  taler-hacktivism
)

PIN_IP="${PIN_IP:-}"
if [ -z "$PIN_IP" ]; then
  PIN_IP=$(getent ahostsv4 bank.hacktivism.ch 2>/dev/null | awk '{print $1; exit}' || true)
fi
[ -n "$PIN_IP" ] || PIN_IP=212.51.151.254

echo "PIN_IP=$PIN_IP"
echo "domains: ${DOMAINS[*]}"
echo

pin_one() {
  local C="$1"
  if ! podman ps --format '{{.Names}}' | grep -qx "$C"; then
    echo "=== $C === SKIP (not running)"
    return 0
  fi
  if [ "$CHECK_ONLY" != "1" ]; then
    # Keep localhost lines; drop previous hacktivism pins; append ours
    podman exec "$C" bash -lc "
      set -e
      TMP=\$(mktemp)
      # keep non-hacktivism lines
      if [ -f /etc/hosts ]; then
        grep -vE 'hacktivism\\.ch|[[:space:]]bank\\.hacktivism|[[:space:]]exchange\\.hacktivism|[[:space:]]taler\\.hacktivism' /etc/hosts > \"\$TMP\" || true
      fi
      # ensure localhost
      grep -qE '^127\\.0\\.0\\.1[[:space:]]+localhost' \"\$TMP\" 2>/dev/null || echo '127.0.0.1 localhost' >> \"\$TMP\"
      grep -qE '^::1[[:space:]]' \"\$TMP\" 2>/dev/null || echo '::1 localhost ip6-localhost ip6-loopback' >> \"\$TMP\"
      echo '${PIN_IP} bank.hacktivism.ch exchange.hacktivism.ch taler.hacktivism.ch' >> \"\$TMP\"
      # de-dupe consecutive blank lines lightly
      cat \"\$TMP\" > /etc/hosts
      rm -f \"\$TMP\"
    "
    # wirewatch needs bank DNS after pin
    if [ "$C" = "taler-hacktivism-exchange-ansible" ]; then
      podman exec "$C" systemctl try-restart taler-exchange-wirewatch 2>/dev/null || true
    fi
  fi

  echo "=== $C ==="
  podman exec "$C" grep -E 'hacktivism|localhost' /etc/hosts 2>/dev/null || true
  for h in "${DOMAINS[@]}"; do
    # ahostsv4 first (matches what wire tools need)
    ip=$(podman exec "$C" getent ahostsv4 "$h" 2>/dev/null | awk '{print $1; exit}' || true)
    [ -n "$ip" ] || ip=$(podman exec "$C" getent hosts "$h" 2>/dev/null | awk '{print $1; exit}' || true)
    code=$(podman exec "$C" curl -skS -m 4 -o /dev/null -w '%{http_code}' "https://${h}/config" 2>/dev/null || echo 000)
    if [ -n "$ip" ] && [ "$code" = "200" ]; then
      echo "  OK   $h → $ip  /config=$code"
    elif [ -n "$ip" ]; then
      echo "  WARN $h → $ip  /config=$code"
    else
      echo "  FAIL $h → (no resolve)  /config=$code"
    fi
  done
  echo
}

for C in "${CONTAINERS[@]}"; do
  pin_one "$C"
done

echo "done (CHECK_ONLY=$CHECK_ONLY)"
