#!/bin/bash

# =============================================================================
# Abloomify Device Agent Uninstaller
# =============================================================================
#
# This script completely removes the Abloomify Device Agent from macOS systems.
# It can be run manually with sudo or deployed through MDM.
#
# Usage:
#   sudo ./uninstall_agent.sh
#
# MDM Deployment:
#   Deploy this script with root privileges through your MDM solution
#
# =============================================================================

set -u

# --- Configuration ---
APP_NAME="Abloomify"
APP_PATH="/Applications/${APP_NAME}.app"
# Legacy bundle name (pre-rename). Removed alongside APP_PATH so upgrading from an older
# build does not leave an orphan /Applications/AbloomifyDeviceAgent.app behind. The process
# / executable name is intentionally unchanged, so process matching below still works.
LEGACY_APP_PATH="/Applications/AbloomifyDeviceAgent.app"
PROCESS_NAME="AbloomifyDeviceAgent"
XPC_PROCESS_NAME="ChromeTelemetryXPCService"
BUNDLE_ID="com.abloomify.AbloomifyDeviceAgent"
APP_GROUP_ID="group.com.abloomify.deviceagent"
LAUNCH_AGENT_NAME="com.abloomify.deviceagent"
LAUNCH_AGENT_FILE="${LAUNCH_AGENT_NAME}.plist"
XPC_LAUNCH_AGENT_NAME="com.abloomify.chrome-telemetry-xpc"
XPC_LAUNCH_AGENT_FILE="${XPC_LAUNCH_AGENT_NAME}.plist"
DIAGNOSTIC_HELPER_PATH="/usr/local/bin/abloomify-diagnostics"
MAIN_STDOUT_LOG="/tmp/abloomify-stdout.log"
MAIN_STDERR_LOG="/tmp/abloomify-stderr.log"
XPC_STDOUT_LOG="/tmp/abloomify-xpc-stdout.log"
XPC_STDERR_LOG="/tmp/abloomify-xpc-stderr.log"
APP_EXECUTABLE="${APP_PATH}/Contents/MacOS/${PROCESS_NAME}"
PACKAGE_IDS=(
    "$BUNDLE_ID"
    "com.abloomify.deviceagent"
    "com.abloomify.agent"
)
PRESERVE_IDENTITY=false

for arg in "$@"; do
    case "$arg" in
        --preserve-identity)
            PRESERVE_IDENTITY=true
            ;;
        *)
            echo "Ignoring unknown argument: $arg"
            ;;
    esac
done

# --- Colors for output (disabled if not running in terminal) ---
if [[ -t 1 ]]; then
    RED='\033[0;31m'
    GREEN='\033[0;32m'
    YELLOW='\033[1;33m'
    BLUE='\033[0;34m'
    NC='\033[0m' # No Color
else
    RED=''
    GREEN=''
    YELLOW=''
    BLUE=''
    NC=''
fi

# --- Helper Functions ---
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} ✅ $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} ⚠️  $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} ❌ $1"
}

# --- Check if running as root ---
check_root() {
    if [ "$EUID" -ne 0 ]; then
        log_error "This script must be run with sudo or as root"
        echo "Usage: sudo $0"
        exit 1
    fi
}

get_gui_user_ids() {
    {
        stat -f %u /dev/console 2>/dev/null || true
        ps -axo uid=,comm= 2>/dev/null | awk '$2 == "loginwindow" {print $1}' || true
    } | awk '$1 ~ /^[0-9]+$/ && $1 > 0 {print $1}' | sort -u
}

remove_path_if_exists() {
    local path="$1"
    local label="$2"

    if [ ! -e "$path" ] && [ ! -L "$path" ]; then
        return 0
    fi

    if rm -rf "$path"; then
        log_success "Removed ${label}"
    else
        log_warning "Could not remove ${label} at ${path}"
    fi
}

remove_user_path_if_exists() {
    local path="$1"
    local label="$2"
    local user_home="$3"

    if [ ! -e "$path" ] && [ ! -L "$path" ]; then
        return 0
    fi

    local user_name
    user_name=$(stat -f %Su "$user_home" 2>/dev/null || true)
    if [ -z "$user_name" ] || [ "$user_name" = "root" ]; then
        log_warning "Could not resolve owning user for ${label} at ${path}"
        return 1
    fi

    if sudo -u "$user_name" /bin/rm -rf "$path"; then
        log_success "Removed ${label}"
    else
        log_warning "Could not remove ${label} at ${path}"
        return 1
    fi
}

