#!/usr/bin/env bash
# One-time VPS provisioning for bigscreen10.maxbrandenbarg.nl.
# Assumes Debian/Ubuntu with nginx + certbot already installed.
#
# Usage on the VPS (as a sudoer):
#   git clone git@github.com:YOUR_USER/YOUR_REPO.git /tmp/bigscreen10-setup
#   cd /tmp/bigscreen10-setup
#   bash deploy/setup-vps.sh
#   rm -rf /tmp/bigscreen10-setup

set -euo pipefail

DOMAIN="bigscreen10.maxbrandenbarg.nl"
WEBROOT="/var/www/bigscreen10"
NGX_AVAILABLE="/etc/nginx/sites-available/bigscreen10"
NGX_ENABLED="/etc/nginx/sites-enabled/bigscreen10"
HTPASSWD="/etc/nginx/.htpasswd-bigscreen10"
EMAIL="maxbrandenbarg@gmail.com"

echo "=== bigscreen10 VPS setup ==="
echo "Domain:  $DOMAIN"
echo "Webroot: $WEBROOT"
echo

# ── 1. Web root ────────────────────────────────────────────────────
echo "[1/5] Creating $WEBROOT"
sudo mkdir -p "$WEBROOT"
sudo chown -R "$USER":www-data "$WEBROOT"
sudo chmod -R g+rX "$WEBROOT"
echo "<!doctype html><meta charset=utf-8><title>Coming soon</title><body style='background:#0d0d0d;color:#fff;font-family:system-ui;padding:80px;text-align:center'>Coming soon.</body>" \
  | sudo tee "$WEBROOT/index.html" > /dev/null

# ── 2. Basic-auth password ─────────────────────────────────────────
echo
echo "[2/5] Basic-auth credentials for the preview gate"
read -rp "  username [bigscreen]: " AUTHUSER
AUTHUSER="${AUTHUSER:-bigscreen}"
read -rsp "  password: " AUTHPASS; echo
HASH=$(openssl passwd -apr1 "$AUTHPASS")
echo "$AUTHUSER:$HASH" | sudo tee "$HTPASSWD" > /dev/null
sudo chmod 640 "$HTPASSWD"
sudo chown root:www-data "$HTPASSWD"
echo "  wrote $HTPASSWD"

# ── 3. nginx site ──────────────────────────────────────────────────
echo
echo "[3/5] Installing nginx site config"
sudo cp "$(dirname "$0")/nginx-bigscreen10.conf" "$NGX_AVAILABLE"
sudo ln -sf "$NGX_AVAILABLE" "$NGX_ENABLED"
sudo nginx -t

# ── 4. SSL via certbot (Let's Encrypt) ─────────────────────────────
echo
echo "[4/5] Issuing TLS cert via certbot"
echo "  (DNS A-record for $DOMAIN must already point to this server)"
sudo certbot --nginx -d "$DOMAIN" --non-interactive --agree-tos -m "$EMAIL" --redirect

# ── 5. Reload nginx ────────────────────────────────────────────────
echo
echo "[5/5] Reloading nginx"
sudo systemctl reload nginx

echo
echo "✓ Done. Visit https://$DOMAIN — you should hit the basic-auth prompt."
echo "  GitHub Actions can now rsync into $WEBROOT on every push to main."
