#!/bin/bash
# Deploy tinqs-proxy on Lightsail (replaces Caddy).
# Run as: ssh ubuntu@46.51.144.31 'bash -s' < proxy/deploy.sh
#
# Prerequisites: binary already built by Gitea Actions or manually:
#   cd proxy && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o tinqs-proxy-linux-amd64 .
#   scp tinqs-proxy-linux-amd64 ubuntu@46.51.144.31:/tmp/

set -euo pipefail

BIN=/usr/local/bin/tinqs-proxy
SVC=/etc/systemd/system/tinqs-proxy.service
CERT_DIR=/var/lib/tinqs-proxy/certs

echo "=== tinqs-proxy deploy ==="

# 1. Create cert dir
sudo mkdir -p "$CERT_DIR"
sudo chown ubuntu:ubuntu "$CERT_DIR"

# 2. Install binary (from Gitea Actions output or manual upload)
SRC="$HOME/bot-arikigame/public/proxy/releases/tinqs-proxy-linux-amd64"
if [ ! -f "$SRC" ]; then
  SRC="/tmp/tinqs-proxy-linux-amd64"
fi
if [ ! -f "$SRC" ]; then
  echo "ERROR: no binary found at ~/bot-arikigame/public/proxy/releases/ or /tmp/"
  exit 1
fi
sudo cp "$SRC" "$BIN"
sudo chmod +x "$BIN"
echo "OK binary: $BIN"

# 3. Install systemd unit
cat <<'UNIT' | sudo tee "$SVC" > /dev/null
[Unit]
Description=tinqs-proxy — TLS reverse proxy for *.arikigame.com
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=/usr/local/bin/tinqs-proxy
Restart=always
RestartSec=3
Environment=CERT_DIR=/var/lib/tinqs-proxy/certs
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
User=ubuntu
Group=ubuntu
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=read-only
ReadWritePaths=/var/lib/tinqs-proxy

[Install]
WantedBy=multi-user.target
UNIT
echo "OK systemd unit"

# 4. Stop Caddy (free ports 80/443)
if systemctl is-active --quiet caddy; then
  sudo systemctl stop caddy
  sudo systemctl disable caddy
  echo "OK stopped + disabled caddy"
else
  echo "OK caddy not running"
fi

# 5. Start tinqs-proxy
sudo systemctl daemon-reload
sudo systemctl enable tinqs-proxy
sudo systemctl start tinqs-proxy
sleep 2

if systemctl is-active --quiet tinqs-proxy; then
  echo "OK tinqs-proxy is running"
  sudo journalctl -u tinqs-proxy --no-pager -n 5
else
  echo "FAIL tinqs-proxy did not start"
  sudo journalctl -u tinqs-proxy --no-pager -n 20
  exit 1
fi

echo ""
echo "=== Done. Caddy disabled, tinqs-proxy active. ==="
echo "Test: curl -I https://git.arikigame.com"
echo "Rollback: sudo systemctl stop tinqs-proxy  # Caddy fully removed 2026-04-27"
