#!/usr/bin/env bash
#
# compositor: an Openbox Pipe Menu for use with picom compositor
# Copyright (C) 2012 Philip Newborough <corenominal@corenominal.org>
# Copyright (C) 2013 Aleks-Daniel Jakimenko
# Copyright (C) 2015 John Crawley <john@bunsenlabs.org>
#
# forked by manjaro <fhatmanjaroorg>
# modified for picom
#

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 PICOM_CONF="$HOME/.config/picom/picom.conf"
readonly EXECXCOMP="picom -b --config ${PICOM_CONF}"
readonly RESTART_ATTEMPTS=5
readonly HELP="
manjaro-compositor is an openbox pipe menu for use with picom
It should normally be called from an openbox menu.

Options (passed from the menu):
    -h --help   show this message
    --start     start the compositor
    --restart   restart the compositor, if running
    --stop      stop the compositor
    --edit      open the picom config file in a text editor
    --watch     restart picom when the config is modified (useful for debugging)

If manjaro-compositor is called with no options (the usual method),
it will output an xml openbox pipemenu for handling compositing.

See ~/.config/picom/picom.conf and 'man picom' for configuration options."

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

declareDependencies picom

forcekill_picom() {
    pkill picom
    for ((i=0; i<RESTART_ATTEMPTS; i++))
    do
        [[ -z $(pidof picom) ]] || break
        ## killall -q -S KILL picom
        pkill picom
        sleep 0.5
    done
}


if [[ $1 = '--edit' ]]; then # Edit picom settings
    if ! [ -e "${PICOM_CONF}" ]; then
        mkdir -p "$HOME/.config/picom"
        cp '/etc/xdg/picom.conf' "${PICOM_CONF}"
    fi
    if hash xdg-open &>/dev/null; then
        xdg-open "${PICOM_CONF}"
    elif hash exo-open &>/dev/null; then
        exo-open "${PICOM_CONF}"
    else
        "$TERMINAL" -e "$EDITOR ${PICOM_CONF}"
    fi
elif [[ $1 = '--start' ]]; then
    if ! [[ $(pidof picom) ]]; then
        $EXECXCOMP
    else
        echo "$0 --start: Compositor already running" && exit 1
    fi

elif [[ $1 = '--stop' ]]; then
    forcekill_picom

elif [[ $1 = '--restart' ]]; then
    if [[ $(pidof picom) ]]; then
        forcekill_picom
        "$0" --start
    else # nothing to restart
        echo "$0 --restart: Compositor is not running" && exit 2
    fi

elif [[ $1 = '--watch' ]]; then
    while inotifywait -e close_write "${PICOM_CONF}"; do
        "$0" --restart
    done

else
    menuStart
    if ! [[ $(pidof picom) ]]; then
        menuItem 'Enable Compositing' "$0 --start"
    else
        menuItem 'Restart Compositing' "$0 --restart"
        menuItem 'Disable Compositing' "$0 --stop"
        menuSeparator
    fi
    menuItem 'Edit Compositor Config' "$0 --edit"
    menuEnd
fi

exit 0
