#!/usr/bin/env bash
#
# tintedit: a tint2 config file editor
# Copyright (C) 2015 damo <damo@bunsenlabs.org>
#
#
# forked by manjaro <fhatmanjaroorg>
#

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

readonly TITLE="Tint2 Raw File Editor"
readonly ICON="--window-icon=/usr/share/icons/manjaro/maia/48x48.png"
readonly CHECKLIST="zenity --width=400 --height=500 $ICON --list --checklist --multiple"
readonly CONFIG_PATH="$HOME/.config/tint2"
readonly FILES=($(find "$CONFIG_PATH" -maxdepth 2 -type f))
readonly HELP="
\tmanjaro-tint2-edit a script to edit selected tint2 config files
\nOptions:
\t-h --help   show this message
\nNo other options are supported.
\nTint2 files must be in $CONFIG_PATH
Checkmarked tint2s will be opened in the text editor.
Multiple tint2s can be chosen."

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

declareDependencies zenity

open_configs() {
    for file in "${FILES[@]}"; do
        NAME=$(basename "$file")
        if grep -q "panel_monitor" "$file" || [[ $NAME = *tint2rc ]] || [[ $NAME == 'tint2rc' ]] && [[ ! $NAME =~ "backup" ]]; then
            LIST="$LIST FALSE $NAME"
            ARRAY+=("$file")
        fi
    done
    MSG="<big>Select tint2 configs to edit</big>\n\n"
    ANSWER=$($CHECKLIST --title="$TITLE" --text="$MSG" --column="Select" --column="Name" $LIST --separator=" ")
    if [[ $? == 1 ]]; then
        exit 0
    else
        for name in $ANSWER; do
            for file in "${ARRAY[@]}"; do
                if [[ $(basename "$file") == "$name" ]]; then
                    if hash xdg-open &>/dev/null; then
                        (xdg-open "$file" &) ; break
                    elif hash exo-open &>/dev/null; then
                        (exo-open "$file" &) ; break
                    else
                        ($TERMINAL -e "$EDITOR $file" &) ; break
                    fi
                fi
            done
        done
    fi
}

open_configs

exit 0
