#!/usr/bin/env bash
# Daniel Napora 2020 <napcok@gmail.com>

# Read a directory to an array and sort it directories first.
case $LANG in
    pl*)
        DIRECTORIES="Katalogi"
        FILES="Pliki"
        OPENDIR="Otwórz w menadżerze plików"
        OPENTERM="Otwórz w terminalu"
        ;;
    es*)
        DIRECTORIES="Directorios"
        FILES="Archivos"
        OPENDIR="Abrir Gestor de archivos aquí"
        OPENTERM="Abrir terminal aquí"
        ;;
    *)
        DIRECTORIES="Directories"
        FILES="Files"
        OPENDIR="Open filemanager here"
        OPENTERM="Open terminal here"
     ;;
esac
    
: ${JGMENU_RESOURCE_OPENER=xdg-open}
    
    DIRECTORY=${1:-$HOME}

    # If '$DIRECTORY' is '/', unset it to avoid '//'.
    [[ $DIRECTORY == / ]] && DIRECTORY=

    for item in "$DIRECTORY"/*; do
        if [[ -d $item ]]; then
            dirs+=("${item##*/},^pipe(jgbrowser \"$DIRECTORY/${item##*/}\")")
        else
        if [[ -f $item ]]; then
            files+=("${item##*/},xdg-open \"$DIRECTORY/${item##*/}\"")
        fi
        fi
    done
    
printf "%b\n" "^sep(<small><i>${DIRECTORY:-/}</i></small>)"
printf "%b\n" "   $OPENDIR,${JGMENU_RESOURCE_OPENER} \"${DIRECTORY:-/}\""
printf "%b\n" "    $OPENTERM,exo-open --launch TerminalEmulator --working-directory=\"${DIRECTORY:-/}\""
if [ ${#dirs[@]} -ne 0 ]; then
    printf "%b\n" "^sep($DIRECTORIES)"
    printf '%s\n' "${dirs[@]}"
fi
if [ ${#files[@]} -ne 0 ]; then
    printf "%b\n" "^sep($FILES)"
    printf '%s\n' "${files[@]}"
fi