#!/usr/bin/env bash
set -euo pipefail

# scripts/ssl_setup.sh
# Host-side script that helps setup nginx reverse proxy and obtain Let's Encrypt certificates.
# IMPORTANT: run this script on the host machine (not inside containers) with sudo.
# Usage: sudo ./scripts/ssl_setup.sh domain example.com email you@example.com

if [[ $(id -u) -ne 0 ]]; then
  echo "This script must be run as root (sudo)."
  exit 2
fi

DOMAIN="$1"
EMAIL="$2"

if [[ -z "$DOMAIN" || -z "$EMAIL" ]]; then
  echo "Usage: sudo ./scripts/ssl_setup.sh <domain> <email>"
  exit 1
fi

echo "Installing nginx and certbot (Debian/Ubuntu)..."
apt-get update
apt-get install -y nginx certbot python3-certbot-nginx

echo "Creating nginx config for reverse proxy..."
NGINX_CONF="/etc/nginx/sites-available/links.conf"
cat > "$NGINX_CONF" <<'EOF'
server {
    listen 80;
    server_name REPLACE_DOMAIN;

    location / {
        proxy_pass http://127.0.0.1:3000; # frontend
        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;
    }

    location /api/ {
        proxy_pass http://127.0.0.1:8000; # backend
        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;
    }

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

# Replace domain
sed -i "s|REPLACE_DOMAIN|$DOMAIN|g" "$NGINX_CONF"

# Enable
ln -sf "$NGINX_CONF" /etc/nginx/sites-enabled/links.conf
mkdir -p /var/www/certbot

echo "Testing nginx config and reloading..."
nginx -t
systemctl reload nginx

echo "Obtaining Let's Encrypt certificate for $DOMAIN..."
certbot --nginx -d "$DOMAIN" --non-interactive --agree-tos --email "$EMAIL" || {
  echo "certbot failed; you can retry manually: certbot --nginx -d $DOMAIN"
}

echo "SSL setup complete. Nginx should be proxying to frontend/backend on ports 3000/8000"
