#!/bin/bash
# ============================================================
# SSL Setup with Let's Encrypt (Certbot)
# Usage: sudo bash setup_ssl.sh your-domain.com [email]
# ============================================================
set -euo pipefail

RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; BLUE='\033[0;34m'; NC='\033[0m'
log()  { echo -e "${GREEN}[✓]${NC} $1"; }
info() { echo -e "${BLUE}[→]${NC} $1"; }
err()  { echo -e "${RED}[✗]${NC} $1"; exit 1; }

DOMAIN="${1:-}"
EMAIL="${2:-admin@${1}}"

[[ $EUID -ne 0 ]] && err "Run as root: sudo bash setup_ssl.sh domain.com"
[[ -z "$DOMAIN" ]] && err "Usage: sudo bash setup_ssl.sh your-domain.com [email]"

info "Setting up SSL for: ${DOMAIN}"

# Install Certbot
apt-get install -y -qq certbot python3-certbot-nginx
log "Certbot installed"

# Obtain certificate
certbot --nginx \
    --non-interactive \
    --agree-tos \
    --email "${EMAIL}" \
    --domains "${DOMAIN}" \
    --redirect
log "SSL certificate obtained"

# Update Nginx config with security headers for HTTPS
cat >> /etc/nginx/sites-available/cryptomining <<NGINX_SSL

# HSTS (after SSL is enabled)
# add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
NGINX_SSL

# Auto-renew test
certbot renew --dry-run
log "Auto-renewal verified"

# Enable renewal timer
systemctl enable --now certbot.timer
log "Auto-renewal timer enabled"

echo ""
log "SSL active: https://${DOMAIN}"
echo -e "Certificate expires: $(certbot certificates 2>/dev/null | grep 'Expiry Date' | head -1 | awk '{print $3, $4}')"
