#!/bin/bash

###################################################
## shut down pc and break instantwm restart loop ##
###################################################

# multiple instances would overlap
if ! pgrep instantshutdown | wc -l | grep -q '1'; then
    echo "instantmenu already running"
    exit
fi

answer=$(echo "cancel
shutdown
logout
reboot
lock screen
kill wm" | instantmenu -l 10 -w 400 -c -n -F -p "do you want to shut down?")

# if there are apps open, ask for confirmation
zconfirm() {
    if wmctrl -l | grep -q '..'; then
        echo "running applications found"
        if zenity --question --text="there are apps running, sure you want to $1"; then
            echo "yes"
            return 0
        else
            echo "no"
            exit
        fi
    else
        echo "no running applications found"
    fi
}

case "$answer" in
s*)
    zconfirm "shutdown"
    rm ~/.instantosrunning
    sleep 0.4
    shutdown now
    ;;
r*)
    zconfirm "reboot"
    rm ~/.instantosrunning
    sleep 0.4
    reboot
    ;;
log*)
    zconfirm "sign out"
    rm ~/.instantosrunning
    sleep 0.4
    kill -9 -1
    ;;
loc*)
    ilock
    ;;
k*)
    pkill instantwm
    ;;
*)
    echo "canceled"
    ;;
esac
