#!/bin/bash
##
#   Read a saved BunsenLabs Tint2 session file and start the tint2s
#
#   Written by damo <damo@bunsenlabs.org> for BunsenLabs Linux, April 2015
#
#   To start the chosen Tint2 session at login, add the following line
#   to config/openbox/autostart:
#
#      (sleep 2s && mb-tint2-session) &
#
########################################################################
TINT2PATH="$HOME/.config/tint2"
SESSIONFILE="$TINT2PATH/tint2-sessionfile"
USAGE=$(
    echo -e "\vUSAGE:  with no command argument, the script uses the chosen"
    echo -e "\tTint2 session file \"$TINT2PATH/tint2-sessionfile\","
    echo -e "\tif it exists, otherwise the default tint2rc is used"
    echo -e "\v\tTo start them at login, add the following line to autostart:"
    echo -e "\v\t\t(sleep 2s && mb-tint2-session) &"
)

findArgs(){     # get command args
    for arg in "$@";do
        if [[ $1 = "-h" ]] || [[ $1 = "--help" ]];then
            echo "$USAGE"
            exit 0
        else
            echo -e "\tERROR: sorry I don't understand the input"
            echo "$USAGE"
            exit 0
        fi
    done
}

testSessionfile(){
    if test -f  "$1" &>/dev/null;then # sessionfile found
        killTints
        while read line;do
        if test -z $line &>/dev/null;then
        continue
        else
            if test -e "$HOME$line";then 
            tint2 -c "$HOME$line" &
            sleep 1s
            echo "$HOME$line" >> "$SESSIONFILE".tmp
            else
            tint2 -c "$line" &
            fi
        fi
        done < "$1"
        if test -f "$SESSIONFILE".tmp &>/dev/null;then
        cat "$SESSIONFILE".tmp > "$SESSIONFILE"
        rm "$SESSIONFILE".tmp
        fi
    else
        echo -e "Created sessionfile \"$1\"\nRunning default tint2rc" 2>&1
        echo "$HOME/.config/tint2/tint2rc" > "$SESSIONFILE"
        killTints
        tint2 -c "$TINT2PATH/tint2rc" &>/dev/null
    fi
}

killTints(){
    pgrep -a tint2 | while read pid cmd; do 
        if [[ ${cmd%% *} = tint2 ]]; then
            kill "$pid"
        fi     
    done
}

if [ $# -eq 0 ];then    # if no args, then run default sessionfile
    testSessionfile "$SESSIONFILE"
else
    findArgs "$@"
fi

# restart compositor in case of rendering problems
if pgrep picom;then mabox-compositor --restart; fi

exit 0
