#!/bin/bash
# GuruRMM Agent Diagnostics for Scileppi Law Firm
# Usage: curl -fsSL https://rmm.azcomputerguru.com/install/scileppi-diag | sudo bash

echo "=== GuruRMM Agent Diagnostics ==="
echo ""

echo "=== Service Status ==="
launchctl list | grep gururmm || echo "Service not registered"
echo ""

echo "=== Running Process ==="
ps aux | grep gururmm-agent | grep -v grep || echo "No process running"
echo ""

echo "=== Binary Info ==="
if [ -f /usr/local/bin/gururmm-agent ]; then
    file /usr/local/bin/gururmm-agent
    ls -lh /usr/local/bin/gururmm-agent
    /usr/local/bin/gururmm-agent --version 2>&1 || echo "Version check failed"
else
    echo "Binary not found at /usr/local/bin/gururmm-agent"
fi
echo ""

echo "=== Config File ==="
if [ -f /etc/gururmm/config.toml ]; then
    cat /etc/gururmm/config.toml
else
    echo "Config file not found at /etc/gururmm/config.toml"
fi
echo ""

echo "=== Site Plist ==="
if [ -f /usr/local/etc/gururmm/site.plist ]; then
    cat /usr/local/etc/gururmm/site.plist
else
    echo "Site plist not found at /usr/local/etc/gururmm/site.plist"
fi
echo ""

echo "=== LaunchDaemon ==="
if [ -f /Library/LaunchDaemons/com.azcomputerguru.gururmm-agent.plist ]; then
    cat /Library/LaunchDaemons/com.azcomputerguru.gururmm-agent.plist
else
    echo "LaunchDaemon not found"
fi
echo ""

echo "=== Recent Agent Logs (last 30 lines) ==="
if [ -f /Library/Logs/GuruRMM/agent.log.$(date +%Y-%m-%d) ]; then
    tail -30 /Library/Logs/GuruRMM/agent.log.$(date +%Y-%m-%d)
else
    echo "No log file for today"
    ls -lh /Library/Logs/GuruRMM/ 2>/dev/null || echo "Log directory doesn't exist"
fi
echo ""

echo "=== Stderr Log ==="
if [ -f /Library/Logs/GuruRMM/stderr.log ]; then
    cat /Library/Logs/GuruRMM/stderr.log
else
    echo "No stderr log"
fi
echo ""

echo "=== Stdout Log ==="
if [ -f /Library/Logs/GuruRMM/stdout.log ]; then
    cat /Library/Logs/GuruRMM/stdout.log
else
    echo "No stdout log"
fi
echo ""

echo "=== Manual Test Run (5 seconds) ==="
echo "Attempting to run agent manually..."
timeout 5 /usr/local/bin/gururmm-agent run 2>&1 || echo "Manual run failed or timed out"
echo ""

echo "=== Network Test ==="
echo "Testing connection to rmm-api.azcomputerguru.com..."
nc -zv rmm-api.azcomputerguru.com 443 2>&1 || curl -I https://rmm-api.azcomputerguru.com 2>&1 | head -5
echo ""

echo "=== Diagnostics Complete ==="
