#!/usr/bin/env bash

# Read a directory to an array and sort it directories first.

: ${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" "        Otwórz w menadżerze plików,${JGMENU_RESOURCE_OPENER} \"${DIRECTORY:-/}\""
printf "%b\n" "        Otwórz w termianlu,terminator --working-directory=\"${DIRECTORY:-/}\""
printf "%b\n" "^sep()"
if [ ${#dirs[@]} -ne 0 ]; then
    printf "%b\n" "^sep(Katalogi)"
    printf '%s\n' "${dirs[@]}"
fi
if [ ${#files[@]} -ne 0 ]; then
    printf "%b\n" "^sep(Pliki)"
    printf '%s\n' "${files[@]}"
fi