#!/bin/sh
# rofi-launch drun|run|window|filebrowser|sudo (module rofi, novox/hq ADR 0208): what the launcher's
# key bindings run.
#
# After a resume the keyboard grab can fail for a moment, and rofi then exits at once: a key press
# that opens nothing. So a failure within half a second is tried again, up to five times. A person
# closing the menu takes longer than that, and is never shown it a second time.
set -u
mode=${1:-drun}

now_ms() { date +%s%3N; }

attempt() {
	i=0
	while [ "$i" -lt 5 ]; do
		start=$(now_ms)
		"$@" && return 0
		[ $(($(now_ms) - start)) -ge 500 ] && return 1
		i=$((i + 1))
		sleep 0.1
	done
	return 1
}

case $mode in
drun | run | window | filebrowser)
	attempt rofi -show "$mode"
	;;
sudo)
	# A command line, run with sudo in the node's terminal.
	command=$(attempt rofi -dmenu -p sudo </dev/null) || exit 0
	[ -n "$command" ] || exit 0
	exec rofi-sensible-terminal -e sudo sh -c "$command"
	;;
*)
	echo "rofi-launch: no mode $mode (drun, run, window, filebrowser, sudo)" >&2
	exit 2
	;;
esac
