POWER_OFF=" Power Off"
REBOOT=" Reboot"
SUSPEND=" Suspend"
LOCK=" Lock"
LOG_OUT="󰗽 Log out"

chosen=`printf "%s\n%s\n%s\n%s\n%s" "$POWER_OFF" "$REBOOT" "$SUSPEND" "$LOCK" "$LOG_OUT" | rofi -dmenu -i -p ""`

case "$chosen" in
	$POWER_OFF) action="power off" ;;
	$REBOOT) action="reboot" ;;
	$SUSPEND) action="suspend" ;;
	$LOCK) action="lock" ;;
	$LOG_OUT) action="log out" ;;
	*) exit 1 ;;
esac

confirm=`printf "Yes, %s" "$action"`
sure=`printf "%s\nNo, cancel" "$confirm" | rofi -dmenu -i -p "Are you sure"`

if [[ $sure != $confirm ]]; then
	exit 1
fi

if [[ $chosen != $SUSPEND ]] && [[ $chosen != $LOCK ]]; then
	# based on https://github.com/ardadem/graceful-shutdown

	TIMEOUT=10

	APPLIST_TO_TERMINATE=(Discord firefox)

	close_windows () {
		wmctrl -l | awk '{print $1}' | while read -r wId
		do
			wmctrl -i -c $wId
		done
	}

	window_timeout_countdown () {
		for i in $(seq 1 $TIMEOUT);
		do
			if [[ -z $(wmctrl -l) ]]; then
				return 0
			fi
			sleep 1
		done
		exit 1
	}

	terminate_processes () {
		pidof ${APPLIST_TO_TERMINATE[@]} | tr ' ' '\n' | while read -r pId
		do
			kill -15 $pId
			tail --pid=$pId -f /dev/null # wait until terminate it
		done
	}

	close_windows
	window_timeout_countdown
	terminate_processes
fi

case "$chosen" in
	$POWER_OFF) poweroff ;;
	$REBOOT) reboot ;;
	$SUSPEND) dm-tool switch-to-greeter && systemctl suspend ;;
	$LOCK) dm-tool lock ;;
	$LOG_OUT) i3-msg exit ;;
	*) exit 1 ;;
esac
