#!/bin/bash
# Install + run landing-stats.sh *inside* the bank container, and optionally
# install a cron entry there. Documented in configs/bank-landing/README.md.
#
# Run on koopa host (root or user in podman group):
#   ./landing-stats-install.sh              # copy + one-shot run
#   ./landing-stats-install.sh --cron       # also install *minutely* cron inside container
#   ./landing-stats-install.sh --run-only   # only exec existing script
set -euo pipefail

DO_CRON=0
RUN_ONLY=0
# cron schedule (default: every minute)
: "${LANDING_STATS_CRON:=* * * * *}"
for a in "$@"; do
  case "$a" in
    --cron) DO_CRON=1 ;;
    --run-only) RUN_ONLY=1 ;;
    -h|--help)
      sed -n '2,12p' "$0" | sed 's/^# \?//'
      exit 0
      ;;
  esac
done

ROOT=$(cd "$(dirname "$0")" && pwd)
SRC="$ROOT/landing-stats.sh"
[ -f "$SRC" ] || { echo "missing $SRC" >&2; exit 1; }

# Prefer the known names from ops docs
C=""
for name in taler-hacktivism-bank taler-bank-hacktivism; do
  if podman ps --format '{{.Names}}' 2>/dev/null | grep -qx "$name"; then
    C=$name
    break
  fi
done
if [ -z "$C" ]; then
  C=$(podman ps --format '{{.Names}}' 2>/dev/null | grep -i bank | head -1 || true)
fi
[ -n "$C" ] || { echo "no bank container running" >&2; exit 1; }
echo "container=$C"

# Host password → container /root (if not already there)
if [ -f /root/bank-explorer-password.txt ]; then
  podman cp /root/bank-explorer-password.txt "$C:/root/bank-explorer-password.txt" 2>/dev/null || true
fi

if [ "$RUN_ONLY" != "1" ]; then
  podman exec "$C" mkdir -p /usr/local/bin /var/www/bank-landing
  podman cp "$SRC" "$C:/usr/local/bin/landing-stats.sh"
  podman exec "$C" chmod 755 /usr/local/bin/landing-stats.sh
  echo "installed /usr/local/bin/landing-stats.sh"
fi

# Ensure landing dir exists for nginx intro
podman exec "$C" mkdir -p /var/www/bank-landing

echo "running landing-stats.sh inside $C …"
podman exec \
  -e LANDING_DIR=/var/www/bank-landing \
  -e BANK_USER=explorer \
  "$C" /usr/local/bin/landing-stats.sh

if [ "$DO_CRON" = "1" ]; then
  # default: every minute (* * * * *); override with LANDING_STATS_CRON='*/5 * * * *'
  podman exec -e LANDING_STATS_CRON="$LANDING_STATS_CRON" "$C" bash -c '
    sched="${LANDING_STATS_CRON:-* * * * *}"
    line="$sched TZ=Europe/Zurich LANDING_DIR=/var/www/bank-landing /usr/local/bin/landing-stats.sh >>/var/log/landing-stats.log 2>&1"
    (crontab -l 2>/dev/null | grep -v landing-stats.sh; echo "$line") | crontab -
    echo "cron installed:"; crontab -l | grep landing-stats
  '
fi

echo "public check: curl -sS https://bank.hacktivism.ch/intro/stats.json | head"
# If host maps 9013 → container landing, show local file
podman exec "$C" head -c 400 /var/www/bank-landing/stats.json 2>/dev/null || true
echo
