summary refs log tree commit diff
path: root/bin/rcmenu
blob: c2a359d09ebcac4f7f127ffed76ab7b8f83c94cf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/bin/bash

[ -n "$DEBUG" ] && set -x
set -u

export MENU_PROMPT="󰑮 rc"
svdir=/run/s6-rc/servicedirs
rcdir=/etc/s6-rc/src
ico=/usr/share/icons/mdi/scalable/run-fast.svg
menu_exitcode=-1

__list() {
	(
		find "$svdir" -mindepth 1 -maxdepth 1 -type d -print |
			while read -r sv; do
				printf "%s " "$(basename "$sv")"
				doas -n s6-svstat "$sv"
			done
		find "$rcdir" -mindepth 1 -maxdepth 1 -type d -print |
			while read -r sv; do
				if [ -f "$sv/type" ] && grep -q bundle "$sv/type"; then
					printf "%s " "$(basename "$sv")"
					printf "[bundle] "
					printf "contents: "
					find "$sv/contents.d/" -type f -exec basename {} \; | xargs | sed 's, ,/,g'
				fi
			done
	) | column -t
}

__start() {
	local sv=$1
	export msg=$(doas -n s6-rc -v2 -u change "$sv")
	export action=start
}
__stop() {
	local sv=$1
	export msg=$(doas -n s6-rc -v2 -d change "$sv")
	export action=stopp
}
__restart() {
	local sv="$1"
	local msg
	local action

	# bemenu-ism
	# if [ $menu_exitcode -eq 18 ]; then
	if jq -ncr '{p:"rcmenu",o:[{l:"restart",x:"false"},{l:"stop",x:"true"}]}' | mkmenu; then
		__stop "$sv"
	else
		__stop "$sv" && sleep 0.5 && __start "$sv"
		action=restart
	fi

	export msg
	export action
}

__handle() {
	while read -r line; do
		sv=$(printf "%s" "${line}" | awk '{print $1}')
		state=$(printf "%s" "${line}" | awk '{print $2}')

		case "$state" in
		up | \[bundle\]) __restart "$sv" ;;
		down) __start "$sv" ;;
		*)
			action=noop
			msg=$(printf "unknown service state: %s\n" "$state")
			false
			;;
		esac

		if [ "$?" = 0 ]; then
			notify-send -i "${ico}" -a rc "${sv}" "${action}ed"
		else
			notify-send -i "${ico}" -a rc -u critical -t 30000 "${sv}" "${action}ing ${sv} failed:\n<i>${msg}</i>"
		fi
		printf "%s\n" "${msg}"
	done
}

case "${1:-}" in
-h | --help | help) printf "usage: %s [start|stop|restart] SERVICE\n" "$(basename "$0")" ;;
start) __start "$2" ;;
stop) __stop "$2" ;;
restart) __restart "$2" ;;
*)
	svs=$(__list | menu -l10)
	menu_exitcode=$?
	__handle <<<"$svs"
	;;
esac