#!/usr/bin/env bash
# zfs_check.sh — ZFS pool health.
set -euo pipefail

if ! command -v zpool >/dev/null 2>&1; then
  echo '{"health":"healthy"}'
  exit 0
fi

STATUS=$(zpool status -x 2>&1 || true)
SCRUB_OVERDUE=""

if echo "$STATUS" | grep -q "all pools are healthy"; then
  for pool in $(zpool list -Ho name 2>/dev/null || true); do
    LAST=$(zpool status "$pool" 2>/dev/null | awk '/scan:/{print $0}' || true)
    if [ -z "$LAST" ] || echo "$LAST" | grep -q "scrub repaired"; then
      SCRUB_OVERDUE="$pool"
      break
    fi
  done
  if [ -n "$SCRUB_OVERDUE" ]; then
    echo "{\"health\":\"degraded\",\"signalKind\":\"zfs-scrub-overdue\",\"evidence\":\"pool $SCRUB_OVERDUE scrub has errors or is overdue\"}"
  else
    echo '{"health":"healthy"}'
  fi
else
  HEALTH=$(echo "$STATUS" | grep "state:" | awk '{print $2}' | head -1)
  echo "{\"health\":\"degraded\",\"signalKind\":\"zfs-degraded\",\"evidence\":\"pool state: $HEALTH\"}"
fi
