Created
July 11, 2022 09:52
-
-
Save koonix/ee35768bedefbedb7f8c6cd4e8dcb381 to your computer and use it in GitHub Desktop.
a dmenu wrapper script for system functions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# a dmenu wrapper script for system functions. | |
actions=( | |
'鈴 Sleep' | |
'鈴 Hibernate' | |
'⏻ Poweroff' | |
' Reboot' | |
' Logout' | |
) | |
# the -shb and -shf dmenu color options require dmenu's fuzzyhighlight patch. | |
colors='-sb #42214d' | |
main() | |
{ | |
set -e | |
noconfirm=false | |
case $1 in | |
-n|--noconfirm) noconfirm=true; shift ;; | |
esac | |
action=${1,,} | |
[[ -z $1 ]] && action=$( | |
printf '%s\n' "${actions[@]}" | dmenu -p 'System Action:' $colors | |
) | |
ctl=$(get_ctl_cmd) | |
case $action in | |
*' Logout'|logout) | |
ask 'Logout?' && | |
kill "$(pstree -ps $$ | grep -Po 'xinit\(\K\d+')" | |
;; | |
*' Sleep'|sleep|suspend) | |
"$ctl" suspend"$(can_hibernate && echo -then-hibernate)" | |
;; | |
*' Poweroff'|poweroff|shutdown) | |
ask 'Poweroff?' && | |
"$ctl" poweroff | |
;; | |
*' Reboot'|reboot) | |
os=$(ask_reboot_os) | |
ask 'Reboot?' || return 1 | |
[[ -n $os ]] && sudo -A grub-reboot "$os" | |
"$ctl" reboot | |
;; | |
*' Hibernate'|hibernate) | |
if can_hibernate; then | |
ask 'Hibernate?' && "$ctl" hibernate | |
else | |
msg='Hibernation is not enabled on this machine.' | |
echo "$msg" >&2 | |
notify-send "$msg" | |
fi | |
;; | |
esac | |
} | |
ask_reboot_os() | |
{ | |
command -v grub-reboot >/dev/null || return 1 | |
command -v grub-entries >/dev/null || return 1 | |
entries=$(sudo -A grub-entries -g) || return 1 | |
readarray -t entries <<< "$entries" | |
[[ ${#entries[@]} -le 1 ]] && return 0 | |
sel=$(printf '%s\n' "${entries[@]}" | dmenu -p 'Reboot to:' $colors) || return 1 | |
echo "${sel#* }" | |
} | |
ask() | |
{ | |
[[ $noconfirm = true ]] && return 0 | |
ans=$(printf 'No\nYes\n' | dmenu -p "$*" \ | |
-nb darkred -nhb darkred -nf darkgray -nhf darkgray \ | |
-sb maroon -shb maroon -sf white -shf orange) | |
[[ $ans = Yes ]] && return 0 || return 1 | |
} | |
can_hibernate() | |
{ | |
local file=/sys/power/resume | |
[[ -f $file ]] && [[ $(<"$file") != 0:0 ]] | |
} | |
get_ctl_cmd() | |
{ | |
case $(readlink -f /sbin/init) in | |
*systemd*) echo systemctl ;; | |
*) echo loginctl ;; | |
esac | |
} | |
main "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment