#!/bin/zsh
# Enhance error handling
set -euo pipefail
echo "Listing all installed non-Apple package identifiers..."
# Filter out packages that start with com.apple
pkgutil --pkgs | grep -v "^com.apple"
echo "\nPlease enter the package identifier from the list above that you wish to uninstall:"
read pkg_id
if [[ -z "$pkg_id" ]]; then
echo "No package identifier entered. Exiting..."
exit 1
fi
# Validate if the package identifier is for an Apple package
if [[ "$pkg_id" =~ ^com.apple ]]; then
echo "Apple packages cannot be uninstalled using this script. Exiting..."
exit 1
fi
# Ask the user if they want to see the files associated with the package
echo "Do you want to see the files associated with $pkg_id? (y/N)"
read -r see_files
pkg_files=$(pkgutil --files "$pkg_id" || echo "")
# Check if pkg_files is non-empty
if [[ -z "$pkg_files" ]]; then
echo "No files found for $pkg_id, or it may not be a valid package identifier. Exiting..."
exit 1
fi
# If user wants to see the files, print them
if [[ "$see_files" == "y" ]] || [[ "$see_files" == "Y" ]]; then
echo "Listing files for $pkg_id..."
echo "$pkg_files"
fi
# Confirm with the user for uninstallation
echo "\nDo you really want to uninstall $pkg_id and all its associated files? This action cannot be undone. (y/N)"
read -r confirm_uninstall
if [[ "$confirm_uninstall" != "y" ]] && [[ "$confirm_uninstall" != "Y" ]]; then
echo "Uninstall cancelled."
exit 1
fi
# Splitting the pkg_files string into an array by newlines
IFS=$'\n' pkg_files_array=($pkg_files)
unset IFS
# Remove the files and directories
echo "Removing files..."
for file_path in "${pkg_files_array[@]}"; do
full_path="/$file_path"
if [[ -e "$full_path" ]]; then
sudo rm -rf "$full_path"
echo "Removed $full_path"
else
echo "File $full_path does not exist or has already been removed."
fi
done
# Forget the package to remove its receipt
echo "Removing package receipt..."
sudo pkgutil --forget "$pkg_id" && echo "Package receipt removed for $pkg_id."
# Heuristic search for the application bundle in /Applications
echo "Searching for related application bundles in the /Applications folder..."
app_guess=$(echo $pkg_id | cut -d '.' -f 2) # Attempt to extract a meaningful part of the package ID
found_apps=$(find /Applications -type d -name "*$app_guess*.app" -maxdepth 1)
if [[ ! -z "$found_apps" ]]; then
echo "Found application bundle(s) related to $pkg_id:"
echo "$found_apps"
while IFS= read -r app_path; do
echo "Removing application bundle at $app_path"
sudo rm -rf "$app_path"
done <<< "$found_apps"
echo "Application bundle(s) removed."
else
echo "No matching application bundle found in the Applications folder."
fi
echo "Package $pkg_id and its files have been successfully removed."