#!/usr/bin/env bash
# ─────────────────────────────────────────────────────────────────────────────
# Torvali — Apache + Let's Encrypt setup (run as root on the server)
# Usage: sudo bash scripts/setup-apache.sh
# ─────────────────────────────────────────────────────────────────────────────
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ENV_FILE="$SCRIPT_DIR/../.env"

# Load .env
if [ ! -f "$ENV_FILE" ]; then
  echo "ERROR: .env not found at $ENV_FILE"; exit 1
fi
export $(grep -v '^#' "$ENV_FILE" | grep -v '^\s*$' | xargs)

DOMAIN="${STORE_DOMAIN:?STORE_DOMAIN not set in .env}"
EMAIL="${CERTBOT_EMAIL:?CERTBOT_EMAIL not set in .env}"
PORT="${PORT:-8800}"
APACHE_SITES="${APACHE_SITES_DIR:-/etc/apache2/sites-available}"
WEBROOT="/var/www/html"

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "  Torvali Apache + SSL Setup"
echo "  Domain : $DOMAIN"
echo "  Port   : $PORT (Node app)"
echo "  Email  : $EMAIL"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# ── 1. Install Apache & Certbot if missing ────────────────────────────────────
echo "[1/5] Installing Apache & Certbot..."
apt-get update -qq
apt-get install -y apache2 certbot python3-certbot-apache

# ── 2. Enable required modules ────────────────────────────────────────────────
echo "[2/5] Enabling Apache modules..."
a2enmod proxy proxy_http headers rewrite ssl deflate

# ── 3. Serve HTTP temporarily for ACME challenge ──────────────────────────────
echo "[3/5] Obtaining SSL certificate..."
mkdir -p "$WEBROOT/.well-known/acme-challenge"

cat > "$APACHE_SITES/${DOMAIN}-acme.conf" <<EOF
<VirtualHost *:80>
    ServerName ${DOMAIN}
    ServerAlias www.${DOMAIN}
    DocumentRoot ${WEBROOT}
    <Directory ${WEBROOT}>
        Require all granted
    </Directory>
</VirtualHost>
EOF

a2ensite "${DOMAIN}-acme.conf"
systemctl reload apache2

certbot certonly \
    --webroot \
    --webroot-path "$WEBROOT" \
    --non-interactive \
    --agree-tos \
    --email "$EMAIL" \
    -d "$DOMAIN" \
    -d "www.$DOMAIN"

a2dissite "${DOMAIN}-acme.conf"
rm -f "$APACHE_SITES/${DOMAIN}-acme.conf"

# ── 4. Write final vhost (HTTP redirect + HTTPS reverse proxy) ────────────────
echo "[4/5] Writing virtual host config..."
cat > "$APACHE_SITES/${DOMAIN}.conf" <<EOF
# Torvali — ${DOMAIN}
# Generated by setup-apache.sh — do not edit manually

<VirtualHost *:80>
    ServerName ${DOMAIN}
    ServerAlias www.${DOMAIN}
    RewriteEngine On
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</VirtualHost>

<VirtualHost *:443>
    ServerName ${DOMAIN}
    ServerAlias www.${DOMAIN}

    SSLEngine on
    SSLCertificateFile    /etc/letsencrypt/live/${DOMAIN}/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/${DOMAIN}/privkey.pem
    Include /etc/letsencrypt/options-ssl-apache.conf

    # ── Reverse proxy to Node.js ──────────────────────────────────────────────
    ProxyPreserveHost On
    ProxyRequests     Off
    ProxyPass        / http://127.0.0.1:${PORT}/
    ProxyPassReverse / http://127.0.0.1:${PORT}/

    RequestHeader set X-Forwarded-Proto "https"
    RequestHeader set X-Real-IP         "%{REMOTE_ADDR}s"

    # ── Security headers ──────────────────────────────────────────────────────
    Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
    Header always set X-Content-Type-Options    "nosniff"
    Header always set X-Frame-Options           "SAMEORIGIN"
    Header always set Referrer-Policy           "strict-origin-when-cross-origin"

    # ── Compression ───────────────────────────────────────────────────────────
    AddOutputFilterByType DEFLATE text/html text/css application/javascript application/json

    ErrorLog  \${APACHE_LOG_DIR}/${DOMAIN}-ssl-error.log
    CustomLog \${APACHE_LOG_DIR}/${DOMAIN}-ssl-access.log combined
</VirtualHost>
EOF

a2ensite "${DOMAIN}.conf"

# ── 5. Auto-renewal cron ──────────────────────────────────────────────────────
echo "[5/5] Setting up auto-renewal..."
if ! crontab -l 2>/dev/null | grep -q "certbot renew"; then
    (crontab -l 2>/dev/null; echo "0 3 * * * certbot renew --quiet && systemctl reload apache2") | crontab -
fi

systemctl reload apache2

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "  ✓ Done! https://${DOMAIN} is live."
echo "  Node app must be running on port ${PORT}"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
