#!/bin/bash
# ============================================
# Document Translation API - SSL Setup Script
# ============================================
# Usage: ./scripts/setup-ssl.sh <domain> <email>
# Example: ./scripts/setup-ssl.sh translate.example.com admin@example.com

set -e

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

if [ -z "$DOMAIN" ] || [ -z "$EMAIL" ]; then
    echo "Usage: ./scripts/setup-ssl.sh <domain> <email>"
    echo "Example: ./scripts/setup-ssl.sh translate.example.com admin@example.com"
    exit 1
fi

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo -e "${YELLOW}Setting up SSL for $DOMAIN${NC}"

# Create directory for certbot
mkdir -p ./docker/certbot/www
mkdir -p ./docker/certbot/conf

# Create initial nginx config for ACME challenge
cat > ./docker/nginx/conf.d/certbot.conf << EOF
server {
    listen 80;
    server_name $DOMAIN;
    
    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }
    
    location / {
        return 301 https://\$host\$request_uri;
    }
}
EOF

# Start nginx with HTTP only
echo "Starting nginx for certificate request..."
docker compose up -d nginx

# Request certificate
echo "Requesting Let's Encrypt certificate..."
docker run --rm \
    -v "$(pwd)/docker/certbot/www:/var/www/certbot" \
    -v "$(pwd)/docker/certbot/conf:/etc/letsencrypt" \
    certbot/certbot certonly \
    --webroot \
    --webroot-path=/var/www/certbot \
    --email "$EMAIL" \
    --agree-tos \
    --no-eff-email \
    -d "$DOMAIN"

# Copy certificates
echo "Installing certificates..."
cp ./docker/certbot/conf/live/$DOMAIN/fullchain.pem ./docker/nginx/ssl/
cp ./docker/certbot/conf/live/$DOMAIN/privkey.pem ./docker/nginx/ssl/
cp ./docker/certbot/conf/live/$DOMAIN/chain.pem ./docker/nginx/ssl/

# Remove temporary config
rm ./docker/nginx/conf.d/certbot.conf

# Restart nginx with SSL
echo "Restarting nginx with SSL..."
docker compose restart nginx

echo -e "${GREEN}SSL setup complete for $DOMAIN${NC}"
echo ""
echo "To auto-renew certificates, add this to crontab:"
echo "0 0 1 * * cd $(pwd) && ./scripts/renew-ssl.sh"