run_app_uninstall_cleanup() {
    if [ "$PRESERVE_IDENTITY" = true ]; then
        return 0
    fi

    if [ ! -x "$APP_EXECUTABLE" ]; then
        log_info "App cleanup executable not found; skipping app-owned cleanup"
        return 0
    fi

    local ran_cleanup=false
    local cleanup_failed=false
    local user_id

    for user_id in $(get_gui_user_ids); do
        local user_name
        user_name=$(id -un "$user_id" 2>/dev/null || true)
        if [ -z "$user_name" ]; then
            log_warning "Could not resolve username for GUI session ${user_id}"
            cleanup_failed=true
            continue
        fi

        log_info "Running app-owned uninstall cleanup for ${user_name}"
        if launchctl asuser "$user_id" sudo -u "$user_name" "$APP_EXECUTABLE" --uninstall-cleanup; then
            log_success "App-owned cleanup completed for ${user_name}"
            ran_cleanup=true
        else
            log_warning "App-owned cleanup failed for ${user_name}"
            cleanup_failed=true
        fi
    done

    if [ "$ran_cleanup" = false ]; then
        log_info "No logged-in GUI users found for app-owned cleanup"
    fi

    if [ "$cleanup_failed" = true ]; then
        return 1
    fi
}

forget_package_receipts() {
    local removed_any=false
    local pkg_id

    for pkg_id in "${PACKAGE_IDS[@]}"; do
        if pkgutil --pkg-info "$pkg_id" &>/dev/null; then
            if pkgutil --forget "$pkg_id" >/dev/null 2>&1; then
                log_success "Removed package receipt for ${pkg_id}"
                removed_any=true
            else
                log_warning "Could not remove package receipt for ${pkg_id}"
            fi
        fi
    done

    if [ "$removed_any" = false ]; then
        log_info "No package receipts found"
    fi
}

