#!/bin/sh

# A dmenu wrapper script for system functions.
export WM="dwm"
case "$(readlink -f /sbin/init)" in
	*systemd*) ctl='systemctl' ;;
	*) ctl='loginctl' ;;
esac

wmpid(){ # This function is needed if there are multiple instances of the window manager.
	tree="$(pstree -ps $$)"
	tree="${tree#*$WM(}"
	echo "${tree%%)*}"
}

lock(){
    mpc pause
    pauseallmpv
    wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle
    kill -44 $(pidof dwmblocks)
    slock
    wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle
    kill -44 $(pidof dwmblocks)
}

case "$(printf "lock\nleave $WM\nrenew $WM\nhibernate\nreboot\nshutdown\nsleep\ndisplay off" | dmenu -i -p 'Action: ')" in
	'lock') lock ;;
	"leave $WM") kill -TERM "$(wmpid)" ;;
	"renew $WM") kill -HUP "$(wmpid)" ;;
	'hibernate') slock $ctl hibernate -i ;;
	'sleep') slock $ctl suspend -i ;;
	'reboot') $ctl reboot -i ;;
	'shutdown') $ctl poweroff -i ;;
	'display off') xset dpms force off ;;
	*) exit 1 ;;
esac
