#!/usr/bin/env bash
# HostSeba NOC — Probe node uninstaller
#
# Removes the probe agent + its systemd service + user + config files.
# Safe to run more than once (idempotent — missing pieces are skipped).
#
# Usage on the probe server:
#   curl -fsSL https://noc.hostseba.com/probe/uninstall.sh | sudo bash
#
# Or if downloaded:
#   sudo bash uninstall.sh
#
# After this runs, the probe stops pushing data to the NOC. The dashboard
# will show the location as "stale" within ~5 minutes (no heartbeat). To
# fully remove it from the dashboard, decommission it from the
# "Probe Locations" page on the NOC.

set -uo pipefail

if [[ $EUID -ne 0 ]]; then
  echo "This uninstaller must run as root (sudo)." >&2
  exit 1
fi

echo "==> HostSeba NOC probe uninstaller"

# Stop + disable systemd service. We tolerate "not found" because the
# operator may already have stopped it, or the install never completed.
if systemctl list-unit-files 2>/dev/null | grep -q '^hostseba-probe\.service'; then
  echo "==> Stopping hostseba-probe service"
  systemctl stop hostseba-probe.service 2>/dev/null || true
  systemctl disable hostseba-probe.service 2>/dev/null || true
  rm -f /etc/systemd/system/hostseba-probe.service
  systemctl daemon-reload
else
  echo "    Service not installed, skipping"
fi

# Remove install dir + config + logs.
echo "==> Removing files"
for path in /opt/hostseba-probe /etc/hostseba-probe /var/log/hostseba-probe; do
  if [[ -d "$path" ]]; then
    rm -rf "$path"
    echo "    Removed $path"
  fi
done

# Remove the system user. We don't delete the user's home (-r) because
# the home is /opt/hostseba-probe which we already removed above.
if id hostseba-probe >/dev/null 2>&1; then
  echo "==> Removing hostseba-probe user"
  userdel hostseba-probe 2>/dev/null || true
fi

echo
echo "==> Done. The probe is fully removed from this server."
echo "    Don't forget to decommission this location in the NOC dashboard"
echo "    (Probe Locations → click the trash icon)."
