#!/usr/bin/env sh

# Dmenu for quickly finding and opening files to edit.
# If '-r' is passed, it will search root relevant files and edit as root.

# Find the files to be displayed:
case $1 in
    -r|--root) Files=$(sudo find '/etc' -type f)
               AsRoot=' as root';;
    *) Files1=$(find "$LBIN" -type l)
       Files2=$(find "$HOME" "$LSHARE" -maxdepth 1 -type f)
       Files3=$(find "$XDG_DOCUMENTS_DIR/notes" "$XDG_CONFIG_HOME" "$LBIN" -type f)
        # Exclude some paths:
       Files=$(printf "%s\n%s\n%s" "$Files1" "$Files2" "$Files3" | grep -Ev \
       '.tdb|.sql|dump|eb26f4|google-chrome|VirtualBox|BraveSoftware|.config/cargo');;
esac

# Choose the file to open:
Prompt="Select a file to edit${AsRoot}:"
Chosen=$(printf '%s' "$Files" | dmenu -i -l 30 -p "$Prompt")
[ -z "$Chosen" ] && exit 1

# Open the editor with the selected file:
if [ "$1" = '-r' ]; then
    ### If `$EDITOR` is a GUI, permissions will likely get quite messed up.
    sudo $EDITOR "$Chosen"
else
    $EDITOR "$Chosen"
fi
