#!/usr/bin/env bash
set -euo pipefail

OUT_DIR="${NODE_TEXTFILE_DIR:-/var/lib/node_exporter/textfile}"
OUT_FILE="${OUT_DIR}/smartmon.prom"
STDOUT=0
if [[ "${1:-}" == "--stdout" ]]; then
  STDOUT=1
fi

emit_metrics() {
  cat <<'EOF'
# HELP node_smartmon_device_smart_healthy SMART overall-health self-assessment, 1 healthy and 0 unhealthy.
# TYPE node_smartmon_device_smart_healthy gauge
# HELP node_smartmon_reallocated_sector_ct_raw_value SMART Reallocated_Sector_Ct raw value.
# TYPE node_smartmon_reallocated_sector_ct_raw_value gauge
# HELP node_smartmon_power_on_hours_raw_value SMART Power_On_Hours raw value.
# TYPE node_smartmon_power_on_hours_raw_value gauge
# HELP node_smartmon_temperature_celsius SMART temperature in Celsius.
# TYPE node_smartmon_temperature_celsius gauge
EOF

  command -v smartctl >/dev/null 2>&1 || return 0
  mapfile -t DEVICES < <(smartctl --scan-open 2>/dev/null | awk '{print $1}')
  [[ "${#DEVICES[@]}" -gt 0 ]] || return 0

  local dev label output healthy realloc hours temp
  for dev in "${DEVICES[@]}"; do
    label="${dev//\"/}"
    output="$(smartctl -A -H "$dev" 2>/dev/null || true)"
    [[ -n "$output" ]] || continue
    healthy=0
    grep -Eiq 'SMART overall-health self-assessment test result: PASSED|SMART Health Status: OK|SMART overall-health self-assessment test result: OK' <<<"$output" && healthy=1
    realloc="$(awk '$2 == "Reallocated_Sector_Ct" {print $10; found=1} END {if (!found) print 0}' <<<"$output")"
    hours="$(awk '$2 == "Power_On_Hours" {print $10; found=1} END {if (!found) print 0}' <<<"$output")"
    temp="$(awk '$2 == "Temperature_Celsius" || $2 == "Temperature_Internal" || $2 == "Airflow_Temperature_Cel" {print $10; found=1; exit} END {if (!found) print 0}' <<<"$output")"
    printf 'node_smartmon_device_smart_healthy{device="%s"} %s\n' "$label" "$healthy"
    printf 'node_smartmon_reallocated_sector_ct_raw_value{device="%s"} %s\n' "$label" "${realloc:-0}"
    printf 'node_smartmon_power_on_hours_raw_value{device="%s"} %s\n' "$label" "${hours:-0}"
    printf 'node_smartmon_temperature_celsius{device="%s"} %s\n' "$label" "${temp:-0}"
  done
}

if [[ "$STDOUT" -eq 1 ]]; then
  emit_metrics
else
  mkdir -p "$OUT_DIR"
  tmp="${OUT_FILE}.$$"
  emit_metrics > "$tmp"
  mv -f "$tmp" "$OUT_FILE"
fi
