#!/bin/sh
# docs/adr/0061 Sec.20: postgresql-common's stock /etc/logrotate.d/postgresql-common
# ships "weekly, rotate 10" with no size cap -- the real gap behind the
# 2026-09-05 incident where postgresql-17-main.log grew to 38GB and filled
# /var to 0 bytes free before the next scheduled weekly rotation could ever
# run (root cause of the flood itself was a separate query bug, fixed
# independently -- this closes the rotation gap so ANY future runaway growth,
# from any cause, can't repeat the same outage).
#
# This idempotently patches that file -- owned by the postgresql-common
# package, not ours, so a maintainer-script edit rather than a conflicting
# .install of the same path -- to add "size 250M". logrotate's own semantics
# make "size" REPLACE the time interval rather than combine with it
# (confirmed live: "note: 'size' overrides previously specified 'weekly'"),
# giving a hard-bounded on-disk footprint of size*rotate = 2.5GB regardless
# of growth rate, instead of "however much accumulated in a week." Paired
# with argus-postgresql-logrotate.timer, which runs this check every 15
# minutes rather than waiting for the stock once-a-day logrotate.timer.
#
# Safe to re-run at any time; skips cleanly if postgresql-common isn't
# installed yet (same pattern as argus-db-provision).
set -e

TARGET=/etc/logrotate.d/postgresql-common

if [ ! -f "$TARGET" ]; then
    echo "[argus-postgresql-logrotate-provision] $TARGET not present (postgresql-common not installed yet) -- skipping." >&2
    echo "[argus-postgresql-logrotate-provision] Re-run 'argus-postgresql-logrotate-provision' (as root) once postgresql-common is installed." >&2
    exit 0
fi

if grep -q "^[[:space:]]*size 250M" "$TARGET"; then
    echo "[argus-postgresql-logrotate-provision] size cap already present in $TARGET -- nothing to do."
    exit 0
fi

if grep -q "^[[:space:]]*weekly[[:space:]]*$" "$TARGET"; then
    sed -i 's/^[[:space:]]*weekly[[:space:]]*$/       size 250M/' "$TARGET"
    echo "[argus-postgresql-logrotate-provision] Replaced 'weekly' with 'size 250M' in $TARGET."
else
    # Unexpected stanza shape (a future postgresql-common package version
    # changed its default config) -- insert right after the opening brace
    # of the first block rather than guessing further or failing outright.
    sed -i '0,/{/s//{\n       size 250M/' "$TARGET"
    echo "[argus-postgresql-logrotate-provision] Inserted 'size 250M' into $TARGET (no 'weekly' line found to replace)."
fi
