#!/usr/bin/env bash
# Send alert via email. Called by monitoring scripts.
# Usage: send-alert <LEVEL> <message>
# LEVEL: DOWN | CRITICAL | WARN | RECOVERED | BLOCKED | INFO

LEVEL="${1:-INFO}"
MESSAGE="${2:-No message}"
HOSTNAME=$(hostname -f 2>/dev/null || hostname)
ALERT_EMAIL="canadasmarketplace@gmail.com"
ALERT_FROM="alerts@communitymarketplace.ca"
SUBJECT="[$LEVEL] $HOSTNAME: $MESSAGE"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S UTC')

BODY="Server:    $HOSTNAME
Level:     $LEVEL
Time:      $TIMESTAMP
Message:   $MESSAGE

--- System Snapshot ---
$(uptime 2>/dev/null)
$(free -h 2>/dev/null)
$(df -h / /home 2>/dev/null | head -5)
Apache: $(systemctl is-active httpd 2>/dev/null || echo 'unknown')
Nginx:  $(systemctl is-active nginx 2>/dev/null || echo 'unknown')
---"

# Funnel through alert-spool: DOWN/CRITICAL send immediately, everything else
# is batched into the once-daily digest (see /usr/local/bin/alert-spool).
if [ -x /usr/local/bin/alert-spool ]; then
    /usr/local/bin/alert-spool "$LEVEL" "$MESSAGE" "$BODY"
    exit 0
fi

# Fallbacks if the spooler is missing.
if command -v mail &>/dev/null; then
    echo "$BODY" | mail -r "$ALERT_FROM" -s "$SUBJECT" "$ALERT_EMAIL" 2>/dev/null && exit 0
fi
logger -p daemon.crit -t server-resilience "ALERT $LEVEL: $MESSAGE"

exit 0
