#!/bin/bash
# ============================================================================
# StartOS Registry - VPS Setup Script
# ============================================================================
# Run this on your Hetzner VPS as root (or with sudo).
# It installs Node.js, nginx, certbot, creates a service user,
# deploys the registry, and sets up TLS.
#
# Usage:
#   scp -r startos-registry/ root@YOUR_VPS_IP:/tmp/
#   ssh root@YOUR_VPS_IP
#   bash /tmp/startos-registry/scripts/setup-vps.sh
#
# Prerequisites:
#   - DNS A record for registry.satsflows.com pointing to your VPS IP
#   - Ubuntu 22.04 or Debian 12
# ============================================================================

set -euo pipefail

DOMAIN="registry.satsflows.com"
INSTALL_DIR="/opt/startos-registry"
SERVICE_USER="registry"

echo ""
echo "  StartOS Registry - VPS Setup"
echo "  ============================="
echo "  Domain:  $DOMAIN"
echo "  Install: $INSTALL_DIR"
echo ""

# ------------------------------------------------------------------
# 1. Install system packages
# ------------------------------------------------------------------
echo "[1/7] Installing system packages..."
apt-get update -qq
apt-get install -y -qq nginx certbot python3-certbot-nginx curl

# Install Node.js 20 LTS if not present
if ! command -v node &>/dev/null; then
    echo "  Installing Node.js 20..."
    curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
    apt-get install -y -qq nodejs
fi

echo "  Node.js $(node --version)"
echo "  npm $(npm --version)"
echo "  nginx $(nginx -v 2>&1 | cut -d/ -f2)"

# ------------------------------------------------------------------
# 2. Create service user
# ------------------------------------------------------------------
echo "[2/7] Creating service user '$SERVICE_USER'..."
if ! id "$SERVICE_USER" &>/dev/null; then
    useradd --system --no-create-home --shell /usr/sbin/nologin "$SERVICE_USER"
fi

# ------------------------------------------------------------------
# 3. Deploy application
# ------------------------------------------------------------------
echo "[3/7] Deploying registry to $INSTALL_DIR..."
mkdir -p "$INSTALL_DIR"

# Copy files (we're running from the script's parent directory)
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_DIR="$(dirname "$SCRIPT_DIR")"

cp "$REPO_DIR/server.js" "$INSTALL_DIR/"
cp "$REPO_DIR/registry.json" "$INSTALL_DIR/"
cp "$REPO_DIR/package.json" "$INSTALL_DIR/"
cp -r "$REPO_DIR/packages" "$INSTALL_DIR/"

# Install Node dependencies
cd "$INSTALL_DIR"
npm install --production --quiet

# Set ownership
chown -R "$SERVICE_USER:$SERVICE_USER" "$INSTALL_DIR"

echo "  Deployed to $INSTALL_DIR"

# ------------------------------------------------------------------
# 4. Install systemd service
# ------------------------------------------------------------------
echo "[4/7] Installing systemd service..."
cp "$REPO_DIR/startos-registry.service" /etc/systemd/system/
systemctl daemon-reload
systemctl enable startos-registry
systemctl start startos-registry

echo "  Service started"

# ------------------------------------------------------------------
# 5. Configure nginx (HTTP only first, for certbot)
# ------------------------------------------------------------------
echo "[5/7] Configuring nginx..."

# Write a temporary HTTP-only config for certbot
cat > "/etc/nginx/sites-available/$DOMAIN" << 'NGINX_TEMP'
server {
    listen 80;
    server_name registry.satsflows.com;

    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        proxy_pass http://127.0.0.1:3030;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_buffering off;
        client_max_body_size 500M;
    }
}
NGINX_TEMP

mkdir -p /var/www/certbot
ln -sf "/etc/nginx/sites-available/$DOMAIN" /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default
nginx -t && systemctl reload nginx

# ------------------------------------------------------------------
# 6. Obtain TLS certificate
# ------------------------------------------------------------------
echo "[6/7] Obtaining TLS certificate for $DOMAIN..."
echo ""
echo "  IMPORTANT: Make sure your DNS A record for $DOMAIN"
echo "  points to this server's IP before continuing."
echo ""
read -p "  Press Enter when DNS is ready (or Ctrl+C to skip TLS)..."

certbot --nginx -d "$DOMAIN" --non-interactive --agree-tos --email "grant@ten31.xyz" --redirect

# ------------------------------------------------------------------
# 7. Install the full nginx config with TLS
# ------------------------------------------------------------------
echo "[7/7] Installing production nginx config..."
cp "$REPO_DIR/nginx.conf" "/etc/nginx/sites-available/$DOMAIN"
nginx -t && systemctl reload nginx

# ------------------------------------------------------------------
# Done!
# ------------------------------------------------------------------
echo ""
echo "  =========================================="
echo "  Setup complete!"
echo "  =========================================="
echo ""
echo "  Registry URL:  https://$DOMAIN"
echo "  Health check:  https://$DOMAIN/health"
echo "  Package index: https://$DOMAIN/package/v0/index"
echo ""
echo "  Users add this URL in StartOS:"
echo "    Marketplace -> Change -> Add custom registry"
echo "    URL: https://$DOMAIN"
echo ""
echo "  Manage the service:"
echo "    systemctl status startos-registry"
echo "    systemctl restart startos-registry"
echo "    journalctl -u startos-registry -f"
echo ""
echo "  To reload packages without restarting:"
echo "    systemctl reload startos-registry"
echo ""
