# ============================================================
#  Apache reverse-proxy template for the Flask file-converter
#
#  Two placeholders are substituted before installation:
#    "domain"     → real domain (e.g. yourdomain.com)
#    ${APP_PORT}  → port from .env  (default 6001)
#
#  operate.sh / install-domain.sh replaces both via:
#    DOMAIN=yourdomain.com
#    APP_PORT=$(grep ^APP_PORT .env | cut -d= -f2); APP_PORT=${APP_PORT:-6001}
#    sed "s|domain|${DOMAIN}|g" proxy-domain.conf \
#      | APP_PORT=${APP_PORT} envsubst '${APP_PORT}' \
#      > /etc/apache2/sites-available/${DOMAIN}.conf
#
#  Virtual hosts created:
#    domain              →  main site
#    www.domain          →  redirect to domain
#    api.domain          →  REST API (Flask subdomain="api")
#    developers.domain   →  Developer docs (Flask subdomain="developers")
# ============================================================

# ------------------------------------------------------------------
#  1. Main domain
# ------------------------------------------------------------------
<VirtualHost *:80>
    ServerName domain
    ServerAlias www.domain

    # Redirect www → bare domain (keeps SEO canonical)
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

    ProxyPreserveHost On
    ProxyPass        / http://127.0.0.1:${APP_PORT}/
    ProxyPassReverse / http://127.0.0.1:${APP_PORT}/

    RequestHeader set X-Forwarded-Proto "http"

    ErrorLog  /var/log/apache2/domain-error.log
    CustomLog /var/log/apache2/domain-access.log combined
</VirtualHost>

# ------------------------------------------------------------------
#  2. API subdomain  →  api.domain
# ------------------------------------------------------------------
<VirtualHost *:80>
    ServerName api.domain

    ProxyPreserveHost On
    ProxyPass        / http://127.0.0.1:${APP_PORT}/
    ProxyPassReverse / http://127.0.0.1:${APP_PORT}/

    RequestHeader set X-Forwarded-Proto "http"

    # Pass the real subdomain host so Flask subdomain routing works
    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>

# ------------------------------------------------------------------
#  3. Developer-docs subdomain  →  developers.domain
# ------------------------------------------------------------------
<VirtualHost *:80>
    ServerName developers.domain

    ProxyPreserveHost On
    ProxyPass        / http://127.0.0.1:${APP_PORT}/
    ProxyPassReverse / http://127.0.0.1:${APP_PORT}/

    RequestHeader set X-Forwarded-Proto "http"

    RequestHeader set X-Forwarded-Host developers.domain

    ErrorLog  /var/log/apache2/developers.domain-error.log
    CustomLog /var/log/apache2/developers.domain-access.log combined
</VirtualHost>