# --- Main Uninstall Process ---
main() {
    echo "=========================================="
    echo "Abloomify Device Agent Uninstaller"
    echo "=========================================="
    echo ""

    # Check for root privileges
    check_root

    log_info "Starting uninstall process..."
    if [ "$PRESERVE_IDENTITY" = true ]; then
        log_info "Preserving device certificate identity for update/preinstall"
    fi
    echo ""

    # Step 1: Unload launch agents for all users
    log_info "Unloading launch agents..."

    # Unload from all GUI sessions
    local unloaded=false
    for USER_ID in $(get_gui_user_ids); do
        if launchctl bootout "gui/${USER_ID}/${LAUNCH_AGENT_NAME}" 2>/dev/null; then
            log_success "Unloaded ${LAUNCH_AGENT_NAME} from GUI session ${USER_ID}"
            unloaded=true
        fi
        if launchctl bootout "gui/${USER_ID}/${XPC_LAUNCH_AGENT_NAME}" 2>/dev/null; then
            log_success "Unloaded ${XPC_LAUNCH_AGENT_NAME} from GUI session ${USER_ID}"
            unloaded=true
        fi
    done

    # Also try legacy unload for the system-wide agent
    if launchctl unload "/Library/LaunchAgents/${LAUNCH_AGENT_FILE}" 2>/dev/null; then
        log_success "Unloaded ${LAUNCH_AGENT_NAME} using legacy method"
        unloaded=true
    fi
    if launchctl unload "/Library/LaunchAgents/${XPC_LAUNCH_AGENT_FILE}" 2>/dev/null; then
        log_success "Unloaded ${XPC_LAUNCH_AGENT_NAME} using legacy method"
        unloaded=true
    fi

    # Unload the privileged self-update LaunchDaemon (system domain) and remove its spool.
    if launchctl bootout system "/Library/LaunchDaemons/com.abloomify.updater.plist" 2>/dev/null; then
        log_success "Unloaded com.abloomify.updater LaunchDaemon"
        unloaded=true
    fi
    launchctl unload "/Library/LaunchDaemons/com.abloomify.updater.plist" 2>/dev/null || true
    rm -f "/Library/LaunchDaemons/com.abloomify.updater.plist" 2>/dev/null || true
    rm -rf "/Library/Application Support/Abloomify/UpdateSpool" 2>/dev/null || true

    if [ "$unloaded" = false ]; then
        log_info "No active launch agents found"
    fi
    echo ""

    # Step 2: Kill all running instances so cleanup can run without data being recreated.
    log_info "Terminating all ${APP_NAME} processes..."

    # First try graceful termination
    local pids=$(pgrep -x "$PROCESS_NAME" 2>/dev/null || true)
    local xpc_pids=$(pgrep -x "$XPC_PROCESS_NAME" 2>/dev/null || true)
    pids="${pids} ${xpc_pids}"
    pids=$(echo "$pids" | xargs 2>/dev/null || true)
    if [ -n "$pids" ]; then
        log_info "Found running processes: $pids"
        for pid in $pids; do
            kill -TERM "$pid" 2>/dev/null || true
        done
        sleep 2

        # Force kill if still running
        pids="$(pgrep -x "$PROCESS_NAME" 2>/dev/null || true) $(pgrep -x "$XPC_PROCESS_NAME" 2>/dev/null || true)"
        pids=$(echo "$pids" | xargs 2>/dev/null || true)
        if [ -n "$pids" ]; then
            log_warning "Force killing remaining processes..."
            for pid in $pids; do
                kill -9 "$pid" 2>/dev/null || true
            done
            sleep 1
        fi
        log_success "All processes terminated"
    else
        log_info "No running processes found"
    fi
    echo ""

    # Step 3: Ask the signed app to remove sensitive data from its sandbox/App Group.
    log_info "Running app-owned cleanup..."
    if ! run_app_uninstall_cleanup; then
        log_warning "App-owned cleanup reported failures; final verification will check sensitive data"
    fi
    echo ""

    # Step 4: Remove launch agent files
    log_info "Removing launch agent files..."

    # Remove system-wide launch agent
    if [ -f "/Library/LaunchAgents/${LAUNCH_AGENT_FILE}" ]; then
        remove_path_if_exists "/Library/LaunchAgents/${LAUNCH_AGENT_FILE}" "system-wide launch agent"
    fi
    if [ -f "/Library/LaunchAgents/${XPC_LAUNCH_AGENT_FILE}" ]; then
        remove_path_if_exists "/Library/LaunchAgents/${XPC_LAUNCH_AGENT_FILE}" "Chrome telemetry XPC launch agent"
    fi

    # Remove user-specific launch agents
    local removed_user_agents=false
    for USER_HOME in /Users/*; do
        if [ -d "$USER_HOME" ] && [ "$USER_HOME" != "/Users/Shared" ] && [ "$USER_HOME" != "/Users/Guest" ]; then
            local user_agent="${USER_HOME}/Library/LaunchAgents/${LAUNCH_AGENT_FILE}"
            if [ -f "$user_agent" ]; then
                remove_path_if_exists "$user_agent" "launch agent for $(basename "$USER_HOME")"
                removed_user_agents=true
            fi
            local user_xpc_agent="${USER_HOME}/Library/LaunchAgents/${XPC_LAUNCH_AGENT_FILE}"
            if [ -f "$user_xpc_agent" ]; then
                remove_path_if_exists "$user_xpc_agent" "Chrome telemetry XPC launch agent for $(basename "$USER_HOME")"
                removed_user_agents=true
            fi
        fi
    done

    if [ "$removed_user_agents" = false ]; then
        log_info "No user-specific launch agents found"
    fi
    echo ""

    # Step 5: Remove application
    log_info "Removing application..."

    if [ -d "$APP_PATH" ]; then
        remove_path_if_exists "$APP_PATH" "${APP_PATH}"
    else
        log_info "Application not found at ${APP_PATH}"
    fi

    # Remove the legacy (pre-rename) bundle if a prior build left it in /Applications.
    if [ -d "$LEGACY_APP_PATH" ]; then
        remove_path_if_exists "$LEGACY_APP_PATH" "${LEGACY_APP_PATH} (legacy)"
    fi

    # Check for app in user Applications folders
    for USER_HOME in /Users/*; do
        if [ -d "$USER_HOME" ] && [ "$USER_HOME" != "/Users/Shared" ] && [ "$USER_HOME" != "/Users/Guest" ]; then
            local user_app="${USER_HOME}/Applications/${APP_NAME}.app"
            if [ -d "$user_app" ]; then
                remove_path_if_exists "$user_app" "app from $(basename "$USER_HOME")/Applications"
            fi
        fi
    done
    echo ""

    # Step 6: Forget package receipts before optional user-data cleanup.
    log_info "Removing package receipts..."
    forget_package_receipts
    echo ""

    # Step 7: Remove Chrome Native Messaging Host
    log_info "Removing Chrome Native Messaging Host..."

    local chrome_host="/Library/Google/Chrome/NativeMessagingHosts/com.abloomify.identity.json"
    if [ -f "$chrome_host" ]; then
        remove_path_if_exists "$chrome_host" "Chrome Native Messaging Host"
    else
        log_info "Chrome Native Messaging Host not found"
    fi

    local removed_user_hosts=false
    for USER_HOME in /Users/*; do
        if [ -d "$USER_HOME" ] && [ "$USER_HOME" != "/Users/Shared" ] && [ "$USER_HOME" != "/Users/Guest" ]; then
            local user_chrome_host="${USER_HOME}/Library/Application Support/Google/Chrome/NativeMessagingHosts/com.abloomify.identity.json"
            if [ -f "$user_chrome_host" ]; then
                remove_path_if_exists "$user_chrome_host" "user Chrome Native Messaging Host for $(basename "$USER_HOME")"
                removed_user_hosts=true
            fi
        fi
    done

    if [ "$removed_user_hosts" = false ]; then
        log_info "No user Chrome Native Messaging Hosts found"
    fi
    echo ""

    # Step 8: Remove logs
    log_info "Removing log files..."

    if [ -d "/Library/Logs/${APP_NAME}" ]; then
        remove_path_if_exists "/Library/Logs/${APP_NAME}" "system logs"
    fi
    if [ -f "$MAIN_STDOUT_LOG" ]; then
        remove_path_if_exists "$MAIN_STDOUT_LOG" "main app stdout log"
    fi
    if [ -f "$MAIN_STDERR_LOG" ]; then
        remove_path_if_exists "$MAIN_STDERR_LOG" "main app stderr log"
    fi
    if [ -f "$XPC_STDOUT_LOG" ]; then
        remove_path_if_exists "$XPC_STDOUT_LOG" "Chrome telemetry XPC stdout log"
    fi
    if [ -f "$XPC_STDERR_LOG" ]; then
        remove_path_if_exists "$XPC_STDERR_LOG" "Chrome telemetry XPC stderr log"
    fi

    # Remove user-specific logs
    for USER_HOME in /Users/*; do
        if [ -d "$USER_HOME" ] && [ "$USER_HOME" != "/Users/Shared" ] && [ "$USER_HOME" != "/Users/Guest" ]; then
            local user_logs="${USER_HOME}/Library/Logs/${APP_NAME}"
            if [ -d "$user_logs" ]; then
                remove_path_if_exists "$user_logs" "logs for $(basename "$USER_HOME")"
            fi
        fi
    done
    echo ""

    # Step 9: Remove non-container user data. Container contents are cleaned by the app-owned step above.
    if [ "$PRESERVE_IDENTITY" = true ]; then
        log_info "Preserving application container and device identity data"
        echo ""
    else
        log_info "Removing application data..."

        local removed_containers=false
        for USER_HOME in /Users/*; do
            if [ -d "$USER_HOME" ] && [ "$USER_HOME" != "/Users/Shared" ] && [ "$USER_HOME" != "/Users/Guest" ]; then
                # Also remove Application Support data
                local app_support="${USER_HOME}/Library/Application Support/${APP_NAME}"
                if [ -d "$app_support" ]; then
                    remove_user_path_if_exists "$app_support" "Application Support data for $(basename "$USER_HOME")" "$USER_HOME"
                fi

                # Remove preferences
                local prefs="${USER_HOME}/Library/Preferences/${BUNDLE_ID}.plist"
                if [ -f "$prefs" ]; then
                    remove_user_path_if_exists "$prefs" "preferences for $(basename "$USER_HOME")" "$USER_HOME"
                fi
            fi
        done

        if [ "$removed_containers" = false ]; then
            log_info "No container data found"
        fi
        echo ""
    fi

    # Step 10: Remove temporary installation artifacts
    log_info "Removing temporary installation artifacts..."

    if [ -d "/Applications/LaunchAgents" ]; then
        remove_path_if_exists "/Applications/LaunchAgents" "temporary LaunchAgents folder"
    fi

    if [ -f "$DIAGNOSTIC_HELPER_PATH" ]; then
        remove_path_if_exists "$DIAGNOSTIC_HELPER_PATH" "diagnostic helper"
    fi
    echo ""

    # Step 11: Final verification
    log_info "Performing final verification..."

    local all_clean=true

    # Check for running processes
    if pgrep -x "$PROCESS_NAME" >/dev/null 2>&1; then
        log_error "Processes still running!"
        all_clean=false
    fi
    if pgrep -x "$XPC_PROCESS_NAME" >/dev/null 2>&1; then
        log_error "Chrome telemetry XPC process still running!"
        all_clean=false
    fi

    # Check for application
    if [ -d "$APP_PATH" ]; then
        log_error "Application still exists!"
        all_clean=false
    fi

    # Check for launch agents
    if [ -f "/Library/LaunchAgents/${LAUNCH_AGENT_FILE}" ]; then
        log_error "Launch agent still exists!"
        all_clean=false
    fi
    if [ -f "/Library/LaunchAgents/${XPC_LAUNCH_AGENT_FILE}" ]; then
        log_error "Chrome telemetry XPC launch agent still exists!"
        all_clean=false
    fi

    for USER_ID in $(get_gui_user_ids); do
        if launchctl print "gui/${USER_ID}/${LAUNCH_AGENT_NAME}" >/dev/null 2>&1; then
            log_error "Launch agent still loaded for GUI session ${USER_ID}!"
            all_clean=false
        fi
        if launchctl print "gui/${USER_ID}/${XPC_LAUNCH_AGENT_NAME}" >/dev/null 2>&1; then
            log_error "Chrome telemetry XPC launch agent still loaded for GUI session ${USER_ID}!"
            all_clean=false
        fi
    done

    for pkg_id in "${PACKAGE_IDS[@]}"; do
        if pkgutil --pkg-info "$pkg_id" &>/dev/null; then
            log_error "Package receipt still exists: ${pkg_id}"
            all_clean=false
        fi
    done

    if [ "$PRESERVE_IDENTITY" != true ]; then
        for USER_HOME in /Users/*; do
            if [ -d "$USER_HOME" ] && [ "$USER_HOME" != "/Users/Shared" ] && [ "$USER_HOME" != "/Users/Guest" ]; then
                local app_group_identity="${USER_HOME}/Library/Group Containers/${APP_GROUP_ID}/DeviceIdentity"
                local legacy_identity="${USER_HOME}/Library/Containers/${BUNDLE_ID}/Data/Library/Application Support/DeviceIdentity"
                local restart_history="${USER_HOME}/Library/Containers/${BUNDLE_ID}/Data/Library/Application Support/${APP_NAME}/restart_history.json"
                local crash_marker="${USER_HOME}/Library/Containers/${BUNDLE_ID}/Data/Library/Application Support/crash_marker.txt"
                local debug_logs="${USER_HOME}/Library/Containers/${BUNDLE_ID}/Data/Documents/AbloomifyLogs"
                local app_cache="${USER_HOME}/Library/Containers/${BUNDLE_ID}/Data/Library/Caches/${BUNDLE_ID}"

                for sensitive_path in "$app_group_identity" "$legacy_identity" "$restart_history" "$crash_marker" "$debug_logs" "$app_cache"; do
                    if [ -e "$sensitive_path" ] || [ -L "$sensitive_path" ]; then
                        log_error "Sensitive Abloomify data still exists for $(basename "$USER_HOME"): ${sensitive_path}"
                        all_clean=false
                    fi
                done
            fi
        done
    fi

    if [ -f "$DIAGNOSTIC_HELPER_PATH" ]; then
        log_error "Diagnostic helper still exists!"
        all_clean=false
    fi
    if [ -f "$MAIN_STDOUT_LOG" ]; then
        log_error "Main app stdout log still exists!"
        all_clean=false
    fi
    if [ -f "$MAIN_STDERR_LOG" ]; then
        log_error "Main app stderr log still exists!"
        all_clean=false
    fi
    if [ -f "$XPC_STDOUT_LOG" ]; then
        log_error "Chrome telemetry XPC stdout log still exists!"
        all_clean=false
    fi
    if [ -f "$XPC_STDERR_LOG" ]; then
        log_error "Chrome telemetry XPC stderr log still exists!"
        all_clean=false
    fi

    if [ "$all_clean" = true ]; then
        log_success "All components successfully removed"
    else
        log_warning "Some components could not be removed. Manual cleanup may be required."
    fi

    echo ""
    echo "=========================================="
    echo "Uninstall process completed"
    echo "=========================================="
    echo ""

    if [ "$all_clean" != true ]; then
        exit 1
    fi

    # Optional: Prompt for restart (skip in MDM mode)
    if [[ -t 0 ]]; then  # Check if running interactively
        read -p "A restart is recommended. Restart now? (y/n): " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            log_info "Restarting system..."
            shutdown -r now
        fi
    else
        log_info "Note: A system restart is recommended after uninstallation"
    fi
}

# --- Run main function ---
main "$@"

exit 0
