aboutsummaryrefslogtreecommitdiff
path: root/lib/util/config.bash
blob: 7918a1e022e626326e112aac738213c565d694f4 (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
#!/usr/bin/env bash

# Read a particular value from a key/value configuration file. Using this
# function introduces a dependency on awk.
config() {
	config_for "${BASHTARD_PLATFORM[fqdn]}" "$@"
}

config_for() {
	local host=$1 ; shift
	local key=$1 ; shift
	local default=$1 ; shift

	local default
	local file
	local files

	files=(
		"$BASHTARD_ETCDIR/secrets"
		"$BASHTARD_ETCDIR/hosts.d/$host"
		"$BASHTARD_ETCDIR/os.d/${BASHTARD_PLATFORM[key]}"
		"$BASHTARD_ETCDIR/defaults"
	)

	if [[ -n "$BASHTARD_PLAYBOOK" ]]
	then
		debug "bashtard/config_for" "BASHTARD_PLAYBOOK=$BASHTARD_PLAYBOOK, adding etc entries"
		files+=(
			"$BASHTARD_ETCDIR/playbooks.d/$BASHTARD_PLAYBOOK/etc/os.d/${BASHTARD_PLATFORM[key]}"
			"$BASHTARD_ETCDIR/playbooks.d/$BASHTARD_PLAYBOOK/etc/defaults"
		)
	fi

	files+=(
		"$BASHTARD_SHAREDIR/os.d/${BASHTARD_PLATFORM[key]}"
		"$BASHTARD_SHAREDIR/defaults"
	)

	# Check configuration files
	for file in "${files[@]}"
	do
		debug "bashtard/config_for" "Checking for '$key' in '$file'"

		[[ ! -f $file ]] && continue

		value="$(awk -F= '$1 == "'"$key"'" { print $NF }' "$file")"

		if [[ -n $value ]]
		then
			debug "bashtard/config_for" "Found $key=$value in $file"

			printf "%s" "$value"
			return
		fi
	done

	# Return default value
	if [[ -n $default ]]
	then
		printf "%s" "$default"
		return
	fi

	# Error
	alert "bashtard/config_for" "No configuration value for $key"
}