#!/usr/bin/env bash
# 巡检：健康端点 + 磁盘水位告警。失败/越线写 ALERT.log（供总管日检）。
# 建议 cron：*/5 * * * * /path/to/deploy/monitor.sh >/dev/null 2>&1
set -euo pipefail
ROOT="$(cd "$(dirname "$0")" && pwd)"
URL="${HEALTH_URL:-http://127.0.0.1:4173/}"
DATA_DIR="${DATA_DIR:-$ROOT/../data}"
ALERT="$ROOT/ALERT.log"
DISK_THRESHOLD="${DISK_THRESHOLD:-80}"

now() { date "+%Y-%m-%d %H:%M:%S"; }

# 1) 健康检查：HTTP 200 才算通过
if ! curl -fsS -m 8 -o /dev/null "$URL"; then
    echo "[$(now)] HEALTH FAIL: $URL 无响应" >> "$ALERT"
    exit 1
fi

# 2) 磁盘水位：数据所在分区使用率超阈值告警
pct="$(df -P "$DATA_DIR" | awk 'NR==2 {gsub("%",""); print $5}')"
if [ "${pct:-0}" -ge "$DISK_THRESHOLD" ]; then
    echo "[$(now)] DISK ALERT: $DATA_DIR 使用率 ${pct}% >= ${DISK_THRESHOLD}%" >> "$ALERT"
    exit 2
fi

# 3) 容器状态：非 running/restarting 告警
state="$(docker inspect -f '{{.State.Status}}' "${CONTAINER:-caiwuzongzhang-app}" 2>/dev/null || echo missing)"
if [ "$state" != "running" ]; then
    echo "[$(now)] CONTAINER ALERT: ${CONTAINER:-caiwuzongzhang-app} state=$state" >> "$ALERT"
    exit 3
fi
echo "[$(now)] ok"
