#!/usr/bin/env bash
# disk_smart_check.sh — SMART pre-failure indicators for physical disks.
set -euo pipefail

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

DISKS=$(lsblk -ndo NAME,TYPE 2>/dev/null | awk '$2=="disk"{print "/dev/"$1}' || true)
if [ -z "$DISKS" ]; then
  echo '{"health":"healthy"}'
  exit 0
fi

FAILED=""
for dev in $DISKS; do
  INFO=$(smartctl -H "$dev" 2>/dev/null || true)
  if ! echo "$INFO" | grep -q "PASSED\|OK"; then
    MODEL=$(smartctl -i "$dev" 2>/dev/null | awk -F': ' '/Device Model|Product/{print $2; exit}' || echo "$dev")
    FAILED="$FAILED $MODEL"
  fi
done

if [ -n "$FAILED" ]; then
  echo "{\"health\":\"degraded\",\"signalKind\":\"disk-smart-fail\",\"evidence\":\"SMART check failed for:$(echo "$FAILED" | sed 's/ /, /g')\"}"
else
  echo '{"health":"healthy"}'
fi
