#!/bin/bash
# BlackRoad fleet node Slack notifier
# Usage: slack-notify "message"
#        slack-notify alert "critical message"
#        slack-notify health          — auto health check + post
#        slack-notify heartbeat       — alive ping

source ~/.blackroad/slack-webhook.env 2>/dev/null
[ -z "$SLACK_WEBHOOK_URL" ] && { echo "No webhook"; exit 1; }

NODE=$(hostname)
IP=$(hostname -I 2>/dev/null | awk '{print $1}')
TS=$(date -u +%Y-%m-%dT%H:%M:%SZ)

post() {
  curl -sf -X POST -H "Content-type: application/json" --data "$1" "$SLACK_WEBHOOK_URL" >/dev/null 2>&1
}

case "${1:-message}" in
  alert)
    shift
    MSG="$*"
    post "{\"blocks\":[{\"type\":\"section\",\"text\":{\"type\":\"mrkdwn\",\"text\":\":rotating_light: *Fleet Alert — ${NODE}*\n${MSG}\"}},{\"type\":\"context\",\"elements\":[{\"type\":\"mrkdwn\",\"text\":\"${NODE} (${IP}) | ${TS}\"}]}]}"
    ;;
  health)
    TEMP=$(cat /sys/class/thermal/thermal_zone0/temp 2>/dev/null)
    TEMP_C=$(echo "scale=1; ${TEMP:-0}/1000" | bc 2>/dev/null || echo "?")
    MEM=$(free -m 2>/dev/null | awk '/Mem:/{printf "%d/%d", $3, $2}')
    DISK=$(df -h / 2>/dev/null | awk 'NR==2{print $5}')
    LOAD=$(cat /proc/loadavg 2>/dev/null | awk '{print $1}')
    UPTIME=$(uptime -p 2>/dev/null || uptime | sed 's/.*up /up /' | sed 's/,.*//')
    FAILED=$(systemctl --failed --no-legend 2>/dev/null | wc -l | tr -d " ")
    DOCKER=$(docker ps -q 2>/dev/null | wc -l | tr -d " ")
    THROTTLE=$(vcgencmd get_throttled 2>/dev/null | cut -d= -f2 || echo "n/a")

    EMOJI=":large_green_circle:"
    [ "${FAILED:-0}" -gt 0 ] && EMOJI=":large_yellow_circle:"
    [ "$THROTTLE" != "0x0" ] && [ "$THROTTLE" != "n/a" ] && EMOJI=":red_circle:"

    post "{\"blocks\":[{\"type\":\"section\",\"text\":{\"type\":\"mrkdwn\",\"text\":\"${EMOJI} *${NODE}* health\nTemp: ${TEMP_C}C | Mem: ${MEM}MB | Disk: ${DISK}\nLoad: ${LOAD} | Docker: ${DOCKER} | Failed: ${FAILED}\nThrottle: ${THROTTLE} | ${UPTIME}\"}},{\"type\":\"context\",\"elements\":[{\"type\":\"mrkdwn\",\"text\":\"${IP} | ${TS}\"}]}]}"
    ;;
  heartbeat)
    UPTIME=$(uptime -p 2>/dev/null || echo "up")
    post "{\"text\":\":heartbeat: ${NODE} alive — ${UPTIME} | ${TS}\"}"
    ;;
  *)
    MSG="$*"
    post "{\"blocks\":[{\"type\":\"section\",\"text\":{\"type\":\"mrkdwn\",\"text\":\":satellite: *${NODE}*\n${MSG}\"}},{\"type\":\"context\",\"elements\":[{\"type\":\"mrkdwn\",\"text\":\"${IP} | ${TS}\"}]}]}"
    ;;
esac
