#!/usr/bin/env bash
#
# Add /var/log/whp-ssl-orchestrator.log to the AI monitor's [log_sources]
# section in /etc/whp/ai-monitor.conf so renewal failures get noticed.
# Idempotent.

set -euo pipefail

CONF="/etc/whp/ai-monitor.conf"
LOG_FILE="/var/log/whp-ssl-orchestrator.log"
KEY="ssl_orchestrator"
LINE="${KEY} = ${LOG_FILE}"

# Pre-touch the log so the AI monitor doesn't error on a missing file before
# the cron's first successful run writes to it.
touch "${LOG_FILE}"
chmod 0644 "${LOG_FILE}"

if [ ! -f "${CONF}" ]; then
    echo "WARN: ${CONF} not present; skipping. AI monitor may not be installed on this host."
    exit 0
fi

if grep -qE "^${KEY}[[:space:]]*=" "${CONF}"; then
    # Already there — make sure the value matches; rewrite only if it doesn't.
    EXISTING=$(grep -E "^${KEY}[[:space:]]*=" "${CONF}" | head -1 | sed -E 's/^[^=]+=[[:space:]]*//')
    if [ "${EXISTING}" = "${LOG_FILE}" ]; then
        echo "${KEY} log source already configured."
        exit 0
    fi
    sed -i -E "s|^${KEY}[[:space:]]*=.*|${LINE}|" "${CONF}"
    echo "Updated ${KEY} log source path in ${CONF}."
    exit 0
fi

# Insert under the [log_sources] section header. If [log_sources] doesn't
# exist, append at the end with the section header.
if grep -qE '^\[log_sources\]' "${CONF}"; then
    awk -v line="${LINE}" '
        BEGIN { in_section = 0; inserted = 0 }
        /^\[log_sources\]/ { print; in_section = 1; next }
        in_section && /^\[/ && !inserted { print line; inserted = 1; in_section = 0; print; next }
        { print }
        END { if (in_section && !inserted) print line }
    ' "${CONF}" > "${CONF}.new"
    mv "${CONF}.new" "${CONF}"
else
    {
        echo
        echo "[log_sources]"
        echo "${LINE}"
    } >> "${CONF}"
fi

echo "Added ${KEY} log source to ${CONF}."
