#!/usr/bin/env bash
# alert-digest — emails a single summary of the day's spooled alerts, then
# rotates the spool. Run once daily from cron. If there were no alerts, it
# still sends a short "all quiet" line so you know monitoring is alive.

set -u
ALERT_EMAIL="canadasmarketplace@gmail.com"
ALERT_FROM="alerts@communitymarketplace.ca"
HOSTNAME=$(hostname -f 2>/dev/null || hostname)
DAY=$(date +%Y%m%d)
SPOOL="/var/spool/alert-digest/${DAY}.log"
TODAY=$(date '+%Y-%m-%d')

if [ -s "$SPOOL" ]; then
  TOTAL=$(grep -c '^\[' "$SPOOL" 2>/dev/null)
  SUMMARY=$(grep '^\[' "$SPOOL" | sed -E 's/^\[[^]]+\] //' | sort | uniq -c | sort -rn)
  BODY="Daily monitoring digest for $HOSTNAME — $TODAY

Total alerts today: $TOTAL

--- Grouped by type (count x message) ---
$SUMMARY

--- Full chronological log ---
$(cat "$SPOOL")"
  SUBJ="[DIGEST] $HOSTNAME: $TOTAL alerts on $TODAY"
else
  BODY="Daily monitoring digest for $HOSTNAME — $TODAY

No alerts today. All monitored services were healthy.
(Critical outages, if any, are sent immediately and also appear here.)"
  SUBJ="[DIGEST] $HOSTNAME: all quiet on $TODAY"
fi

printf '%s\n' "$BODY" | mail -r "$ALERT_FROM" -s "$SUBJ" "$ALERT_EMAIL" 2>/dev/null

# Retain 14 days of spools, drop older.
find /var/spool/alert-digest -name '*.log' -mtime +14 -delete 2>/dev/null
exit 0
