aboutsummaryrefslogtreecommitdiff
path: root/lib/subcommands/add.bash
blob: 644c04f32f40d4457567280b252d20190e75135d (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
#!/usr/bin/env bash

# SPDX-FileCopyrightText: 2023 Patrick Spek <p.spek@tyil.nl>
#
# SPDX-License-Identifier: AGPL-3.0-or-later

subcommand()
{
	local buffer
	local missing_vars=0

	export BASHTARD_PLAYBOOK="$1" ; shift

	if [[ -z "$BASHTARD_PLAYBOOK" ]]
	then
		crit "bashtard/add" "No playbook name specified"
		return 2
	fi

	local playbook_base="$(playbook_path "base")"
	local playbook_registry="$BASHTARD_ETCDIR/registry.d/${BASHTARD_PLATFORM[fqdn]}"

	# Make sure we only run add if the playbook is not in the registry yet
	if grep -Fqx "$BASHTARD_PLAYBOOK" "$playbook_registry"
	then
		crit "bashtard/add" "'$BASHTARD_PLAYBOOK' is already registered for ${BASHTARD_PLATFORM[fqdn]}"
		return 3
	fi

	notice "bashtard/add" "Adding playbook '$BASHTARD_PLAYBOOK' to '${BASHTARD_PLATFORM[fqdn]}'"

	if [[ ! -d "$playbook_base" ]]
	then
		emerg "bashtard/add" "No such directory: $playbook_base"
		return 1
	fi

	if [[ ! -f "$playbook_base/playbook.bash" ]]
	then
		emerg "bashtard/add" "No such file: $playbook_base/playbook.bash"
		return 1
	fi

	# shellcheck disable=SC1090,SC1091
	. "$playbook_base/playbook.bash"

	# Ensure all required vars are non-empty
	debug "bashtard/add" "Checking for \$BASHTARD_PLAYBOOK_VARS"

	for key in "${!BASHTARD_PLAYBOOK_VARS[@]}"
	do
		# shellcheck disable=SC2086
		in_args "required" ${BASHTARD_PLAYBOOK_VARS[$key]} || continue

		debug "bashtard/add" "Checking \$BASHTARD_PLAYBOOK_VARS[$key]"

		if [[ "$(config "$key")" == "" ]]
		then
			missing_vars=$(( missing_vars + 1))
		fi
	done

	if (( 0 < missing_vars ))
	then
		emerg "bashtard/add" "One or more required variables are unset"
		return 3
	fi

	# Run the playbook
	if ! playbook_add
	then
		crit "bashtard/add" "$BASHTARD_PLAYBOOK reported an error"
		return 1
	fi

	buffer="$(tmpfile)"

	# Add the playbook to the registry
	cp -- "$playbook_registry" "$buffer"
	printf -- "%s\n" "$BASHTARD_PLAYBOOK" >> "$buffer"
	sort -- "$buffer" > "$playbook_registry"
}