#!/bin/bash
#
# Rewrite one site's Apache proxy configs correctly.
#
# Two things it puts back that a hand written config keeps losing:
#
#   ProxyPreserveHost On
#     Without it Apache replaces the Host header with the backend address, so
#     Django sees 127.0.0.1. PanelSubdomainMiddleware matches the request host
#     against the tenant's cms_subdomain to mount the CMS at /, so a lost Host
#     header means panel.example.com serves the public site instead of the
#     panel, and System Info reports a certificate for 127.0.0.1.
#
#   No /media/ exclusion
#     Media is served by Django through the proxy. Excluding /media/ here means
#     the route in config/urls.py is never reached and every uploaded image
#     404s. See the media memory note.
#
#   bash fix-vhost.sh <sysuser> <port> [panel-host]
#
#     bash fix-vhost.sh mostafaei 8002
#     bash fix-vhost.sh hpglobal  8010 panel.hpglobal.uk
#
# The panel host defaults to panel.<sysuser>.com, which is only right when the
# site is a .com. Pass it explicitly for anything else.
#
set -uo pipefail

SYSUSER="${1:?usage: fix-vhost.sh <sysuser> <port> [panel-host]}"
PORT="${2:?usage: fix-vhost.sh <sysuser> <port> [panel-host]}"
PANEL="${3:-panel.${SYSUSER}.com}"
STAMP=$(date +%F-%H%M%S)

echo "  user  $SYSUSER"
echo "  port  $PORT"
echo "  panel $PANEL"
echo

wrote=0
for kind in std ssl; do
    for d in /etc/apache2/conf.d/userdata/${kind}/2_4/${SYSUSER}/*/; do
        [ -d "$d" ] || continue
        f="${d}proxy.conf"
        [ -f "$f" ] && cp -f "$f" "${f}.bak-${STAMP}"
        {
            echo "ProxyPreserveHost On"
            echo "ProxyPass / http://127.0.0.1:${PORT}/"
            echo "ProxyPassReverse / http://127.0.0.1:${PORT}/"
            # Without this Django cannot tell the request was HTTPS, so
            # SECURE_SSL_REDIRECT sends it round in a loop forever.
            [ "$kind" = "ssl" ] && echo 'RequestHeader set X-Forwarded-Proto "https"'
        } > "$f"
        echo "  wrote ${f#/etc/apache2/conf.d/userdata/}"
        wrote=$((wrote + 1))
    done
done

[ "$wrote" -eq 0 ] && { echo "  no vhost config found for ${SYSUSER}"; exit 1; }

echo
apachectl configtest || { echo "  config test failed, NOT restarting"; exit 1; }
systemctl restart httpd && sleep 2
echo "  httpd: $(systemctl is-active httpd)"

echo
echo "→ What the panel host now answers with"
printf '  %-40s %s\n' "https://${PANEL}/" \
  "$(curl -s -o /dev/null -w '%{http_code}' "https://${PANEL}/")"
printf '  %-40s %s\n' "  redirects to" \
  "$(curl -s -o /dev/null -w '%{redirect_url}' "https://${PANEL}/")"
echo
echo "  A panel host should redirect to a login page, not serve the public site."
echo "  Rollback: restore ${f}.bak-${STAMP} and restart httpd"
