#!/bin/sh
# Datargo Agent — uninstaller (Linux/macOS). Removes the agent without residue.
#
#   curl -fsSL https://agent.datargo.com/uninstall.sh | sudo sh
#
# Steps:
#   1. Deregister from the cockpit (best-effort, using the credentials in the
#      config file) so the host disappears there automatically.
#   2. Stop + remove the service (launchd/systemd).
#   3. Remove the binary, state, dedicated service user (Linux) and logs.
#
# Safety: NO `rm -rf` on system paths — known files are removed individually and
# the (now empty) state directory with `rmdir` (which never recurses). Idempotent.
set -eu

BIN="/usr/local/bin/datargo-agent"
STATE_DIR="/var/lib/datargo-agent"
STATE_FILE="/var/lib/datargo-agent/agent.toml"
SVC_USER="datargo-agent"
PLIST="/Library/LaunchDaemons/com.datargo.agent.plist"
UNIT="/etc/systemd/system/datargo-agent.service"
LOG="/var/log/datargo-agent.log"

info() { printf '\033[1;34m›\033[0m %s\n' "$1"; }
ok() { printf '\033[1;32m✓\033[0m %s\n' "$1"; }
die() { printf '\033[1;31m✗ %s\033[0m\n' "$1" >&2; exit 1; }

# Sanity: never operate on empty paths (defensive — these are constants).
[ -n "$BIN" ] && [ -n "$STATE_DIR" ] || die "internal error: empty paths."

SUDO_CMD=""
if [ "$(id -u)" -ne 0 ]; then
  command -v sudo >/dev/null 2>&1 && SUDO_CMD="sudo" || die "root/sudo required to remove."
fi

os="$(uname -s)"
info "Removing Datargo Agent ($os) …"

# ── 1. Deregister from the cockpit (best-effort) ─────────────────────────────
# Read base URL + per-agent token from the config; revoke this agent server-side
# so it vanishes from the cockpit. Never blocks the uninstall (host may be off).
if [ -r "$STATE_FILE" ] && command -v curl >/dev/null 2>&1; then
  server="$(sed -n 's/^[[:space:]]*server[[:space:]]*=[[:space:]]*"\(.*\)".*/\1/p' "$STATE_FILE" | head -1)"
  token="$(sed -n 's/^[[:space:]]*agent_token[[:space:]]*=[[:space:]]*"\(.*\)".*/\1/p' "$STATE_FILE" | head -1)"
  if [ -n "$server" ] && [ -n "$token" ]; then
    info "Deregistering from the cockpit …"
    if curl -fsS --max-time 15 -X DELETE -H "Authorization: Bearer $token" "$server/agent/self" >/dev/null 2>&1; then
      ok "Removed from the cockpit."
    else
      info "Could not reach the cockpit — remove the entry manually there (Host agents → Remove)."
    fi
  fi
fi

# ── 2. Stop + remove the service ─────────────────────────────────────────────
case "$os" in
  Darwin)
    $SUDO_CMD launchctl bootout system/com.datargo.agent 2>/dev/null || true
    $SUDO_CMD rm -f "$PLIST"
    $SUDO_CMD rm -f "$LOG"
    ;;
  Linux)
    if command -v systemctl >/dev/null 2>&1; then
      $SUDO_CMD systemctl disable --now datargo-agent 2>/dev/null || true
    fi
    $SUDO_CMD rm -f "$UNIT"
    command -v systemctl >/dev/null 2>&1 && $SUDO_CMD systemctl daemon-reload 2>/dev/null || true
    # Remove the dedicated service user (if present).
    if id "$SVC_USER" >/dev/null 2>&1; then
      $SUDO_CMD userdel "$SVC_USER" 2>/dev/null || $SUDO_CMD deluser "$SVC_USER" 2>/dev/null || true
    fi
    ;;
  *)
    info "Unknown OS — removing only binary + state."
    ;;
esac

# ── 3. Remove binary + state (no rm -rf) ─────────────────────────────────────
$SUDO_CMD rm -f "$BIN"
# Known state files individually, then rmdir (only removes an EMPTY directory and
# never recurses — unexpected files are left untouched).
$SUDO_CMD rm -f "$STATE_FILE"
$SUDO_CMD rmdir "$STATE_DIR" 2>/dev/null \
  || info "$STATE_DIR not empty — left in place (inspect manually)."

ok "Datargo Agent removed."
