#!/bin/bash
# agent360-guard.sh
# Re-asserts the agent360 anti-OOM fix in case cpanel-monitoring-plugin
# regenerates /etc/agent360.ini (its header warns it auto-regenerates).
#
# Enforces:
#   [execution] threads = 10   (cap worker pile-up; default 100 caused 12GB OOM)
#   [httpd]     enabled = no    (status_page_url http://127.0.0.1/whm-server-status
#                                never resolves — Apache serves on :81/:444, not :80 —
#                                so every cycle hung and stacked workers)
# Only restarts agent360 if it actually changed something.
set -euo pipefail

INI=/etc/agent360.ini
[ -f "$INI" ] || exit 0

changed=0

# Enforce threads=10 under [execution]
cur_threads=$(awk '/^\[execution\]/{f=1;next} /^\[/{f=0} f&&/^threads=/{print $0}' "$INI" | head -1)
if [ "$cur_threads" != "threads=10" ]; then
    # rewrite the threads line within the [execution] section only
    awk '
        /^\[/{sec=$0}
        sec=="[execution]" && /^threads=/ {print "threads=10"; next}
        {print}
    ' "$INI" > "$INI.tmp" && mv "$INI.tmp" "$INI"
    changed=1
fi

# Enforce enabled=no under [httpd]
cur_httpd=$(awk '/^\[httpd\]/{f=1;next} /^\[/{f=0} f&&/^enabled=/{print $0}' "$INI" | head -1)
if [ "$cur_httpd" != "enabled=no" ]; then
    awk '
        /^\[/{sec=$0}
        sec=="[httpd]" && /^enabled=/ {print "enabled=no"; next}
        {print}
    ' "$INI" > "$INI.tmp" && mv "$INI.tmp" "$INI"
    changed=1
fi

if [ "$changed" -eq 1 ]; then
    logger -t agent360-guard "agent360.ini drifted from anti-OOM fix; re-asserted threads=10 / httpd enabled=no and restarting agent360"
    systemctl restart agent360.service || true
fi
exit 0
