#!/usr/bin/env bash
#
# tint2-pipemenu - an Openbox pipemenu for tint2 manipulation
# Copyright (C) 2015-2016 damo
#
# 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 ZEN_BIN="manjaro-tint2zen"
readonly DEFAULT_TINT2="$HOME/.config/tint2/KvFlatRed.tint2rc"
readonly HELP="
manjaro-tint2-pipemenu is an Openbox Pipe Menu for tint2 manipulation
It should normally be called from an openbox menu.

Options:
    -h --help   show this message

If manjaro-tint2-pipemenu is called with no options (the usual method),
it will output an xml openbox pipemenu for handling tint2 sessions,
and editing configuration files.

For more information, see \"man tint2\"
and Help >> Tint2 in the menu."

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


tint_edit_menu() {
    menuSeparator
    if has xdg-open &>/dev/null; then
        menuItem "Default tint2rc" "xdg-open $DEFAULT_TINT2"
    elif hash exo-open &>/dev/null; then
        menuItem "Default tint2rc" "exo-open $DEFAULT_TINT2"
    else
        menuItem "Default tint2rc" "$TERMITE -e '$EDITOR $DEFAULT_TINT2'"
    fi
    if [[ $(pidof tint2) ]]; then
        menuSubmenu "RunningTint2" "Running Tint2s"
            while read -r pid cmd; do
                if [[ ${cmd%% *} = tint2 ]]; then
                    TINT=${cmd##* }
                    TINT2=${TINT#$HOME/.config/}
                    if [[ $TINT = tint2 ]]; then
                        TINT="$DEFAULT_TINT2"
                        TINT2="Default tint2rc"
                    fi
                    if hash exo-open &>/dev/null; then
                        menuItem "$TINT2" "xdg-open $TINT"
                    elif has xdg-open &>/dev/null; then
                        menuItem "Default tint2rc" "xdg-open $DEFAULT_TINT2"
                    else
                        menuItem "$TINT2" "sakura -e '$EDITOR $TINT'"
                    fi
                fi
            done <<< "$(pgrep -a tint2)"
        menuSubmenuEnd
    fi
}

edit_menu() {
    menuSubmenu "EditTint2" "Edit Tint2s"
        if type manjaro-tint2edit &>/dev/null; then
            menuItem "Tint2 Editor" "manjaro-tint2edit"
        fi
        tint_edit_menu
    menuSubmenuEnd
}

chooser_menu() {
    if type $ZEN_BIN &>/dev/null; then
        menuItem "Tint2 Session" "$ZEN_BIN"
    fi
}

restart_menu() {
    if [[ $(pidof tint2) ]];then
        if type manjaro-tint2restart &>/dev/null; then
            menuItem "Restart Tint2" "manjaro-tint2restart"
        fi
        menuItem "Stop Tint2s" "pkill tint2"
    fi
}

menuStart "Tintmenu" "Tint2"
    menuItem "Tint2 Settings" "tint2conf"
    chooser_menu
    restart_menu
    edit_menu
menuEnd
