#!/bin/bash
# ServerManager Agent Uninstaller

# Try system paths first, fall back to user paths
if [ -f /usr/local/bin/servermanager-agent ]; then
    echo "[1/3] Stopping and disabling service..."
    systemctl stop servermanager-agent 2>/dev/null || true
    systemctl disable servermanager-agent 2>/dev/null || true
    systemctl daemon-reload 2>/dev/null || true

    echo "[2/3] Removing system files..."
    rm -f /usr/local/bin/servermanager-agent 2>/dev/null || true
    rm -rf /etc/servermanager 2>/dev/null || true
    rm -f /etc/systemd/system/servermanager-agent.service 2>/dev/null || true

    echo "[3/3] Reloading systemd..."
    systemctl daemon-reload 2>/dev/null || true
elif [ -f "$HOME/.local/bin/servermanager-agent" ]; then
    echo "[1/2] Removing cron job..."
    crontab -l 2>/dev/null | grep -v 'servermanager-agent' | crontab - 2>/dev/null || true

    echo "[2/2] Removing user files..."
    rm -f "$HOME/.local/bin/servermanager-agent" 2>/dev/null || true
    rm -rf "$HOME/.config/servermanager" 2>/dev/null || true
else
    echo "Agent is not installed."
    # Still try to clean up any leftover system files
    rm -f /usr/local/bin/servermanager-agent 2>/dev/null || true
    rm -rf /etc/servermanager 2>/dev/null || true
    rm -f /etc/systemd/system/servermanager-agent.service 2>/dev/null || true
    systemctl daemon-reload 2>/dev/null || true
    crontab -l 2>/dev/null | grep -v 'servermanager-agent' | crontab - 2>/dev/null || true
fi

echo "ServerManager Agent uninstalled successfully."
