#!/usr/bin/env bash
set -euo pipefail
NODE="${BLACKROAD_NODE_NAME:-$(hostname)}"
REPO_DIR="$HOME/blackroad-sync/BlackRoad-Operating-System"
[ -d "$REPO_DIR/.git" ] || exit 0
cd "$REPO_DIR"
git pull --ff-only origin main 2>/dev/null || true

# System metrics
LOAD=$(cat /proc/loadavg 2>/dev/null | cut -d' ' -f1-3 || echo '?')
MEM=$(free -m 2>/dev/null | awk '/Mem:/{printf "%d/%dMB", $3, $2}' || echo '?')
DISK=$(df / 2>/dev/null | awk 'NR==2{print $5}' || echo '?')
TEMP=$(cat /sys/class/thermal/thermal_zone0/temp 2>/dev/null | awk '{printf "%.1f", $1/1000}' || echo '?')
UPTIME=$(uptime -p 2>/dev/null || uptime | sed 's/.*up/up/')

mkdir -p fleet-heartbeat
cat > "fleet-heartbeat/${NODE}.json" << INNER
{
  "node": "$NODE",
  "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  "status": "online",
  "load": "$LOAD",
  "memory": "$MEM",
  "disk": "$DISK",
  "temp_c": "$TEMP",
  "uptime": "$UPTIME"
}
INNER

git add fleet-heartbeat/
git diff --cached --quiet 2>/dev/null && exit 0
git commit -m "heartbeat: $NODE [$(date -u +%Y-%m-%dT%H:%M)]" 2>/dev/null
git push origin main 2>/dev/null
