#!/bin/bash

# Define the folder containing scripts
SCRIPT_DIR="/usr/local/bin/flatpacks"

# Check if the directory exists
if [[ ! -d "$SCRIPT_DIR" ]]; then
    echo "Directory $SCRIPT_DIR does not exist."
    exit 1
fi

# Get the list of executable scripts
SCRIPTS=($(find "$SCRIPT_DIR" -maxdepth 1 -type f -executable))

# Check if there are any scripts
if [[ ${#SCRIPTS[@]} -eq 0 ]]; then
    whiptail --msgbox "No executable scripts found in $SCRIPT_DIR." 10 40
    exit 0
fi

# Prepare menu options
MENU_OPTIONS=()
declare -A SCRIPT_MAP

for script in "${SCRIPTS[@]}"; do
    # Get base name, remove underscores, and capitalize first letter of each word
    DISPLAY_NAME=$(basename "$script" | sed 's/_/ /g' | awk '{for(i=1;i<=NF;i++) $i=toupper(substr($i,1,1)) tolower(substr($i,2)); print}')

    # Exclude scripts with "Toolbox" in the name
    if [[ "$DISPLAY_NAME" != *"Toolbox"* ]]; then
        MENU_OPTIONS+=("$DISPLAY_NAME" "")
        SCRIPT_MAP["$DISPLAY_NAME"]="$script"
    fi
done

# Show the menu using whiptail with the new title
CHOICE=$(whiptail --title "TyOS Flatpacks Selections" --menu "Choose A Script To Run:" 15 50 5 "${MENU_OPTIONS[@]}" 3>&1 1>&2 2>&3)

# Check if the user made a selection
if [[ -n "$CHOICE" ]]; then
    SCRIPT_PATH="${SCRIPT_MAP[$CHOICE]}"
    "$SCRIPT_PATH"
fi