#!/bin/sh
# $HOME file-manager with rofi
# adapted from dfm by prx <prx@ybad.name>
# licence: MIT

userlocale=$(echo $LANG | cut -b-2)
case $userlocale in
    fr) prompt="ouvrir " ;;
    *) prompt="open " ;;
esac

[ $# -eq 0 ] && curpath="$HOME"
[ $# -eq 1 ] && curpath="$1"
[ ! -d "${curpath}" ] && exit

selection=$(ls -ap "${curpath}" | rofi -dmenu -p "${prompt}")
[ -z "${selection}" ] && exit

case $userlocale in
    fr) promptopen="ouvrir ${selection} avec " ;;
    *) promptopen="open ${selection} with " ;;
esac

case ${selection} in
    */ ) ${0} "${curpath}/${selection}" ;;
    *  )
        # system decide how to open file
        #xdg-open "${curpath}/${selection}"

        # user decide how to open file
        # define default application for selection
        defdesk=$(xdg-mime query default $(printf $(xdg-mime query filetype "${curpath}/${selection}")))
        defapp=$(grep ^Exec /usr/share/applications/${defdesk} | sed -e 's/^[^=]*=//g' | sed -e 's/%.*//g')
        # get all apps in $PATH
        allapps=$(for d in $(printf $PATH | sed 's/:/\n/g'); do cd $d; ls; done)
        # launch menu
        run=$(printf "${defapp}\n${allapps}" | \
            rofi -dmenu -p "${promptopen}")
        exec ${run} "${curpath}/${selection}" && exit
        ;;
esac
