#!/usr/bin/env bash
# NodeMCP / Plink Linux Agent Uninstaller v1.0
# Default: read-only audit. Destructive mode: --purge + TTY confirmation.
set -Eeuo pipefail
export LC_ALL=C
umask 077

mode="--dry-run"
if (( $# > 0 )); then mode="$1"; shift; fi
if (( $# != 0 )); then echo "Unexpected arguments." >&2; exit 2; fi
case "$mode" in
  --dry-run|--purge) ;;
  --help|-h)
    echo "Usage: bash uninstall-linux.sh [--dry-run|--purge]"
    echo "  --dry-run: preview, no changes (default)"
    echo "  --purge: remove known agent services, files and device identity"
    exit 0 ;;
  *) echo "Unknown mode: $mode" >&2; exit 2 ;;
esac

units() {
  printf '%s\n' \
    plink-agent.service \
    plink-agent-admin.service \
    plink-fulladmin-agent.service \
    nodemcp-agent.service
}

paths() {
  cat <<'PATHS'
/etc/systemd/system/plink-agent.service
/etc/systemd/system/plink-agent.service.d
/etc/systemd/system/plink-agent-admin.service
/etc/systemd/system/plink-agent-admin.service.d
/etc/systemd/system/plink-fulladmin-agent.service
/etc/systemd/system/plink-fulladmin-agent.service.d
/etc/systemd/system/nodemcp-agent.service
/etc/systemd/system/nodemcp-agent.service.d
/etc/systemd/system/multi-user.target.wants/plink-agent.service
/etc/systemd/system/multi-user.target.wants/plink-agent-admin.service
/etc/systemd/system/multi-user.target.wants/plink-fulladmin-agent.service
/etc/systemd/system/multi-user.target.wants/nodemcp-agent.service
/opt/plink-agent
/opt/plink-fulladmin
/opt/plink-fulladmin-agent
/opt/nodemcp-agent
/var/lib/plink-agent
/var/lib/plink-fulladmin
/var/lib/plink-fulladmin-agent
/var/lib/nodemcp-agent
/etc/plink-agent
/etc/plink-fulladmin-agent
/etc/nodemcp-agent
/usr/local/bin/plink-agent
/usr/local/bin/plink-fulladmin-agent
/usr/local/bin/nodemcp-agent
PATHS
}

exists() { [[ -e "$1" || -L "$1" ]]; }
loaded() {
  local state
  state="$(systemctl show -P LoadState "$1" 2>/dev/null || true)"
  [[ -n "$state" && "$state" != "not-found" ]]
}

echo "NodeMCP / Plink Linux Agent Uninstaller v1.0"
echo "Host: $(hostname)  Mode: $mode"
echo "Scope: Linux agents ONLY; gateway/controller, SSH, other apps and backups are excluded."
echo
echo "[Known agent units]"
while IFS= read -r unit; do
  if command -v systemctl >/dev/null 2>&1 && loaded "$unit"; then
    printf '  %s  active=%s\n' "$unit" "$(systemctl is-active "$unit" 2>/dev/null || true)"
  elif exists "/etc/systemd/system/$unit"; then
    printf '  %s  unit file found\n' "$unit"
  fi
done < <(units)

echo "[Known installed paths]"
found=0
while IFS= read -r path; do
  if exists "$path"; then
    printf '  %s\n' "$path"
    found=1
  fi
done < <(paths)
if (( found == 0 )); then echo "  No known installation paths found."; fi

if command -v systemctl >/dev/null 2>&1; then
  echo "[Other services containing plink/nodemcp (PRESERVED)]"
  while IFS= read -r unit; do
    [[ -n "$unit" ]] || continue
    case "$unit" in
      plink-agent.service|plink-agent-admin.service|plink-fulladmin-agent.service|nodemcp-agent.service) ;;
      *) printf '  %s\n' "$unit" ;;
    esac
  done < <(systemctl list-unit-files --type=service --no-legend 2>/dev/null | awk '{print $1}' | grep -Ei 'plink|nodemcp' || true)
