summaryrefslogtreecommitdiffstats
path: root/plugins-scripts/utils.sh.in
blob: 031c035780e9dca91ecba3522fda8cd8895e9be6 (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
106
107
108
109
110
111
#! /bin/sh

STATE_OK=0
STATE_WARNING=1
STATE_CRITICAL=2
STATE_UNKNOWN=3
STATE_DEPENDENT=4

print_revision() {
	echo "$1 v$2 (@PACKAGE@ @VERSION@)"
	printf '%b' "@WARRANTY@"
}

support() {
	printf '%b' "@SUPPORT@"
}

#
# check_range takes a value and a range string, returning successfully if an
# alert should be raised based on the range.  Range values are inclusive.
# Values may be integers or floats.
#
# Example usage:
#
# Generating an exit code of 1:
# check_range 5 2:8
#
# Generating an exit code of 0:
# check_range 1 2:8
#
check_range() {
	local v range yes no err decimal start end cmp match
	v="$1"
	range="$2"

	# whether to raise an alert or not
	yes=0
	no=1
	err=2

	# regex to match a decimal number
	decimal="-?([0-9]+\.?[0-9]*|[0-9]*\.[0-9]+)"

	# compare numbers (including decimals), returning true/false
	cmp() { awk "BEGIN{ if ($1) exit(0); exit(1)}"; }

	# returns successfully if the string in the first argument matches the
	# regex in the second
	match() { echo "$1" | grep -E -q -- "$2"; }

	# make sure value is valid
	if ! match "$v" "^$decimal$"; then
		echo "${0##*/}: check_range: invalid value" >&2
		unset -f cmp match
		return "$err"
	fi

	# make sure range is valid
	if ! match "$range" "^@?(~|$decimal)(:($decimal)?)?$"; then
		echo "${0##*/}: check_range: invalid range" >&2
		unset -f cmp match
		return "$err"
	fi

	# check for leading @ char, which negates the range
	if match $range '^@'; then
		range=${range#@}
		yes=1
		no=0
	fi

	# parse the range string
	if ! match "$range" ':'; then
		start=0
		end="$range"
	else
		start="${range%%:*}"
		end="${range#*:}"
	fi

	# do the comparison, taking positive ("") and negative infinity ("~")
	# into account
	if [ "$start" != "~" ] && [ "$end" != "" ]; then
		if cmp "$start <= $v" && cmp "$v <= $end"; then
			unset -f cmp match
			return "$no"
		else
			unset -f cmp match
			return "$yes"
		fi
	elif [ "$start" != "~" ] && [ "$end" = "" ]; then
		if cmp "$start <= $v"; then
			unset -f cmp match
			return "$no"
		else
			unset -f cmp match
			return "$yes"
		fi
	elif [ "$start" = "~" ] && [ "$end" != "" ]; then
		if cmp "$v <= $end"; then
			unset -f cmp match
			return "$no"
		else
			unset -f cmp match
			return "$yes"
		fi
	else
		unset -f cmp match
		return "$no"
	fi
}