#!/bin/bash
# Setup HTTPS for QuickBooks POS Help Server
# Run this when you have a domain name and are ready for HTTPS

set -e

echo "=========================================="
echo "HTTPS Setup for QuickBooks POS Help"
echo "=========================================="
echo ""
echo "Prerequisites:"
echo "  1. Domain name pointing to this server"
echo "  2. Ports 80 and 443 open in firewall"
echo ""
read -p "Enter your domain name (e.g., qbpos.prompttech.com): " DOMAIN

if [ -z "$DOMAIN" ]; then
    echo "Error: Domain name required"
    exit 1
fi

echo ""
echo "Installing Certbot for Let's Encrypt SSL..."
sudo apt update
sudo apt install -y certbot python3-certbot-nginx

echo ""
echo "Obtaining SSL certificate for $DOMAIN..."
sudo certbot certonly --standalone -d "$DOMAIN" --agree-tos --non-interactive --email admin@prompttech.com

CERT_PATH="/etc/letsencrypt/live/$DOMAIN/fullchain.pem"
KEY_PATH="/etc/letsencrypt/live/$DOMAIN/privkey.pem"

if [ ! -f "$CERT_PATH" ]; then
    echo "Error: Certificate not found at $CERT_PATH"
    exit 1
fi

echo ""
echo "Updating server configuration..."

# Update secure_production_server.py
sed -i "s|USE_HTTPS = False|USE_HTTPS = True|g" /home/pts/Documents/QBPOS_Help_Web/secure_production_server.py
sed -i "s|SSL_CERT_FILE = \".*\"|SSL_CERT_FILE = \"$CERT_PATH\"|g" /home/pts/Documents/QBPOS_Help_Web/secure_production_server.py
sed -i "s|SSL_KEY_FILE = \".*\"|SSL_KEY_FILE = \"$KEY_PATH\"|g" /home/pts/Documents/QBPOS_Help_Web/secure_production_server.py
sed -i "s|PORT = 8888|PORT = 443|g" /home/pts/Documents/QBPOS_Help_Web/secure_production_server.py

echo ""
echo "Setting up certificate auto-renewal..."
sudo systemctl enable certbot.timer
sudo systemctl start certbot.timer

echo ""
echo "Restarting service..."
sudo systemctl restart qbpos-help

echo ""
echo "=========================================="
echo "HTTPS Setup Complete!"
echo "=========================================="
echo ""
echo "Your server is now accessible at:"
echo "  https://$DOMAIN/"
echo ""
echo "Certificate auto-renewal is enabled."
echo "Certbot will automatically renew before expiry."
