#!/bin/bash

# SSL Setup Script for skyartshop.dynns.com
# Run this script with sudo: sudo bash setup-ssl.sh

DOMAIN="skyartshop.dynns.com"
EMAIL="your-email@example.com"  # Change this to your email!
NGINX_CONF="/media/pts/Website/SkyArtShop/config/nginx-skyartshop.conf"
NGINX_ENABLED="/etc/nginx/sites-enabled/skyartshop"
NGINX_AVAILABLE="/etc/nginx/sites-available/skyartshop"

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

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo "❌ Please run this script with sudo:"
    echo "   sudo bash setup-ssl.sh"
    exit 1
fi

# Step 1: Install Certbot if not installed
echo "📦 Step 1: Checking Certbot installation..."
if ! command -v certbot &> /dev/null; then
    echo "   Installing Certbot..."
    apt update
    apt install -y certbot python3-certbot-nginx
    echo "   ✅ Certbot installed"
else
    echo "   ✅ Certbot already installed"
fi

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

# Step 3: Create temporary nginx config (HTTP only for initial cert)
echo ""
echo "🔧 Step 3: Setting up temporary nginx config for certificate verification..."

cat > /etc/nginx/sites-available/skyartshop-temp << 'EOF'
server {
    listen 80;
    listen [::]:80;
    server_name skyartshop.dynns.com;

    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
        allow all;
    }

    location / {
        root /var/www/skyartshop/public;
        index index.html;
    }
}
EOF

# Disable old config and enable temp
rm -f /etc/nginx/sites-enabled/skyartshop 2>/dev/null
rm -f /etc/nginx/sites-enabled/skyartshop-temp 2>/dev/null
ln -sf /etc/nginx/sites-available/skyartshop-temp /etc/nginx/sites-enabled/skyartshop-temp

# Test and reload nginx
nginx -t && systemctl reload nginx
echo "   ✅ Temporary config active"

# Step 4: Obtain SSL Certificate
echo ""
echo "🔐 Step 4: Obtaining SSL certificate from Let's Encrypt..."
echo "   Domain: $DOMAIN"
echo ""

read -p "Enter your email for Let's Encrypt notifications: " USER_EMAIL
if [ -z "$USER_EMAIL" ]; then
    USER_EMAIL="admin@$DOMAIN"
fi

certbot certonly --webroot \
    -w /var/www/certbot \
    -d $DOMAIN \
    --email $USER_EMAIL \
    --agree-tos \
    --non-interactive \
    --force-renewal

if [ $? -ne 0 ]; then
    echo ""
    echo "❌ Certificate generation failed!"
    echo ""
    echo "Troubleshooting steps:"
    echo "1. Make sure your domain $DOMAIN points to this server's IP"
    echo "2. Check if port 80 is open in your firewall"
    echo "3. Try running: certbot certonly --standalone -d $DOMAIN"
    echo ""
    exit 1
fi

echo "   ✅ SSL certificate obtained successfully!"

# Step 5: Install the full nginx config with SSL
echo ""
echo "🔧 Step 5: Installing production nginx configuration..."

# Remove temp config
rm -f /etc/nginx/sites-enabled/skyartshop-temp
rm -f /etc/nginx/sites-available/skyartshop-temp

# Copy and enable production config
cp "$NGINX_CONF" "$NGINX_AVAILABLE"
ln -sf "$NGINX_AVAILABLE" "$NGINX_ENABLED"

# Test nginx config
echo "   Testing nginx configuration..."
nginx -t

if [ $? -eq 0 ]; then
    systemctl reload nginx
    echo "   ✅ Nginx reloaded with SSL configuration"
else
    echo "   ❌ Nginx configuration test failed!"
    exit 1
fi

# Step 6: Setup auto-renewal
echo ""
echo "🔄 Step 6: Setting up automatic certificate renewal..."
# Certbot auto-renewal is typically set up automatically via systemd timer
systemctl enable certbot.timer 2>/dev/null || true
systemctl start certbot.timer 2>/dev/null || true
echo "   ✅ Auto-renewal configured"

# Step 7: Final verification
echo ""
echo "=========================================="
echo "  ✅ SSL Setup Complete!"
echo "=========================================="
echo ""
echo "Your website is now available at:"
echo "  🔒 https://$DOMAIN"
echo ""
echo "Certificate details:"
certbot certificates --domain $DOMAIN 2>/dev/null | grep -A5 "Certificate Name"
echo ""
echo "Next steps:"
echo "1. Test your site: https://$DOMAIN"
echo "2. Test SSL: https://www.ssllabs.com/ssltest/analyze.html?d=$DOMAIN"
echo ""
echo "Certificate will auto-renew. To manually renew:"
echo "  sudo certbot renew"
echo ""
