#!/bin/sh
CYAN='\033[0;36m'
ORANGE='\033[0;33m'
WHITE='\033[1;37m'
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

# Check if script is run as root, if not then re-execute with sudo
if [ "$(id -u)" != "0" ]; then
    exec sudo "$0" "$@"
fi

clear
# Display Header
printf "%b=================================" "$CYAN"
printf "\n%b  Recently Installed Packages   " "$CYAN"
printf "\n%b=================================%b\n" "$CYAN" "$NC"

# Get packages
recent_packages=$(ls -t /var/jb/var/lib/dpkg/info/*.list | sed 's#.*/##; s/.list$//' | while read pkg; do
    if dpkg --get-selections "$pkg" 2>/dev/null | grep -v -E 'deinstall|gsc\.|cy\+|swift-|build-|llvm|clang' | grep -vw 'git' > /dev/null; then
        echo "$pkg"
    fi
done | head -n 10)

# Display exactly 10 packages
count=1
echo "$recent_packages" | while read package; do
    printf "%b%-3s%b %b%s%b\n" "$WHITE" "$count." "$NC" "$ORANGE" "$package" "$NC"
    count=$((count + 1))
done

# Ask for user input
printf "\nEnter the number of the package you want to uninstall (or press Enter to exit): "
read choice

# If user presses Enter without choosing a package
if [ -z "$choice" ]; then
    echo ""
    printf "%bNo package selected. Exiting.%b\n" "$RED" "$NC"
    echo ""
    exit 0
fi

# Get the selected package
selected_package=$(echo "$recent_packages" | sed -n "${choice}p" 2>/dev/null)

# Validate choice and proceed
if [ ! -z "$selected_package" ]; then
    printf "\n%bYou selected: %b%s%b\n" "$CYAN" "$ORANGE" "$selected_package" "$NC"
    printf "%bAre you sure you want to uninstall this package? (y/n): %b" "$CYAN" "$NC"
    read confirm
    # Remove newline from the input if necessary
    confirm=$(echo "$confirm" | tr -d '\n')
    if [ "$confirm" = "y" ]; then
        # Uninstall
        dpkg -r "$selected_package" 2>/dev/null
        if [ $? -eq 0 ]; then
            printf "%bPackage %s has been successfully uninstalled.%b\n" "$GREEN" "$selected_package" "$NC"
        else
            printf "%bFailed to uninstall package %s.%b\n" "$RED" "$selected_package" "$NC"
        fi
    else
        clear
        echo ""
        printf "%bUninstallation canceled.%b\n" "$RED" "$NC"
        echo ""
    fi
else
    clear
    echo ""
    printf "%bInvalid choice. Exiting.%b\n" "$RED" "$NC"
    echo ""
fi