#!/usr/bin/env bash
# Install nginx vhosts for OMNL production domains
set -euo pipefail

REPO_DIR="${OMNL_BANK_ROOT:-$HOME/smom-dbis-138}"
SNIPPET_SRC="$REPO_DIR/deploy/nginx/omnl-common-locations.conf"
VHOST_SRC="$REPO_DIR/deploy/nginx/omnl-domains.conf"
SNIPPET_DST="/etc/nginx/snippets/omnl-common-locations.conf"
VHOST_DST="/etc/nginx/sites-available/omnl-domains"
VHOST_LINK="/etc/nginx/sites-enabled/omnl-domains"

log() { echo "[$(date -Iseconds)] $*"; }

if [ ! -f "$SNIPPET_SRC" ] || [ ! -f "$VHOST_SRC" ]; then
  echo "Missing nginx configs under $REPO_DIR/deploy/nginx" >&2
  exit 1
fi

log "Installing nginx snippet + vhosts..."
sudo mkdir -p /etc/nginx/snippets
sudo cp "$SNIPPET_SRC" "$SNIPPET_DST"
sudo cp "$VHOST_SRC" "$VHOST_DST"
sudo ln -sf "$VHOST_DST" "$VHOST_LINK"

log "Testing nginx configuration..."
sudo nginx -t

log "Reloading nginx..."
sudo systemctl reload nginx

log "Verifying local routes (Host header)..."
check_host() {
  local host="$1"
  local expect="$2"
  local code
  code=$(curl -s -o /dev/null -w '%{http_code}' -H "Host: $host" "http://127.0.0.1/")
  log "  $host -> HTTP $code (expect redirect to $expect)"
}

check_host exchange.omdnl.org /trade
check_host secure.d-bis.org /central-bank
check_host office24.omdnl.org /office-24
check_host digital.omdnl.org /swap

log "OMNL domain deploy complete"
log "DNS: point all domains A record to 76.53.10.34 (or Cloudflare proxy to origin)"
