#!/bin/bash

    # This program 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.

    # This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.

# A dmenu script to run installed Flatpak applications.

# pass custom colours to dmenu command
source "$HOME/.local/share/my_colours/active-tempus-theme.sh"

# get the system-wide custom font
source "$HOME/.local/share/my_custom_ui_font.sh"

# the customised `dmenu` command
my_dmenu() {
    dmenu -i -p 'Flatpak run' -nb "$background" -nf "$foreground" \
    -sb "$color6" -sf "$background" -fn "$my_custom_ui_font"
}

# select item in a list
my_flatpaks_selection() {
	# We use this method instead of "flatpak list".  It is faster.  The
	# sed ciommand removes the full file path as well as the first
	# result which is the directory name containing the items we need.
	find /var/lib/flatpak/app/ -maxdepth 1 -printf "%f\\n" | \
	sed 's,^/.*/,, ; 1d' | my_dmenu
}

# capture dmenu output
my_flatpaks_choice=$(my_flatpaks_selection)

# get the selected flatpak's corresponding icon
# NOTE this match may require further tweaks
my_flatpaks_choice_icon="$(find /var/lib/flatpak/app/$my_flatpaks_choice \( -name "*.svg" -o -name "*.png" \) | sed 1q)"

# notify about the attempt to run the flatpak app (because these usually
# take some time to perform an initial launch).
if [ "$my_flatpaks_choice" ]; then
    notify-send -i "$my_flatpaks_choice_icon" "Flatpakmenu" "Preparing to execute command:\nflatpak run <b>$my_flatpaks_choice</b>"
    echo "Preparing to run:"
    echo "flatpak run \"$my_flatpaks_choice\""
    flatpak run "$my_flatpaks_choice" &
fi
