#!/usr/bin/env bash
# A simple powermenu listing.
# Uses bemenu to display the powermenu on X11, Wayland and terminal.

#### Environment Variable Options ###
#  Interface options
# POWERMENU_SHOW_ICONS=1
# POWERMENU_SHOW_TEXT=1
# POWERMENU_SHOW_UPTIME=1
#  Command options
# POWERMENU_SHUTDOWN_CMD=""
# POWERMENU_REBOOT_CMD=""
# POWERMENU_LOCKSCREEN_CMD=""
# POWERMENU_LOGOUT_CMD=""
# POWERMENU_SUSPEND_CMD=""
#  Command chooser options
# POWERMENU_PICKER_CMD=""
# POWERMENU_PICKER_OPTS=""

#### Menu Options ###
if [ "${POWERMENU_SHOW_TEXT:-0}" -eq 0 ] && [ "${POWERMENU_SHOW_ICONS:-1}" -eq 0 ]; then
    echo "You disabled both text and icons for rofi-powermenu, nothing can be shown."
    exit 1
elif [ "${POWERMENU_SHOW_ICONS:-1}" -eq 1 ]; then
    power_off_btn=""
    reboot_btn=""
    lock_btn=""
    suspend_btn="鈴"
    logout_btn=""
fi
if [ "${POWERMENU_SHOW_TEXT:-1}" -eq 1 ]; then
    power_off_btn="${power_off_btn} Shut Down"
    reboot_btn="${reboot_btn} Restart"
    lock_btn="${lock_btn} Lock Screen"
    suspend_btn="${suspend_btn} Suspend"
    logout_btn="${logout_btn} Log Out"
fi

## SET PROMPT
if [ "${POWERMENU_SHOW_UPTIME:-1}" -eq 1 ]; then
    prompt="Uptime $(uptime -p | sed -e 's/up //g') >"
else
    prompt="Power >"
fi

selector_program="${POWERMENU_PICKER_CMD:-bemenu}"
selector_opts="${POWERMENU_PICKER_OPTS:--i}"

menu=$(printf "%s\n" "$lock_btn" "$suspend_btn" "$power_off_btn" "$reboot_btn" "$logout_btn")
# shellcheck disable=SC2086
result=$(printf "%s" "$menu" | $selector_program $selector_opts --prompt "$prompt")

# grep -a since it assumes with our nullcodes etc that this is a binary file
# grep -o to only leave the things we grep for
case "$result" in
"Shutdown" | "$power_off_btn")
    if [ -n "$POWERMENU_SHUTDOWN_CMD" ]; then eval "$POWERMENU_SHUTDOWN_CMD"; else
        systemctl poweroff
    fi
    ;;
"Reboot" | "$reboot_btn")
    if [ -n "$POWERMENU_REBOOT_CMD" ]; then eval "$POWERMENU_REBOOT_CMD"; else
        systemctl reboot
    fi
    ;;
"Lockscreen" | "$lock_btn")
    # Completely detach from the parent script
    # If in/outputs are not redirected, rofi will wait for the forked process as well.
    if [ -n "$POWERMENU_LOCKSCREEN_CMD" ]; then eval "$POWERMENU_LOCKSCREEN_CMD"; else
        lockscreen
    fi
    ;;
"Logout" | "$logout_btn")
    if [ -n "$POWERMENU_LOGOUT_CMD" ]; then eval "$POWERMENU_LOGOUT_CMD"; else
        command -v i3 >/dev/null 2>&1 && i3-msg exit
        command -v riverctl >/dev/null 2>&1 && riverctl exit
    fi
    ;;
"Suspend" | "$suspend_btn")
    if [ -n "$POWERMENU_SUSPEND_CMD" ]; then eval "$POWERMENU_SUSPEND_CMD"; else
        systemctl hibernate
    fi
    ;;
esac
