#!/usr/bin/env bash

# This file is part of I38.

# I38 is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation,
# either version 3 of the License, or (at your option) any later version.

# I38 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.

# You should have received a copy of the GNU General Public License along with I38. If not, see <https://www.gnu.org/licenses/>.

# Make sure there is a desktop to search.
if [[ ! -d ~/Desktop ]]; then
    exit 0
fi

# Discover directories and files on the desktop
mapfile -t desktopDirs < <(find ~/Desktop -mindepth 1 -maxdepth 1 -type d)
mapfile -t desktopFiles < <(find ~/Desktop -mindepth 1 -maxdepth 1 -type f)

# Combine directories and files into one list
desktopItems=("${desktopDirs[@]}" "${desktopFiles[@]}")

# Build menu for yad.
declare -a menuList
for i in "${desktopItems[@]}" ; do
    case "$i" in
        *".desktop")
            menuList+=("$(grep "^Name" "$i" | cut -f2- -d '=')" "gio launch \"$i\"")
        ;;
        *)
            menuList+=("${i##*/}" "/usr/bin/env xdg-open \"$i\"")
        ;;
    esac
done

launch=$(yad --list \
    --title="I38 Desktop" \
    --column="Items" \
    --column="Launch Command" \
    --close-on-unfocus \
    --hide-column=2 \
    --search-column=1 \
    --skip-taskbar \
    "${menuList[@]}")
if [[ $? -eq 0 ]]; then
    launch="${launch%|}"
    launch="${launch##*|}"
    eval "$launch"
fi
