#!/bin/sh
#
# /etc/cron.daily/fpm-metrics-prune
#
# fpm-sample.sh already names its output by date (pool-YYYY-MM-DD.jsonl), so
# logrotate would only append a redundant ".1" to a filename that carries its own
# date. Compressing and pruning by age is all that is needed.
#
# Measured volume: 387 bytes/line, 11,520 lines/day (2 pools x 5760 ticks at
# INTERVAL=15) = 4.26 MB/day raw, 0.34 MB/day gzipped (12.7:1 -- the keys repeat
# on every line, so it compresses very well). At RETENTION_DAYS=45 that settles
# at ~23 MB total and stays there: 2 days raw plus 43 gzipped. 45 days covers a
# monthly reporting cycle plus the previous one for comparison.
#
# gzip preserves the original file's mtime, so an age-based delete still measures
# from when the data was written, not from when it was compressed. Verified.
#
set -eu

DIR="${DIR:-/var/log/php8.3-fpm/metrics}"
RETENTION_DAYS="${RETENTION_DAYS:-45}"
COMPRESS_AFTER_DAYS="${COMPRESS_AFTER_DAYS:-2}"

[ -d "$DIR" ] || exit 0

# Leave the most recent days uncompressed so the summary script and the portal UI
# can read them without zcat while they are the ones being looked at.
# ! -name 'rollup-*' guards the permanent hourly archive written by fpm-daily-rollup.
# Those are named .json (not .jsonl) so they already fall outside these globs, but the
# exclusion is stated rather than relied upon: a future rename to .jsonl would
# otherwise start silently deleting the only history that outlives RETENTION_DAYS.
find "$DIR" -maxdepth 1 -type f ! -name 'rollup-*' \( -name '*.jsonl' -o -name '*.log' \) \
	-mtime "+$COMPRESS_AFTER_DAYS" -exec gzip -q {} + || true

# Delete by age across BOTH compressed and uncompressed names. Matching only
# *.gz would let a file whose gzip failed live forever, which is exactly the
# silent-growth case this job exists to prevent.
deleted=$(find "$DIR" -maxdepth 1 -type f ! -name 'rollup-*' \
	\( -name '*.jsonl' -o -name '*.log' -o -name '*.jsonl.gz' -o -name '*.log.gz' \) \
	-mtime "+$RETENTION_DAYS" -print -delete | wc -l)

# Auditable: proves the job ran and says what it did, so "are old logs actually
# being deleted?" is answerable from the journal instead of by inspection.
#   journalctl -t fpm-metrics-prune --since '7 days ago'
logger -t fpm-metrics-prune \
	"retention=${RETENTION_DAYS}d deleted=${deleted} remaining=$(
		find "$DIR" -maxdepth 1 -type f | wc -l
	) size=$(du -sh "$DIR" 2>/dev/null | cut -f1)"

# The portal admin UI reads these files directly as www-data. Group-readable, not
# world-readable: the traffic snapshots carry client IP addresses.
chgrp -R www-data "$DIR" 2>/dev/null || true
chmod 2750 "$DIR" 2>/dev/null || true
find "$DIR" -maxdepth 1 -type f -exec chmod 640 {} + 2>/dev/null || true
