#!/bin/bash

# SSL and Nginx Setup Script for houseofprayer.ddns.net
# This script configures Nginx with Let's Encrypt SSL certificates

set -e

DOMAIN="houseofprayer.ddns.net"
EMAIL="admin@houseofprayer.ddns.net"  # Change this to your email
NGINX_CONF="/etc/nginx/sites-available/church-music"
NGINX_ENABLED="/etc/nginx/sites-enabled/church-music"
PROJECT_DIR="/media/pts/Website/Church_HOP_MusicData/new-site"

echo "🔐 Setting up SSL and Nginx for $DOMAIN"
echo "================================================"

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo "❌ Please run as root (use sudo)"
    exit 1
fi

# Step 1: Check if ports are available
echo ""
echo "📡 Checking if ports 80 and 443 are available..."
if lsof -Pi :80 -sTCP:LISTEN -t >/dev/null 2>&1; then
    echo "⚠️  Port 80 is in use. Stopping nginx if running..."
    systemctl stop nginx 2>/dev/null || true
fi

# Step 2: Create certbot directory
echo ""
echo "📁 Creating certbot directory..."
mkdir -p /var/www/certbot

# Step 3: Check if SSL certificate already exists
if [ -d "/etc/letsencrypt/live/$DOMAIN" ]; then
    echo ""
    echo "✅ SSL certificate already exists for $DOMAIN"
    echo "   To renew: sudo certbot renew"
else
    echo ""
    echo "🔒 Obtaining SSL certificate from Let's Encrypt..."
    echo "   Domain: $DOMAIN"
    echo "   Email: $EMAIL"
    echo ""
    
    # Obtain SSL certificate
    certbot certonly --standalone \
        --preferred-challenges http \
        --agree-tos \
        --email "$EMAIL" \
        --non-interactive \
        -d "$DOMAIN" || {
            echo ""
            echo "❌ Failed to obtain SSL certificate!"
            echo "   Please check:"
            echo "   1. DNS record for $DOMAIN points to this server"
            echo "   2. Port 80 is accessible from the internet"
            echo "   3. No firewall blocking port 80"
            exit 1
        }
    
    echo "✅ SSL certificate obtained successfully!"
fi

# Step 4: Copy Nginx configuration
echo ""
echo "📝 Installing Nginx configuration..."
cp "$PROJECT_DIR/nginx-ssl.conf" "$NGINX_CONF"

# Step 5: Create symbolic link if it doesn't exist
if [ ! -L "$NGINX_ENABLED" ]; then
    ln -s "$NGINX_CONF" "$NGINX_ENABLED"
    echo "✅ Nginx site enabled"
else
    echo "✅ Nginx site already enabled"
fi

# Step 6: Test Nginx configuration
echo ""
echo "🔍 Testing Nginx configuration..."
nginx -t || {
    echo "❌ Nginx configuration test failed!"
    exit 1
}

# Step 7: Restart Nginx
echo ""
echo "🔄 Restarting Nginx..."
systemctl restart nginx
systemctl enable nginx

# Step 8: Set up automatic SSL renewal
echo ""
echo "⏰ Setting up automatic SSL renewal..."
if ! crontab -l 2>/dev/null | grep -q "certbot renew"; then
    (crontab -l 2>/dev/null; echo "0 3 * * * certbot renew --quiet && systemctl reload nginx") | crontab -
    echo "✅ Auto-renewal cron job added (runs daily at 3 AM)"
else
    echo "✅ Auto-renewal already configured"
fi

# Step 9: Update backend CORS if needed
echo ""
echo "🔧 Checking backend CORS configuration..."
echo "   Backend should allow: https://$DOMAIN"

# Step 10: Show status
echo ""
echo "================================================"
echo "✨ SSL and Nginx setup complete!"
echo "================================================"
echo ""
echo "🌐 Your site is now available at:"
echo "   https://$DOMAIN"
echo ""
echo "📊 Services Status:"
systemctl status nginx --no-pager | grep -E "Active:|Loaded:"
echo ""
echo "🔒 SSL Certificate Info:"
certbot certificates | grep -A3 "$DOMAIN" || true
echo ""
echo "📝 Next Steps:"
echo "   1. Make sure your backend is running: cd $PROJECT_DIR/backend && node server.js"
echo "   2. Make sure your frontend is running: cd $PROJECT_DIR/frontend && npm run dev"
echo "   3. Test your site: https://$DOMAIN"
echo "   4. Check SSL rating: https://www.ssllabs.com/ssltest/analyze.html?d=$DOMAIN"
echo ""
echo "🔄 To renew SSL manually: sudo certbot renew"
echo "🔍 View Nginx logs: sudo tail -f /var/log/nginx/church-music-*.log"
echo ""
