#!/bin/bash

# Bash script to delete specific folders on macOS.
# This script requires super user permissions to delete files within system directories.

# --- Configuration ---

# Define the list of specific folder names to search for.
# These patterns will be matched against the *basename* of directories found.
# If a pattern should match variations (e.g., 'com.NeuxPower.App*'), add a wildcard.
target_folder_names=(
    "com.NeuxPower"
    "E93V9LXJ5G."
    "E93V9LXJ5G.com.NeuxPower.NXPowerLite-Desktop.NXEngineXPCService"
    "E93V9LXJ5G.com.NeuxPower"
    "com.NeuxPower.NXPowerLite-Desktop"
    "com.NeuxPower.NXPowerLite-Desktop.NXEngineXPCService"
    "com.NeuxPower.NXPowerLite-Desktop.NXPowerFinderExtension"
)

# Define the base directories where the script will recursively search.
# The '~' will be expanded to the current user's home directory.
base_search_directories=(
    "~/Library/Application Scripts"
    "~/Library/Group Containers"
    "~/Library/Containers"
    "/private/var/folders"
)

# --- Script Logic ---

echo "Starting generic folder deletion script..."
echo "---------------------------------------------------------"

declare -a found_folders_for_deletion # Array to store all folders found
declare -a deletion_failures # Array to store folders that failed to delete

# Phase 1: Search for target folders
echo "Phase 1: Searching for target folders..."
echo "---------------------------------------------------------"

for base_path_tildepath in "${base_search_directories[@]}"; do
    # Expand the tilde (~) to the actual home directory path
    base_path=$(eval echo "$base_path_tildepath")

    if [ -d "${base_path}" ]; then
        echo -e "\nSearching within: ${base_path}"
        for target_name in "${target_folder_names[@]}"; do
            echo "  Looking for directories named: '${target_name}'..."
            # Use 'find' to locate directories matching the target name recursively
            # -type d: searches for directories only
            # -name "${target_name}": matches the basename of the directory
            # -print0: prints results separated by a null character (robust for unusual filenames)
            # 2>/dev/null: redirects any errors from find (e.g., permission denied for certain sub-paths)
            while IFS= read -r -d $'\0' folder; do
                echo "    -> Found: ${folder}"
                found_folders_for_deletion+=("$folder")
            done < <(find "${base_path}" -type d -name "${target_name}" -print0 2>/dev/null)
        done
    else
        echo -e "\n  Base search path not found or not a directory: ${base_path}. Skipping."
    fi
done

echo -e "\n---------------------------------------------------------"
echo "Phase 1 Complete: Found ${#found_folders_for_deletion[@]} potential folders for deletion."
echo "---------------------------------------------------------"

# Phase 2: Confirmation and Deletion
if [ ${#found_folders_for_deletion[@]} -eq 0 ]; then
    echo "No matching folders were found. Nothing to delete."
else
    echo -e "\nList of ALL folders found that match the criteria:"
    for i in "${!found_folders_for_deletion[@]}"; do
        echo "  $((i+1)). ${found_folders_for_deletion[$i]}"
    done

    echo -e "\nWARNING: This will permanently delete these folders and their contents."
    read -rp "Do you want to proceed with deleting these folders? (y/N): " confirm_delete

    if [[ "$confirm_delete" =~ ^[Yy]$ ]]; then
        echo -e "\nPhase 2: Proceeding with deletion..."
        echo "---------------------------------------------------------"
        for folder_to_delete in "${found_folders_for_deletion[@]}"; do
            echo -e "\nAttempting to delete: ${folder_to_delete}"
            rm -rf "${folder_to_delete}"
            if [ $? -eq 0 ]; then
                echo "  ✅ Successfully deleted: ${folder_to_delete}"
            else
                echo "  ❌ Failed to delete: ${folder_to_delete}. This might be due to permissions or other issues."
                deletion_failures+=("$folder_to_delete")
            fi
        done

        echo -e "\n---------------------------------------------------------"
        echo "Phase 2 Complete: Deletion attempt finished."
        echo "---------------------------------------------------------"

        # Phase 3: Report deletion failures
        if [ ${#deletion_failures[@]} -gt 0 ]; then
            echo -e "\nPhase 3: Issues encountered during deletion:"
            echo "The following folders could NOT be deleted:"
            for failed_folder in "${deletion_failures[@]}"; do
                echo "  - ${failed_folder}"
            done
            echo "Please check permissions or manually remove these folders if necessary."
        else
            echo -e "\nPhase 3: No issues to report. All found folders were successfully deleted. 🎉"
        fi
    else
        echo -e "\nDeletion cancelled by user. No folders were deleted."
    fi
fi

echo -e "\n---------------------------------------------------------"
echo "Script execution complete."
echo "Remember to run with 'sudo' for full effectiveness."
