#!/bin/bash
# Ahel Vault (ASUSTOR AS-33xx, Armada 7040) vitals -> M1 pushgateway (job=nas), every 60s.
# Reads /proc + thermal zones over SSH (ahel_control key, installed 2026-07-21).
# No agent runs on the NAS. smartctl needs root there — disk temps deliberately skipped.
PG="http://127.0.0.1:9091/metrics/job/nas"
SSH="ssh -o BatchMode=yes -o ConnectTimeout=8 -i /Users/admin/.ssh/ahel_control admin@192.168.8.193"

R=$($SSH '
  cut -d" " -f1 /proc/loadavg
  awk "/MemTotal/{t=\$2} /MemAvailable/{a=\$2} END{print t*1024; print (t-a)*1024}" /proc/meminfo
  cut -d" " -f1 /proc/uptime
  awk "{print \$1/1000; exit}" /sys/class/thermal/thermal_zone0/temp
  head -1 /proc/stat; sleep 1; head -1 /proc/stat
' 2>/dev/null) || { printf 'nas_up 0\n' | curl -s --data-binary @- "$PG"; exit 0; }

LOAD=$(echo "$R" | sed -n 1p)
MEMTOTAL=$(echo "$R" | sed -n 2p)
MEMUSED=$(echo "$R" | sed -n 3p)
UPTIME=$(echo "$R" | sed -n 4p)
TEMP=$(echo "$R" | sed -n 5p)
CPU=$(echo "$R" | sed -n '6p;7p' | awk '
  {idle[NR]=$5; tot[NR]=0; for(i=2;i<=NF;i++) tot[NR]+=$i}
  END{d=tot[2]-tot[1]; if(d>0) printf "%.1f", 100*(1-(idle[2]-idle[1])/d)}')

{
  printf 'nas_up 1\n'
  printf 'nas_load1 %s\n' "${LOAD:-0}"
  printf 'nas_mem_total_bytes %s\n' "${MEMTOTAL:-0}"
  printf 'nas_mem_used_bytes %s\n' "${MEMUSED:-0}"
  printf 'nas_uptime_seconds %s\n' "${UPTIME:-0}"
  [ -n "$TEMP" ] && printf 'nas_temp_celsius %s\n' "$TEMP"
  [ -n "$CPU" ] && printf 'nas_cpu_pct %s\n' "$CPU"
} | curl -s --data-binary @- "$PG"
echo "pushed load=$LOAD temp=${TEMP}C cpu=${CPU}%"
