#!/bin/bash
# ============================================================
#  install-subdomains.sh
#  Sets up Apache virtual hosts for the API and Developer-docs
#  subdomains on a server that already has the main domain
#  configured and the Flask app running.
#
#  Usage:
#    chmod +x install-subdomains.sh
#    sudo bash install-subdomains.sh yourdomain.com
#
#  What it does:
#    1. Creates /etc/apache2/sites-available/api.DOMAIN.conf
#    2. Creates /etc/apache2/sites-available/developers.DOMAIN.conf
#    3. Enables both sites
#    4. Optionally obtains Let's Encrypt SSL certs (via certbot)
#    5. Reloads Apache
#
#  Prerequisites:
#    - Apache2 with mod_proxy, mod_proxy_http, mod_headers enabled
#    - Flask/gunicorn already running (port read from .env APP_PORT)
#    - DNS A-records pointing api.DOMAIN and developers.DOMAIN
#      to this server's IP address
# ============================================================

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. Provide a bare domain without 'www', e.g., example.com"
    exit 1
fi

# ── Load APP_PORT from .env (same directory as this script) ───────────────────
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ENV_FILE="${SCRIPT_DIR}/.env"
if [ -f "$ENV_FILE" ]; then
    APP_PORT=$(grep -E '^APP_PORT=' "$ENV_FILE" | head -1 | cut -d= -f2 | tr -d '[:space:]')
fi
APP_PORT="${APP_PORT:-6001}"

API_DOMAIN="api.${DOMAIN}"
DEV_DOMAIN="developers.${DOMAIN}"
FLASK_BACKEND="http://127.0.0.1:${APP_PORT}"

echo "==> Setting up subdomains for ${DOMAIN}"
echo "    API docs      : ${API_DOMAIN}"
echo "    Dev docs      : ${DEV_DOMAIN}"
echo "    Flask backend : ${FLASK_BACKEND}  (APP_PORT=${APP_PORT})"
echo ""

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

# ── Write API subdomain virtual host ─────────────────────────────────────────
echo "==> Writing ${API_DOMAIN} virtual host..."
sudo tee /etc/apache2/sites-available/${API_DOMAIN}.conf > /dev/null <<EOF
<VirtualHost *:80>
    ServerName ${API_DOMAIN}

    ProxyPreserveHost On
    ProxyPass        / ${FLASK_BACKEND}/
    ProxyPassReverse / ${FLASK_BACKEND}/

    RequestHeader set X-Forwarded-Proto "http"
    RequestHeader set X-Forwarded-Host  "${API_DOMAIN}"

    ErrorLog  /var/log/apache2/${API_DOMAIN}-error.log
    CustomLog /var/log/apache2/${API_DOMAIN}-access.log combined
</VirtualHost>
EOF

# ── Write developers subdomain virtual host ───────────────────────────────────
echo "==> Writing ${DEV_DOMAIN} virtual host..."
sudo tee /etc/apache2/sites-available/${DEV_DOMAIN}.conf > /dev/null <<EOF
<VirtualHost *:80>
    ServerName ${DEV_DOMAIN}

    ProxyPreserveHost On
    ProxyPass        / ${FLASK_BACKEND}/
    ProxyPassReverse / ${FLASK_BACKEND}/

    RequestHeader set X-Forwarded-Proto "http"
    RequestHeader set X-Forwarded-Host  "${DEV_DOMAIN}"

    ErrorLog  /var/log/apache2/${DEV_DOMAIN}-error.log
    CustomLog /var/log/apache2/${DEV_DOMAIN}-access.log combined
</VirtualHost>
EOF

# ── Enable sites ──────────────────────────────────────────────────────────────
sudo a2ensite ${API_DOMAIN}.conf
sudo a2ensite ${DEV_DOMAIN}.conf

# ── Optional SSL via certbot ──────────────────────────────────────────────────
read -p "Obtain Let's Encrypt SSL certificates for both subdomains? (y/n): " want_ssl
if [ "$want_ssl" = "y" ]; then
    if ! command -v certbot &> /dev/null; then
        echo "==> Installing certbot..."
        sudo apt-get install -y python3-certbot-apache
    fi
    echo "==> Obtaining certificate for ${API_DOMAIN}..."
    sudo certbot --apache -d "${API_DOMAIN}" --non-interactive --agree-tos \
        --cert-name "${API_DOMAIN}" --redirect 2>/dev/null || \
        sudo certbot --apache -d "${API_DOMAIN}"

    echo "==> Obtaining certificate for ${DEV_DOMAIN}..."
    sudo certbot --apache -d "${DEV_DOMAIN}" --non-interactive --agree-tos \
        --cert-name "${DEV_DOMAIN}" --redirect 2>/dev/null || \
        sudo certbot --apache -d "${DEV_DOMAIN}"
fi

# ── Reload Apache ─────────────────────────────────────────────────────────────
echo "==> Reloading Apache..."
sudo apachectl configtest && sudo systemctl reload apache2

echo ""
echo "Done! Your subdomains are now configured:"
echo "  API docs  : http://${API_DOMAIN}"
echo "  Dev docs  : http://${DEV_DOMAIN}"
echo ""
echo "Make sure these DNS A-records point to this server's IP:"
echo "  ${API_DOMAIN}  →  $(curl -s ifconfig.me 2>/dev/null || echo '<your-server-ip>')"
echo "  ${DEV_DOMAIN}  →  $(curl -s ifconfig.me 2>/dev/null || echo '<your-server-ip>')"
