#!/bin/bash
# ================================================================
# Nexus Agent Uninstall Script
# Usage: curl -fsSL https://YOUR_NEXUS_DOMAIN/agent/uninstall.sh | bash
#
# Stops and removes the nexus-agent systemd service and /opt/nexus-agent directory.
# Does NOT remove rsync (may be used by other tools).
# ================================================================

set -e

INSTALL_DIR="/opt/nexus-agent"
SERVICE_NAME="nexus-agent"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"

echo ""
echo "=========================================="
echo "  Nexus Agent Uninstall"
echo "=========================================="
echo ""

# --- Privilege detection ---
if [ "$(id -u)" -eq 0 ]; then
    SUDO=""
else
    if command -v sudo >/dev/null 2>&1 && sudo -n true 2>/dev/null; then
        SUDO="sudo"
    else
        echo "ERROR: Must run as root or have passwordless sudo."
        exit 1
    fi
fi

# 1. Stop service if running
echo "[1/5] Stop service..."
$SUDO systemctl stop "$SERVICE_NAME" 2>/dev/null || true
# Kill any stale agent processes (new: uvicorn agent:app; legacy: python.*agent\.py or nexus_agent)
pkill -f "uvicorn agent:app" 2>/dev/null || true
pkill -f "python.*agent\.py" 2>/dev/null || true
pkill -f "nexus_agent" 2>/dev/null || true
# Kill any process on the agent port
if command -v fuser >/dev/null 2>&1; then
    $SUDO fuser -k 8601/tcp 2>/dev/null || true
fi
echo "  Service stopped, stale processes killed"

# 2. Disable and remove systemd unit
echo "[2/5] Remove systemd unit..."
if [ -f "$SERVICE_FILE" ]; then
    $SUDO systemctl disable "$SERVICE_NAME" 2>/dev/null || true
    $SUDO rm -f "$SERVICE_FILE"
    $SUDO systemctl daemon-reload
    echo "  Unit removed"
else
    echo "  No systemd unit found"
fi

# 3. Remove install directory (standard + legacy paths)
echo "[3/6] Remove install directory..."
for dir in "$INSTALL_DIR" "/opt/multisync-agent"; do
    if [ -d "$dir" ]; then
        $SUDO rm -rf "$dir"
        echo "  ${dir} removed"
    fi
done
if [ ! -d "$INSTALL_DIR" ] && [ ! -d "/opt/multisync-agent" ]; then
    echo "  No install directory found"
fi

# 4. Remove log file
echo "[4/6] Remove log file..."
removed_log=0
for logfile in "/var/log/nexus-agent.log" "/var/log/multisync-agent.log"; do
    if [ -f "$logfile" ]; then
        $SUDO rm -f "$logfile"
        echo "  ${logfile} removed"
        removed_log=1
    fi
done
if [ "$removed_log" -eq 0 ]; then
    echo "  No log file found"
fi

# 5. Clean up crontab entries (legacy agents may use cron for auto-restart)
echo "[5/6] Clean up crontab..."
crontab_cleaned=0
for user_crondir in /var/spool/cron/crontabs /var/spool/cron; do
    if [ -d "$user_crondir" ]; then
        for crontab_file in "$user_crondir"/*; do
            if [ -f "$crontab_file" ] && grep -q "nexus.agent\|multisync.agent\|nexus-agent\|multisync-agent" "$crontab_file" 2>/dev/null; then
                $SUDO sed -i '/nexus.agent\|multisync.agent\|nexus-agent\|multisync-agent/d' "$crontab_file"
                echo "  Cleaned crontab: $crontab_file"
                crontab_cleaned=1
            fi
        done
    fi
done
if [ "$crontab_cleaned" -eq 0 ]; then
    echo "  No crontab entries found"
fi

# 6. Clean up sudoers residual (left by install/upgrade _sudo_wrap)
echo "[6/6] Clean up sudoers..."
if [ -f "/etc/sudoers.d/nexus-agent" ]; then
    $SUDO rm -f /etc/sudoers.d/nexus-agent
    echo "  /etc/sudoers.d/nexus-agent removed"
else
    echo "  No sudoers residual found"
fi

echo ""
echo "=========================================="
echo "  Uninstall complete!"
echo "=========================================="
echo ""
