aboutsummaryrefslogtreecommitdiff
path: root/.local/share/wrapper.sh
blob: 3c6462044ef8041e91781693ef2ec9c15d3a3270 (plain)
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
94
95
96
97
98
99
100
101
102
103
104
105
#!/bin/sh

# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.

main()
{
	WRAPPER_BINS_NORMALIZED="$(mktemp)"
	WRAPPER_ETCFILE="$HOME/.local/etc/wrapper.d/${0##*/}.rc"

	if [ ! -f "$WRAPPER_ETCFILE" ]
	then
		printf "No configuration for %s found at %s\n" \
			"${0##*/}" \
			"$WRAPPER_ETCFILE" \
			>&2

		exit 3
	fi

	# shellcheck disable=SC1090
	. "$WRAPPER_ETCFILE"

	# Turn all WRAPPER_BINS entries into full paths
	for bin in ${WRAPPER_BINS:-${0##*/}}
	do
		case "$bin" in
			./*|/*)
				printf "%s\n" "$bin"
				;;
			*)
				printf "%s" "$PATH" | sed 's/:/\n/g' | while read -r path
				do
					full_path="$(printf "%s/%s\n" "$path" "$bin")"

					# Filter out any paths that refer to
					# the wrapper script itself. This
					# should ensure it won't call itself
					# into perpetuity.
					if [ "$full_path" = "$0" ]
					then
						continue
					fi

					printf "%s\n" "$full_path"
				done
		esac
	done > "$WRAPPER_BINS_NORMALIZED"

	# Clear some stray variables
	unset bin
	unset full_path
	unset path

	# Loop over all possible wrapped options, and run the first one that is
	# executable
	while read -r WRAPPER_CMD
	do
		[ -x "$WRAPPER_CMD" ] || continue

		# Add a firejail wrapper if desired
		if [ -n "$FIREJAIL_PROFILE" ]
		then
			WRAPPER_CMD="firejail --profile=""$FIREJAIL_PROFILE"" -- $WRAPPER_CMD"
		fi

		# Optionally add WRAPPER_OPTS, so theres no double space in
		# case it is empty.
		if [ -n "$WRAPPER_OPTS" ]
		then
			WRAPPER_CMD="$WRAPPER_CMD $(printf "%s" "$WRAPPER_OPTS" | tr "\n" " " | awk '{$1=$1};1')"
		fi

		# Run all the things we want to run
		wrap_before
		wrap_log "> $WRAPPER_CMD $*"
		$WRAPPER_CMD "$@"
		WRAPPER_EXITCODE=$?
		wrap_after

		return $WRAPPER_EXITCODE
	done < "$WRAPPER_BINS_NORMALIZED"

	printf "No underlying executable found for %s:\n" "${0##*/}" >&2
	for bin in $WRAPPER_BINS
	do
		printf "\t%s\n" "$bin" >&2
	done
}

wrap_log() {
	printf "[%s] %s\n" "$(date -u +%FT%TZ)" "$*" >&2
}

wrap_before() { :; }
wrap_after() { :; }

main "$@"