#!/usr/bin/env bash
# alert-spool — funnel point for all monitoring alerts.
# Non-critical alerts are appended to a daily spool and delivered once/day by
# alert-digest. Truly critical events (a site/DB actually DOWN) still send
# immediately so a real outage is never delayed by digest batching.
#
# Usage: alert-spool <LEVEL> <subject> [body]
#   LEVEL: DOWN|CRITICAL  -> sent immediately AND recorded in digest
#          everything else -> spooled for the daily digest only

set -u
LEVEL="${1:-INFO}"
SUBJECT="${2:-(no subject)}"
BODY="${3:-}"
ALERT_EMAIL="canadasmarketplace@gmail.com"
ALERT_FROM="alerts@communitymarketplace.ca"
HOSTNAME=$(hostname -f 2>/dev/null || hostname)
TS=$(date '+%Y-%m-%d %H:%M:%S')
SPOOL="/var/spool/alert-digest/$(date +%Y%m%d).log"

# Always record into the day's spool (one line header + indented body)
{
  echo "[$TS] [$LEVEL] $SUBJECT"
  [ -n "$BODY" ] && printf '%s\n' "$BODY" | sed 's/^/    /'
  echo "----"
} >> "$SPOOL" 2>/dev/null

# Immediate passthrough ONLY for genuine outages.
case "$LEVEL" in
  DOWN|CRITICAL)
    msg="Server:  $HOSTNAME
Level:   $LEVEL
Time:    $TS
$SUBJECT

$BODY"
    if command -v mail &>/dev/null; then
      printf '%s\n' "$msg" | mail -r "$ALERT_FROM" -s "[$LEVEL] $HOSTNAME: $SUBJECT" "$ALERT_EMAIL" 2>/dev/null
    else
      logger -p daemon.crit -t alert-spool "$LEVEL: $SUBJECT"
    fi
    ;;
esac
exit 0
