#!/usr/bin/env bash
# Uninstall the KueSync Agent. © 2026 Krometis Analytics.
#   sudo bash uninstall.sh
set -u
PLIST="/Library/LaunchAgents/com.krometis.kuesync.agent.plist"
MENU_PLIST="/Library/LaunchAgents/com.krometis.kuesync.menu.plist"
DAEMON_PLIST="/Library/LaunchDaemons/com.krometis.kuesync.ptp-helper.plist"
UPDATE_DAEMON_PLIST="/Library/LaunchDaemons/com.krometis.kuesync.update-helper.plist"
DIR="/usr/local/kuesync-agent"
CONSOLE_USER="$(stat -f%Su /dev/console 2>/dev/null || true)"

if [ -n "$CONSOLE_USER" ] && [ "$CONSOLE_USER" != "root" ]; then
  UID_NUM="$(id -u "$CONSOLE_USER" 2>/dev/null || true)"
  if [ -n "$UID_NUM" ]; then
    launchctl bootout "gui/$UID_NUM" "$PLIST" 2>/dev/null || true
    launchctl bootout "gui/$UID_NUM" "$MENU_PLIST" 2>/dev/null || true
  fi
fi

# PTP helper + update helper run in the system domain (root).
launchctl bootout system "$DAEMON_PLIST" 2>/dev/null || true
launchctl bootout system "$UPDATE_DAEMON_PLIST" 2>/dev/null || true

pkill -f "KueSync.app/Contents/MacOS/KueSync" 2>/dev/null || true
pkill -f "kuesync-ptp-helper" 2>/dev/null || true
pkill -f "KueSyncUpdateHelper" 2>/dev/null || true
rm -f "$PLIST" "$MENU_PLIST" "$DAEMON_PLIST" "$UPDATE_DAEMON_PLIST"
rm -rf "$DIR" "/Applications/KueSync.app"
pkgutil --forget com.krometis.kuesync.agent 2>/dev/null || true
echo "KueSync Agent removed."
