#!/bin/bash
# Setup SSL for quickbooksposhelp.access.ly

set -e

DOMAIN="quickbooksposhelp.access.ly"
NGINX_CONF="/home/pts/Documents/QBPOS_Help_Web/qbpos-help-ssl.conf"

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

# Check if domain is accessible
echo "Step 1: Verifying DNS..."
echo "Please ensure $DOMAIN points to this server's IP address"
echo "Current server IP addresses:"
ip addr show | grep "inet " | grep -v "127.0.0.1" | awk '{print "  - " $2}'
echo ""
read -p "Press Enter when DNS is configured and propagated..."

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

# Stop the Python server on port 8888
echo ""
echo "Step 3: Stopping Python development server..."
pkill -f "python3.*server.py" || echo "No server to stop"

# Copy nginx configuration
echo ""
echo "Step 4: Configuring Nginx..."
sudo cp "$NGINX_CONF" /etc/nginx/sites-available/qbpos-help
sudo ln -sf /etc/nginx/sites-available/qbpos-help /etc/nginx/sites-enabled/qbpos-help

# Remove default nginx site if it exists
sudo rm -f /etc/nginx/sites-enabled/default

# Test nginx configuration
echo ""
echo "Step 5: Testing Nginx configuration..."
sudo nginx -t

# Ensure firewall allows HTTP and HTTPS
echo ""
echo "Step 6: Configuring firewall..."
sudo ufw allow 80/tcp comment "HTTP for SSL verification"
sudo ufw allow 443/tcp comment "HTTPS"
sudo ufw status

# Start nginx
echo ""
echo "Step 7: Starting Nginx..."
sudo systemctl enable nginx
sudo systemctl restart nginx

# Get SSL certificate
echo ""
echo "Step 8: Obtaining SSL certificate from Let's Encrypt..."
sudo certbot --nginx -d "$DOMAIN" --non-interactive --agree-tos --email admin@prompttech.com --redirect

# Setup auto-renewal
echo ""
echo "Step 9: Setting up automatic certificate renewal..."
sudo systemctl enable certbot.timer
sudo systemctl start certbot.timer

echo ""
echo "=========================================="
echo "SSL Setup Complete!"
echo "=========================================="
echo ""
echo "Your site is now available at:"
echo "  https://$DOMAIN"
echo ""
echo "HTTP traffic will automatically redirect to HTTPS"
echo ""
echo "Certificate will auto-renew before expiration"
echo ""
echo "To check certificate status:"
echo "  sudo certbot certificates"
echo ""
echo "To test renewal:"
echo "  sudo certbot renew --dry-run"
echo ""
