#!/usr/bin/env bash

####
# @author moonarch.de (nevaforget)
# script used with rofi to list desktop files of specific dir
# dir: /usr/share/settings-menu/
# @example rofi -show fb -modes "fb:~/.config/rofi/settings-menu/setmen.sh" -theme $HOME/.config/rofi/settings-menu/settings-menu.rasi
# @dependencies glib >= 2.67.2
#### 

function get_name {
    local lang=$(locale | grep LANG | cut -d= -f2 | cut -d_ -f1)
    local find="Name\[$lang\]="
    
    local name=$(grep "^$find" $1 | tail -1 | sed "s/^$find//" | sed 's/%.//' | sed 's/^"//g' | sed 's/" *$//g')

    if [ "${name}" = "" ]
    then
        find="Name="
        name=$(grep "^$find" $1 | tail -1 | sed "s/^$find//" | sed 's/%.//' | sed 's/^"//g' | sed 's/" *$//g')
    fi

    echo "$name"
}

if [ "$ROFI_RETV" = "1" ]
then
    for deskfile in /usr/share/settings-menu/*
    do
        match=$(grep "^Name" $deskfile | grep "$@" ) 

        if [ -n "$match" ]
        then
            #gio launch $deskfile

            # old way
            app=$(grep '^Exec' $deskfile | tail -1 | sed 's/^Exec=//' | sed 's/%.//' | sed 's/^"//g' | sed 's/" *$//g')
            coproc ( $app  > /dev/null  2>&1 )

            break
        fi

    done
    exit 0
fi

function init {
    for file in /usr/share/settings-menu/*
    do
        local name=$(get_name "$file")

        local iconline=$(sed -n -e '/^Icon=/p' "$file")
        local icon=${iconline/Icon=/""}

        if [ -n "$name" ]
        then
            echo -en "$name\0icon\x1f$icon\n"

        fi

    done
}

init