#!/usr/bin/env bash
#
# manjaro-polybar-edit: An Manjaro polybar config file editor
# Copyright (C) 2017 Nathaniel <natemaia10@gmail.com>
#
# forked by manjaro <fhatmanjaroorg>
#

readonly SELECT_MESSAGE="<big>Select Polybar Configs to edit</big>\n"
readonly CONFIG_PATH="$HOME/.config/polybar"
readonly TITLE="Polybar Edit"
readonly ICON="--window-icon=/usr/share/icons/manjaro/maia/48x48.png"
readonly CHECKLIST="zenity $ICON --width=450 --height=500 --list --checklist --multiple"
readonly HELP="manjaro-polybar-edit:
\tA script to edit selected polybar configs
\nOptions:\n\t-h --help   show this message
\tNo other options are supported.\n\nPolybar files must be in $CONFIG_PATH
Checkmarked configs will be opened in a text editor"
readonly COMMON_INCLUDE="/usr/lib/manjaro/common/include.cfg"

if ! . "$COMMON_INCLUDE" 2>/dev/null; then
    echo $"Error: Failed to source $COMMON_INCLUDE" >&2 ; exit 1
fi

declareDependencies zenity

case "$@" in
    -h|--help) echo -e "$HELP" ; exit 0
esac

readonly FILES=($(find -L "$CONFIG_PATH" -maxdepth 2 -type f))
open_configs() {
    for f in "${FILES[@]}"; do
        if [[ $f = *config ]] || [[ $f = *conf ]] || [[ $f = *.sh ]] || [[ -x $f ]]; then
            NAME=$(sed "s|${CONFIG_PATH}/||" <<< "$f")
            LIST="$LIST FALSE $NAME"
        fi
    done
    ANSWER=$($CHECKLIST --title="$TITLE" --text="$SELECT_MESSAGE" --column="Select" --column="File" $LIST --separator=" ")
    if [[ $? == 1 ]]; then
        exit 0
    else
        for CONFIG_FILE in $ANSWER
        do
            FILE_URI="${CONFIG_PATH}/$CONFIG_FILE"
            if hash xdg-open &>/dev/null; then
                (xdg-open "$FILE_URI" &)
            elif hash exo-open &>/dev/null; then
                (exo-open "$FILE_URI" &)
            else
                ($TERMINAL -e "$EDITOR $FILE_URI" &) ; break
            fi
        done
    fi
}

open_configs

exit 0
