aboutsummaryrefslogtreecommitdiff
path: root/.local/lib/cmd-wrapper/wrapper.sh
blob: de74794ac02d97f401b1c667adfc1839cffca1fc (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
#!/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.

readonly wrapper_name="${0##*/}"
readonly wrapper_data="$HOME/.local/etc/cmd-wrapper/${0##*/}"

main() {
	# Ensure there's a text file containing a list of potential binaries
	if [ ! -f "$wrapper_data/bins.txt" ]
	then
		printf "No wrapper bins for %s (%s)\n" \
			"$wrapper_name" \
			"$wrapper_data/bins.txt" \
			>&2

		exit 1
	fi

	# Source a custom environment if one exists
	if [ -f "$wrapper_data/env.sh" ]
	then
		#shellcheck disable=1090
		. "$wrapper_data/env.sh"
	fi

	# Loop through all potential binaries
	while read -r bin
	do
		# Check if this particular bin is available
		[ -x "$bin" ] || continue

		# Run the wrap_before command if specified
		if command -V "wrap_before" 2>/dev/null | head -n 1 | grep -Eq "function$"
		then
			wrap_before
		fi

		# shellcheck disable=SC2093
		wrap_cmd "$bin" "$@"
	done < "$wrapper_data/bins.txt"

	# No fitting binary found, show error
	printf "None of the underlying executables for %s exist:\n" \
		"$wrapper_name" >&2

	while read -r bin
	do
		printf "\t%s\n" "$bin" >&2
	done < "$wrapper_data/bins.txt"

	exit 1
}

# The actual running of the binary can be overriden from an env.sh, if desired.
wrap_cmd() {
	exec "$@"
}

main "$@"