#!/bin/bash
# SSL certificate setup for fleety.ghomsoft.com
# Run this ONCE on the VPS before the first HTTPS deploy.
set -e

DOMAIN="fleety.ghomsoft.com"
EMAIL="admin@ghomsoft.com"  # Change to your email
SSL_DIR="/etc/nginx/ssl"
CONTAINER="fleety_app"

echo "=== SSL Setup for $DOMAIN ==="

# 1. Start with HTTP-only config
echo "[1/4] Switching to HTTP-only config temporarily..."
docker exec "$CONTAINER" cp /etc/nginx/templates/nginx-http.conf /etc/nginx/http.d/default.conf
docker exec "$CONTAINER" nginx -s reload

# 2. Install certbot and get certificate
echo "[2/4] Obtaining SSL certificate via Let's Encrypt..."
docker exec "$CONTAINER" apk add --no-cache certbot
docker exec "$CONTAINER" certbot certonly --standalone \
    -d "$DOMAIN" \
    --email "$EMAIL" \
    --agree-tos \
    --non-interactive

# 3. Copy certs to nginx SSL directory
echo "[3/4] Copying certificates..."
docker exec "$CONTAINER" mkdir -p "$SSL_DIR"
docker exec "$CONTAINER" cp "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" "$SSL_DIR/"
docker exec "$CONTAINER" cp "/etc/letsencrypt/live/$DOMAIN/privkey.pem" "$SSL_DIR/"
docker exec "$CONTAINER" cp "/etc/letsencrypt/live/$DOMAIN/chain.pem" "$SSL_DIR/"

# 4. Switch to HTTPS config
echo "[4/4] Switching to HTTPS config..."
docker exec "$CONTAINER" cp /etc/nginx/http.d/default.conf /etc/nginx/http.d/default.conf.http-bak
docker exec "$CONTAINER" cp /etc/nginx/templates/nginx-ssl.conf /etc/nginx/http.d/default.conf
docker exec "$CONTAINER" nginx -s reload

echo ""
echo "=== SSL setup complete! $DOMAIN is now serving HTTPS ==="
echo "Renewal (runs automatically via certbot): docker exec $CONTAINER certbot renew"
