#!/usr/bin/env bash
# Deploy the command-stream stack to a CPU streaming server (London VPS).
# Run from the developer machine. The box must already be provisioned
# (packages, wine, runtime, engine profiles, replays, service user).
set -euo pipefail

APP_ROOT=$(cd "$(dirname "$0")/.." && pwd)      # experiments/d3d9-command-stream
REPO_ROOT=$(cd "$APP_ROOT/../.." && pwd)
HOST=${W3CS_CPU_HOST:-danny@82.39.133.153}
SSH=(ssh -o BatchMode=yes "$HOST")
RSYNC=(rsync -a --delete -e "ssh -o BatchMode=yes" --rsync-path="sudo rsync")

echo "=== sync app tree"
"${RSYNC[@]}" --exclude .git --exclude "*.log" --exclude __pycache__ \
  "$APP_ROOT/" "$HOST:/home/ubuntu/w3cs-lab/app/"

echo "=== sync infra (criu build inputs)"
"${SSH[@]}" sudo mkdir -p /home/ubuntu/war3-repo/infra/runtime \
  /home/ubuntu/war3-repo/infra/patches
"${RSYNC[@]}" --exclude __pycache__ "$REPO_ROOT/infra/runtime/" \
  "$HOST:/home/ubuntu/war3-repo/infra/runtime/"
"${RSYNC[@]}" "$REPO_ROOT/infra/patches/" \
  "$HOST:/home/ubuntu/war3-repo/infra/patches/"

echo "=== remote build + install"
"${SSH[@]}" sudo bash -s <<'REMOTE'
set -euo pipefail
LAB=/home/ubuntu/w3cs-lab
APP=$LAB/app

# Relay (native) and the game-side proxy DLL.
make -C "$APP/native" d3d9.dll
g++ -O3 -g0 -std=c++20 -Wall -Wextra -Werror -pthread \
  -DGST_USE_UNSTABLE_API "$APP/native/w3cs_webrtc_relay.cpp" \
  -o "$APP/native/w3cs-webrtc-relay" \
  $(pkg-config --cflags --libs gstreamer-1.0 gstreamer-webrtc-1.0 \
    gstreamer-sdp-1.0 libsoup-3.0 json-glib-1.0 x11 xfixes xtst zlib libzstd)

# lab-live.sh expects its collaborators flat in LAB_ROOT.
install -m 0755 "$APP/native/w3cs-webrtc-relay" "$LAB/w3cs-webrtc-relay"
install -m 0644 "$APP/native/d3d9.dll" "$LAB/d3d9.dll"
install -m 0755 "$APP/native/lab-live.sh" "$APP/native/lab-game-session.sh" \
  "$APP/native/lab-switch-replay.sh" "$LAB/"
install -m 0644 "$APP/native/stage-replay-session.py" \
  "$APP/native/materialize-catalog-replay.py" \
  "$APP/lab_live_bridge.py" "$APP/protocol.py" "$APP/relay.py" "$LAB/"

# Test index data: one entry per staged replay, grouped by engine profile.
python3 - <<'PY'
import json, glob, os
out = []
for p in sorted(glob.glob('/home/ubuntu/w3cs-lab/replays/*.json')):
    rid = os.path.basename(p)[:-5]
    with open(p) as f:
        d = json.load(f)
    out.append({'id': rid,
                'profile': d.get('engineProfile', 'native-1285'),
                'map': d.get('mapPath', '')})
with open('/home/ubuntu/w3cs-lab/app/replays.json', 'w') as f:
    json.dump(out, f, indent=1)
print(f"replays.json: {len(out)} entries")
PY

# TLS front (secure context for WebGPU): nginx + self-signed IP cert until
# a real domain points at the box.
command -v nginx >/dev/null || {
  DEBIAN_FRONTEND=noninteractive apt-get -yq install nginx >/dev/null
}
DOMAIN=london-cpu-worker.war3replays.com
mkdir -p /etc/ssl/w3cs /var/www/certbot
if [ -d "/etc/letsencrypt/live/$DOMAIN" ]; then
  ln -sf "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" /etc/ssl/w3cs/w3cs.crt
  ln -sf "/etc/letsencrypt/live/$DOMAIN/privkey.pem" /etc/ssl/w3cs/w3cs.key
elif [ ! -f /etc/ssl/w3cs/w3cs.crt ]; then
  BOX_IP=$(ip -4 -br addr show scope global | awk '{print $3}' | cut -d/ -f1 | head -1)
  openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 \
    -keyout /etc/ssl/w3cs/w3cs.key -out /etc/ssl/w3cs/w3cs.crt \
    -days 3650 -nodes -subj "/CN=w3cs-cpu-server" \
    -addext "subjectAltName=IP:$BOX_IP" 2>/dev/null
  chmod 600 /etc/ssl/w3cs/w3cs.key
fi
install -m 0644 "$APP/deploy/nginx-w3cs.conf" /etc/nginx/conf.d/w3cs.conf
rm -f /etc/nginx/sites-enabled/default
nginx -t
systemctl enable --now nginx >/dev/null 2>&1
systemctl reload nginx

install -m 0755 "$APP/deploy/w3cs-watchdog.sh" /usr/local/sbin/w3cs-watchdog.sh
install -m 0755 "$APP/deploy/w3cs-seat-launch.sh" /usr/local/sbin/w3cs-seat-launch.sh
install -m 0644 "$APP/deploy/w3cs-live@.service" \
  "$APP/deploy/w3cs-web.service" "$APP/deploy/w3cs-watchdog.service" \
  "$APP/deploy/w3cs-watchdog.timer" /etc/systemd/system/

# Per-seat wine prefixes (independent games need independent prefixes; the
# Documents/Replays staging path and the wineserver are per prefix).
for SEAT in 1 2 3; do
  P32="/opt/war3-runtime/classic/prefix-seat$SEAT"
  if [ ! -d "$P32" ]; then
    cp -a /opt/war3-runtime/classic/prefix "$P32"
    chown -R ubuntu:ubuntu "$P32"
  fi
  P64="/opt/war3-runtime/classic-131/prefix64-seat$SEAT"
  if [ ! -d "$P64" ] && [ -d /opt/war3-runtime/classic-131/prefix64 ]; then
    cp -a /opt/war3-runtime/classic-131/prefix64 "$P64"
    chown -R ubuntu:ubuntu "$P64"
  fi
done

ufw allow 40000:40599/udp >/dev/null

chown -R ubuntu:ubuntu "$LAB" /home/ubuntu/war3-repo

systemctl daemon-reload
# The singleton unit is replaced by per-seat template instances.
systemctl disable --now w3cs-live.service >/dev/null 2>&1 || true
rm -f /etc/systemd/system/w3cs-live.service
systemctl daemon-reload
systemctl enable w3cs-web w3cs-live@1 w3cs-live@2 w3cs-live@3 \
  w3cs-watchdog.timer >/dev/null 2>&1
systemctl restart w3cs-web
systemctl restart w3cs-live@1 w3cs-live@2 w3cs-live@3
systemctl start w3cs-watchdog.timer
sleep 2
systemctl --no-pager --plain status w3cs-web "w3cs-live@*" \
  | grep -E "service|Active"
REMOTE

echo "=== deployed. Test page: https://london-cpu-worker.war3replays.com/poc/cpu-test-index.html"
