#!/bin/bash

# poweroptionsmenu --- rofi interface for session actions.
#
# Copyright (c) 2019 Protesilaos Stavrou <info@protesilaos.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Void Linux dependencies:
#     xbps-install -S rofi

# Possible actions (see case statement at the end for the actual
# commands)
actions=('Log out' 'Reboot' 'Power off' 'Xmodmap and keyboard reload' 'Configure anew BSPWM monitors/desktops')

# List actions to choose from
_list_actions() {
    # use printf to output array items on a new line
    printf '%s\n' "${actions[@]}" | rofi -dmenu -no-custom -p 'Power options'
}

choice="$(_list_actions)"

_pkill() {
    if pgrep -x "$1"; then
        pkill -x "$1"
    fi
}

_kill_processes() {
    _pkill bspwm_external_rules
    _pkill sxhkd
    _pkill melonpanel
    _pkill feh
    _pkill xcompmgr
}

# In case the Hyper key ever stops working, we can call this script
# (Ctrl+Alt+Delete on my sxhkdrc) and apply the modifications again.
_kbd_reset_and_xmodmap() {
    xmod="$HOME"/.Xmodmap

    setxkbmap -layout 'us,el' -option 'caps:hyper,compose:menu'
    [ -f "$xmod" ] && xmodmap "$xmod"
}

# Run the selected command.  The `reboot' and `poweroff' require
# escalated privilages, unless you configure things.  Read:
# https://wiki.voidlinux.org/Post_Installation#Allow_users_to_shutdown_without_a_password
case "$choice" in
    L*) _kill_processes && bspc quit ;;
    R*) _kill_processes && reboot    ;;
    P*) _kill_processes && poweroff  ;;
    X*) _kbd_reset_and_xmodmap       ;;
    C*) bspwm_conf_reset_monitors    ;;
esac
