#!/bin/bash
# Verify Cockpit NVIDIA GPU dashboard health
# Returns non-zero exit code if anything is wrong.

FAIL=0

echo "=== Checking systemd service ==="
if systemctl is-active --quiet nvidia-gpu-monitor; then
    echo "  [PASS] nvidia-gpu-monitor service is running"
else
    echo "  [FAIL] nvidia-gpu-monitor service is NOT running"
    FAIL=1
fi

echo ""
echo "=== Checking data files ==="
for f in /run/nvidia-gpu.txt /run/nvidia-processes.txt /run/nvidia-cuda.txt; do
    if [ -f "$f" ]; then
        CONTENT=$(head -1 "$f")
        echo "  [PASS] $f: $CONTENT"
    else
        echo "  [FAIL] $f does not exist"
        FAIL=1
    fi
done

echo ""
echo "=== Checking Cockpit package ==="
MANIFEST="/usr/share/cockpit/nvidia-gpu/manifest.json"
INDEX="/usr/share/cockpit/nvidia-gpu/index.html"
if [ -f "$MANIFEST" ] && [ -f "$INDEX" ]; then
    echo "  [PASS] Cockpit nvidia-gpu package installed"
    echo "  Manifest: $(wc -c < "$MANIFEST") bytes"
    echo "  Index:    $(wc -c < "$INDEX") bytes"
else
    echo "  [FAIL] Cockpit package files missing"
    FAIL=1
fi

echo ""
echo "=== Checking GPU accessibility ==="
GPU_LINE=$(nvidia-smi --query-gpu=name --format=csv,noheader 2>/dev/null | head -1)
if [ -n "$GPU_LINE" ]; then
    echo "  [PASS] GPU detected: $GPU_LINE"
else
    echo "  [FAIL] nvidia-smi not working"
    FAIL=1
fi

echo ""
echo "=== Cockpit service ==="
if systemctl is-active --quiet cockpit; then
    echo "  [PASS] Cockpit running on port 9090"
else
    echo "  [FAIL] Cockpit is not running"
    FAIL=1
fi

echo ""
if [ "$FAIL" -eq 0 ]; then
    echo "All checks passed. GPU dashboard should be functional."
else
    echo "Some checks FAILED. See above."
fi
exit $FAIL
