#!/usr/bin/env bash
# Ensure /etc/httpd/conf.d/ssl.conf does not bind :443.
#
# The haproxy-manager container owns :443. Stock mod_ssl ssl.conf with
# `Listen 443 https` active causes haproxy-manager's docker network attach
# to fail silently while it still reports healthy (its in-container health
# check works against its own localhost). All customer SSL + renewal flows
# then 502 / fail with "Failed to connect to localhost port 8000" because
# the host can't reach the network-detached container.
#
# setup.sh handles this on fresh provisions by replacing /etc/httpd/conf.d/
# ssl.conf with our repo-managed version. But auto-updated servers that
# were provisioned BEFORE that logic existed (e.g. sdbees.cloud-hosting.io,
# discovered 2026-05-12) never had it applied. This script self-heals all
# three states idempotently and is safe to re-run.
#
# It also recreates haproxy-manager if it's currently in the network-
# detached zombie state (containers' Networks=={}), since `docker restart`
# alone won't fix that — Docker only attempts network attach at container
# creation time.

set -euo pipefail

SSL_CONF="/etc/httpd/conf.d/ssl.conf"
SSL_BAK="/etc/httpd/conf.d/ssl.conf.bak"

# Resolve repo-shipped fallback via tarball-relative path. update.sh runs
# versioned scripts BEFORE rsyncing configs/, so /root/whp/configs/ssl.conf
# may be stale during initial install — go to the source of truth shipped
# inside the same tarball as this script.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TARBALL_CONFIG="$(cd "${SCRIPT_DIR}/../../" 2>/dev/null && pwd)/configs/ssl.conf"

DISABLED_COMMENT="# Listen 443 https — disabled by WHP setup; haproxy-manager owns :443 (see feedback_haproxy_manager_port_443_conflict)"

needs_reload=0

# ---- 1. Bring ssl.conf into a sane state --------------------------------
if [[ -s "${SSL_CONF}" ]]; then
    # Non-empty ssl.conf present.
    if grep -q "^Listen 443 https" "${SSL_CONF}"; then
        sed -i "s|^Listen 443 https|${DISABLED_COMMENT}|" "${SSL_CONF}"
        echo "  ${SSL_CONF}: commented out Listen 443"
        needs_reload=1
    else
        echo "  ${SSL_CONF}: no active 'Listen 443 https' — leaving alone"
    fi
elif [[ -s "${SSL_BAK}" ]]; then
    # Renamed-to-.bak workaround from an earlier admin. Restore + edit.
    # The .bak rename was fragile because RPM's %config(noreplace) preserves
    # in-place edits but recreates missing files on package update.
    echo "  ${SSL_BAK} present, ${SSL_CONF} missing/empty — restoring and editing in place"
    mv "${SSL_BAK}" "${SSL_CONF}"
    sed -i "s|^Listen 443 https|${DISABLED_COMMENT}|" "${SSL_CONF}"
    needs_reload=1
elif [[ -f "${TARBALL_CONFIG}" ]]; then
    # Neither exists — bootstrap from the tarball's repo-managed version.
    echo "  no ssl.conf found, installing from tarball: ${TARBALL_CONFIG}"
    install -m 0644 "${TARBALL_CONFIG}" "${SSL_CONF}"
    needs_reload=1
else
    echo "  no ssl.conf, no ssl.conf.bak, no tarball fallback — mod_ssl likely not installed; skipping"
fi

# ---- 2. Reload apache if we touched anything ----------------------------
if [[ "${needs_reload}" -eq 1 ]]; then
    if systemctl is-active --quiet httpd; then
        httpd -t 2>&1
        systemctl reload httpd
        echo "  httpd reloaded"
    else
        echo "  httpd not running — skipping reload (will pick up on next start)"
    fi
fi

# ---- 3. Heal haproxy-manager if it's in the wedged state ----------------
# Signature: NetworkSettings.Networks == "{}" (network attach failed at
# create-time because something else held :443; container is "healthy"
# only because its internal localhost check works inside its detached net
# namespace). `docker restart` does NOT redo network setup — must recreate.
if docker inspect haproxy-manager >/dev/null 2>&1; then
    networks=$(docker inspect haproxy-manager -f"{{json .NetworkSettings.Networks}}")
    if [[ "${networks}" == "{}" ]]; then
        echo "  haproxy-manager is network-detached — recreating via container-manager.sh"
        /root/whp/scripts/container-manager.sh recreate haproxy-manager
    else
        echo "  haproxy-manager networking OK"
    fi
fi

echo "fix-stock-ssl-conf.sh: OK"
