#!/bin/bash
# Script to uninstall Acushield. Needs sudo permissions.

# Check if running as root
if [ "$EUID" -ne 0 ]; then
  echo "Please run as root"
  exit 1
fi

echo "Uninstalling Acushield..."

CURRENT_USER=$(stat -f "%Su" /dev/console)
CURRENT_UID=$(id -u "$CURRENT_USER")

# NOTE: Old acushield adds OLD_PLIST file (v1.0.x)
# Once we no longer have any deployments with this version, we can remove
OLD_PLIST="$HOME/Library/LaunchAgents/ai.acuvity.acushield.plist"
if [ -f "$OLD_PLIST" ]; then
    echo "Stopping and removing old agent startup for user $CURRENT_USER..."
    su -l "$CURRENT_USER" -c "launchctl bootout gui/$CURRENT_UID $OLD_PLIST"
    rm -f "$OLD_PLIST"
    pkill acushieldd
    pkill acushield
    rm -rf /tmp/acushield.sock
fi

# Stop and remove systray
AGENT_PLIST="/Library/LaunchAgents/ai.acuvity.acushield.systray.plist"
if [ -f "$AGENT_PLIST" ]; then
    echo "Stopping and removing systray agent for user $CURRENT_USER..."
    su -l "$CURRENT_USER" -c "launchctl bootout gui/$CURRENT_UID $AGENT_PLIST"
    rm -f "$AGENT_PLIST"
fi

# Stop and remove daemon
DAEMON_PLIST="/Library/LaunchDaemons/ai.acuvity.acushield.daemon.plist"
if [ -f "$DAEMON_PLIST" ]; then
    echo "Stopping and removing daemon..."
    launchctl bootout system "$DAEMON_PLIST"
    rm -f "$DAEMON_PLIST"
fi

# Stop and remove helper
HELPER_PLIST="/Library/LaunchDaemons/ai.acuvity.acushield.helper.plist"
if [ -f "$HELPER_PLIST" ]; then
    echo "Stopping and removing helper..."
    launchctl bootout system "$HELPER_PLIST"
    rm -f "$HELPER_PLIST"
fi

# Run cleanup
CLEANUP_BINARY="/Applications/Acushield.app/Contents/MacOS/acushield"
if [ -f "$CLEANUP_BINARY" ]; then
    echo "Running cleanup..."
    "$CLEANUP_BINARY" cleanup
fi

# Remove application files
if [ -d /Applications/Acushield.app ]; then
    echo "Removing Acushield.app from Applications..."
    rm -rf /Applications/Acushield.app
fi

# Remove application files
if [ -d /Applications/Acushield.localized ]; then
    echo "Removing Acushield.localized from Applications..."
    rm -rf /Applications/Acushield.localized
fi

# Remove helper file
if [ -f /Library/PrivilegedHelperTools/ai.acuvity.acushield.helper ]; then
    echo "Removing ai.acuvity.acushield.helper from PrivilegedHelperTools..."
    rm -rf /Library/PrivilegedHelperTools/ai.acuvity.acushield.helper
fi

# Forget the package receipt
PKG_NAME="ai.acuvity.acushield"
if pkgutil --pkgs | grep -q "^${PKG_NAME}$"; then
    echo "Forgetting package receipt $PKG_NAME..."
    pkgutil --forget "$PKG_NAME"
fi

echo "Acushield has been uninstalled."
