#!/bin/bash
# ============================================================
#  operate.sh  —  Configure Apache for the Flask file converter
#  Installs virtual hosts for the main domain, api subdomain,
#  and developers subdomain, then optionally obtains SSL certs.
#
#  Usage:
#    chmod +x operate.sh
#    sudo bash operate.sh yourdomain.com
# ============================================================

set -e

if [ $# -lt 1 ]; then
    echo "Usage: $0 <domain>"
    echo "Example: $0 yourdomain.com"
    exit 1
fi

DOMAIN="$1"

if [[ ! "$DOMAIN" =~ ^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
    echo "Invalid domain format. Please provide a valid domain without 'www', e.g., example.com"
    exit 1
fi

if [ ! -f "proxy-domain.conf" ]; then
    echo "Error: proxy-domain.conf not found in the current directory."
    exit 1
fi

if [ ! -d "/etc/apache2/sites-available" ]; then
    echo "Error: Apache sites-available directory not found."
    exit 1
fi

API_DOMAIN="api.${DOMAIN}"
DEV_DOMAIN="developers.${DOMAIN}"
CONF_FILE="/etc/apache2/sites-available/${DOMAIN}-default.conf"

echo "==> Enabling required Apache modules..."
sudo a2enmod proxy proxy_http headers rewrite ssl 2>/dev/null || true

# Copy template and substitute the real domain for every occurrence of "domain"
echo "==> Writing Apache config: ${CONF_FILE}"
sudo cp "proxy-domain.conf" "${CONF_FILE}"
sudo sed -i "s|domain|${DOMAIN}|g" "${CONF_FILE}"

# Enable the site
sudo a2ensite "${DOMAIN}-default.conf"

# Test config before reloading
echo "==> Testing Apache configuration..."
sudo apachectl configtest

echo "==> Reloading Apache..."
sudo systemctl reload apache2

echo ""
echo "Apache virtual hosts configured for:"
echo "  Main site : http://${DOMAIN}"
echo "  API docs  : http://${API_DOMAIN}"
echo "  Dev docs  : http://${DEV_DOMAIN}"
echo ""

# ── Optional SSL via certbot ──────────────────────────────────────────────────
read -p "Obtain Let's Encrypt SSL certificates? (y/n): " enable_ssl

if [ "$enable_ssl" == "y" ]; then
    if ! command -v certbot &> /dev/null; then
        echo "==> Installing certbot..."
        sudo apt-get install -y python3-certbot-apache
    fi

    echo "==> Obtaining SSL certificate for ${DOMAIN} and www.${DOMAIN}..."
    sudo certbot --apache -d "${DOMAIN}" -d "www.${DOMAIN}" \
        --cert-name "${DOMAIN}" --redirect

    echo "==> Obtaining SSL certificate for ${API_DOMAIN}..."
    sudo certbot --apache -d "${API_DOMAIN}" --cert-name "${API_DOMAIN}" --redirect

    echo "==> Obtaining SSL certificate for ${DEV_DOMAIN}..."
    sudo certbot --apache -d "${DEV_DOMAIN}" --cert-name "${DEV_DOMAIN}" --redirect

    echo ""
    echo "SSL enabled! Your sites are now available over HTTPS:"
    echo "  https://${DOMAIN}"
    echo "  https://${API_DOMAIN}"
    echo "  https://${DEV_DOMAIN}"
fi

echo ""
echo "Done! Remember to add DNS A-records for each subdomain pointing to this server's IP."
