#!/usr/bin/env bash
#
# Sets up a free SSL certificate via Let's Encrypt / Certbot.
# Run AFTER the domain's DNS A record points at this server's IP,
# and AFTER Nginx is installed and the site config is in place
# (deployment/nginx/crop-ai-system.conf).
#
# Usage: sudo bash deployment/scripts/setup_ssl.sh YOUR_DOMAIN.com

set -euo pipefail

DOMAIN="${1:-}"

if [ -z "$DOMAIN" ]; then
    echo "Usage: sudo bash deployment/scripts/setup_ssl.sh YOUR_DOMAIN.com"
    exit 1
fi

echo "=== Requesting certificate for $DOMAIN ==="
certbot --nginx -d "$DOMAIN" -d "www.$DOMAIN" --non-interactive --agree-tos -m admin@"$DOMAIN" --redirect

echo "=== Setting up auto-renewal ==="
systemctl enable certbot.timer
systemctl start certbot.timer

echo "=== Testing renewal (dry run) ==="
certbot renew --dry-run

echo "=== SSL setup complete for $DOMAIN ==="
echo "Certificate will auto-renew via certbot.timer"
