#!/bin/bash
# Send email notification when a systemd service fails
# Usage: systemd-failure-notify <service-name>

NOTIFY_EMAIL="alerts@tylervigario.com"

if [[ -z "${1:-}" ]]; then
    echo "Usage: systemd-failure-notify <service-name>" >&2
    exit 1
fi

SERVICE="$1"
HOSTNAME=$(hostname)
DATE=$(date '+%Y-%m-%d %H:%M:%S %Z')

# Get service status and recent logs
STATUS=$(systemctl status "$SERVICE" 2>&1 | head -20)
LOGS=$(journalctl -u "$SERVICE" --since "10 minutes ago" --no-pager 2>&1 | tail -50)

# Send email
mail -s "[ALERT] Service failed on ${HOSTNAME}: ${SERVICE}" "$NOTIFY_EMAIL" <<EOF
Service failure detected on ${HOSTNAME}

Service: ${SERVICE}
Time: ${DATE}

=== Service Status ===
${STATUS}

=== Recent Logs ===
${LOGS}

---
This is an automated message from systemd-failure-notify
EOF

echo "[$(date)] Sent failure notification for ${SERVICE}"
