#!/bin/bash
#
#   Mabox tint2 selection and switcher script
#
#   Written by damo <damo@bunsenlabs.org> for BunsenLabs Linux, April 2015
#   Ported to Manjaro by napcok <napcok@gmail.com>, March 2016
########################################################################
#
#   Tint2 config files must be in $TINT2PATH
#
#   When the dialog opens, any running tint2s will be checkmarked.
#
#   Click "OK" and all running tint2s are stopped, and all checkmarked
#   tint2s are started
#
#   To stop a tint2 just uncheck it, and "OK"
#
#   Running tint2s are saved to a session file, and can be run with
#   the "tint2-session" script. To start them at login, add the 
#   following line to autostart:
#
#           (sleep 2s && mb-tint2-session) &
#
########################################################################
DEBUGFILE="$HOME/.config/mb-tint2-debug.txt"
TINT2PATH="$HOME/.config/tint2"
SESSIONFILE="$TINT2PATH/tint2-sessionfile"
USAGE="\v\tUSAGE:\n\tWith no command argument, the script uses the chosen
\tTint2 session file \"$TINT2PATH/tint2-sessionfile\",
\tif it exists, otherwise the default tint2rc is used
\v\tTo start them at login, add the following line to autostart:
\v\t\t(sleep 2s && mb-tint2-session) &"

### DIALOG VARIABLES
DLGDEC="yad --center --borders=20 --height=500 "
OK="--button=OK:0"
WINICON="--window-icon=distributor-logo-mabox"
case $LANG in
    pl*)
        TITLE="Tint2 Menedżer"
        CANCEL="--button:Anuluj:1"
        SELECT_TINT="Wybierz Tint2 z listy, po kliknięcu <b>OK</b> wszystkie zaznaczone zostaną uruchomione."
        SELECT="Wybór"
        TINT_CONF_FILE="plik konfiguracji tint2"
    ;;
    *)
        TITLE="Tint2 Manager"
        CANCEL="--button=gtk-cancel:1"
        SELECT_TINT="Select Tint2s from the list:"
        SELECT="Select"
        TINT_CONF_FILE="tint2 Name"
;;
esac
########################################################################

tintRunning(){
    # make blank tempfile, to save running tint2 paths
    TEMPFILE=$(mktemp --tmpdir tint2.XXXX)
    pgrep -a tint2 | while read pid cmd; do 
        if [[ ${cmd%% *} = tint2 ]]; then
            TPATH=$(echo $cmd | awk '{print $NF}')
            echo $TPATH >> $TEMPFILE
        fi     
    done
}

fillArrays(){
    num="$1"
    tintsPath[$num]="$2"   # full filepath to the tint2
    tintsArr[$num]="$3"    # displayed name
    # see if name matches one of the running tints
    if grep -qx "$2" "$TEMPFILE";then # if tint2 is running (read from tempfile)
        checkArr[$num]="TRUE"       # make checkmark in dialog
    else
        checkArr[$num]="FALSE"
    fi
}

findTint(){
# search dirs for tint2 config files
    num=0
    for x in $(find $TINT2PATH -type f );do
        # check if likely tint2 config file
        pm=$(grep  "panel_monitor" "$x")
        if [[ $pm ]];then
            TINT2=$( echo $x | awk -F"/" '{print $(NF-1)"/"$NF}')
            fillArrays $num $x $TINT2
            num=$(($num+1))
        fi
    done
}

# get any commandline arguments
if ! (( $# == 0 ));then    
    for arg in "$@";do
        if [[ $1 = "-h" ]] || [[ $1 = "--help" ]];then
            echo -e "$USAGE"
            exit 0
        else
            echo -e "\tERROR: sorry I don't understand the input"
            echo -e "$USAGE"
            exit 0
        fi
    done
fi
# get tint2 directories in .tint2, add to array
tintRunning
findTint

# loop through arrays, and build msg text for yad dialog
unset LISTTINT
for ((j=0; j<${#tintsArr[*]}; j++));do
    LISTTINT="$LISTTINT ${checkArr[j]} ${tintsArr[j]}"
done

## Populate dialog from array, get return value(s)
RET=$($DLGDEC $WINICON --list --title="$TITLE" \
    --text="$SELECT_TINT" \
    --checklist --width=350 --height=300 \
    --column="$SELECT" --column="$TINT_CONF_FILE" $LISTTINT --separator=":" \
    $OK $CANCEL \
    )

if (( $? == 1 )); then # cancel button pressed
    exit 0
else
    > $SESSIONFILE    # Create new session file
    # loop through returned choices, add to array
    i=0
    OIFS=$IFS   # copy original IFS
    IFS=":"     # separator is ":" in returned choices
    for name in $RET; do 
        retTint[$i]=$name
        i=$(($i+1))
    done
    IFS=$OIFS    # reset IFS
    
    # kill all tint2s
    pgrep -a tint2 | while read pid cmd; do 
        if [[ ${cmd%% *} = tint2 ]]; then
            kill "$pid"
        fi     
    done
    
    for name in ${retTint[*]};do       # loop through checkmarked tint2 names
        for ((j=0; j<${#tintsPath[*]}; j++));do  # traverse through elements
            for f in ${tintsPath[j]};do
                display=$( echo $f | awk -F"/" '{print $(NF-1)"/"$NF}')
                path=$( echo $f | awk -F"/" '{print "/"$(NF-2)"/"$(NF-1)"/"$NF}')
                # see if it matches the returned name
                if [[ $display = $name ]];then
                    #DEBUG
                    #echo "mb-tint2zen: path=$path" >> $DEBUGFILE
                    #echo "mb-tint2zen: f=$f" >> $DEBUGFILE
                    #DEBUG_KONIEC
                    echo -e "$path" >> $SESSIONFILE
                    tint2 -c "$f" &  #start the tint2
                    sleep 1s
                fi
            done
        done
    done
    mabox-compositor --restart &   # restart compositor 
fi

rm -r $TEMPFILE

exit 0