fi

echo
if [[ "$mode" == "--dry-run" ]]; then
  echo "DRY RUN ONLY: Nothing changed."
  echo "To remove these agent installations and local device identities, rerun with --purge."
  exit 0
fi

if (( EUID != 0 )); then echo "ERROR: --purge requires root (sudo)." >&2; exit 1; fi
if [[ ! -d /run/systemd/system ]] || ! command -v systemctl >/dev/null 2>&1; then
  echo "ERROR: A running systemd installation is required for safe removal." >&2; exit 1
fi

# Refuse to remove through unexpected symlinked parent directories.
for base in /etc /etc/systemd /etc/systemd/system /opt /var /var/lib /usr /usr/local /usr/local/bin; do
  if [[ -L "$base" ]]; then
    echo "ERROR: Symlinked parent $base; refusing automatic deletion." >&2
    exit 1
  fi
done

# Refuse deletion if any known agent tree includes a mount/bind mount.
if command -v findmnt >/dev/null 2>&1; then
  while IFS= read -r path; do
    exists "$path" || continue
    while IFS= read -r mount; do
      case "$mount" in
        "$path"|"$path"/*)
          echo "ERROR: Mount detected inside $path ($mount); refusing purge." >&2
          exit 1 ;;
      esac
    done < <(findmnt -rn -o TARGET)
  done < <(paths)
fi

if [[ ! -r /dev/tty || ! -w /dev/tty ]]; then
  echo "ERROR: Interactive TTY required. Aborting without changes." >&2
  exit 1
fi

echo "WARNING: --purge permanently removes LOCAL device IDs, credentials and agent data."
echo "Gateway, controller, other services and existing backup archives are preserved."
printf 'Type PURGE NODEMCP AGENTS to confirm: ' > /dev/tty
IFS= read -r confirmation < /dev/tty || { echo "No confirmation. Aborted."; exit 1; }
if [[ "$confirmation" != "PURGE NODEMCP AGENTS" ]]; then
  echo "Confirmation did not match. Aborted without changes."
  exit 1
fi

echo "[Stopping known agents]"
while IFS= read -r unit; do
  if systemctl is-active --quiet "$unit"; then
    echo "  stopping $unit"
    systemctl stop "$unit" || { echo "ERROR: Failed to stop $unit; refusing removal." >&2; exit 1; }
  fi
done < <(units)

echo "[Disabling known agent units]"
while IFS= read -r unit; do
  if loaded "$unit" || exists "/etc/systemd/system/$unit"; then
    systemctl disable "$unit" >/dev/null 2>&1 || true
  fi
done < <(units)

echo "[Removing known agent paths and local identities]"
while IFS= read -r path; do
  if exists "$path"; then
    echo "  remove $path"
    rm -rf --one-file-system -- "$path"
  fi
done < <(paths)

systemctl daemon-reload
systemctl reset-failed plink-agent.service plink-agent-admin.service plink-fulladmin-agent.service nodemcp-agent.service >/dev/null 2>&1 || true

remaining=0
while IFS= read -r path; do
  if exists "$path"; then
    echo "WARNING: Still present: $path" >&2
    remaining=1
  fi
done < <(paths)
while IFS= read -r unit; do
  if systemctl is-active --quiet "$unit"; then
    echo "WARNING: Still running: $unit" >&2
    remaining=1
  elif loaded "$unit"; then
    echo "WARNING: A unit with the same name still exists elsewhere: $unit" >&2
    remaining=1
  fi
done < <(units)

if (( remaining )); then
  echo "PARTIAL: Review warnings above; no unrelated components were removed." >&2
  exit 1
fi
echo "SUCCESS: Known NodeMCP/Plink Linux agent installations and local identity removed."
echo "Existing records in the web panel must be deleted separately if no longer needed."
