summaryrefslogtreecommitdiff
blob: c1ff6a40ede3928cd0e17fa0dfd02a743544ab15 (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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
# Copyright 1999-2023 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2
# shellcheck shell=sh disable=3043

# shellcheck disable=2034
RC_GOT_FUNCTIONS="yes"

#
#    This is a private function, called by ebegin, eerrorn, einfon, and ewarnn.
#
_eprint() {
	local color
	color=$1
	shift

	if [ -z "${genfun_endcol}" ] && [ "${genfun_lastcall}" = "ebegin" ]; then
		printf '\n'
	fi
	printf ' %s*%s %s%b' "${color}" "${NORMAL}" "${genfun_indent}" "$*"
}

#
#    hard set the indent used for e-commands.
#    num defaults to 0
# This is a private function.
#
_esetdent()
{
	if ! is_int "$1" || [ "$1" -lt 0 ]; then
		set -- 0
	fi
	genfun_indent=$(printf "%${1}s" '')
}

#
#    increase the indent used for e-commands.
#
eindent()
{
	if ! is_int "$1" || [ "$1" -le 0 ]; then
		set -- 2
	fi
	_esetdent "$(( ${#genfun_indent} + $1 ))"
}

#
#    decrease the indent used for e-commands.
#
eoutdent()
{
	if ! is_int "$1" || [ "$1" -le 0 ]; then
		set -- 2
	fi
	_esetdent "$(( ${#genfun_indent} - $1 ))"
}

#
# this function was lifted from OpenRC. It returns 0 if the argument  or
# the value of the argument is "yes", "true", "on", or "1" or 1
# otherwise.
#
yesno()
{
	for _ in 1 2; do
		case $1 in
			[Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0|'')
				return 1
				;;
			[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
				return 0
		esac
		if [ "$_" -gt 1 ]; then
			! break
		else
			# Using eval can be very dangerous. Check whether the
			# value is a legitimate variable name before proceeding
			# to treat it as one.
			(
				LC_ALL=C
				case $1 in
					''|_|[[:digit:]]*|*[!_[:alnum:]]*) exit 1
				esac
			) || ! break
			# Treat the value as a nameref then try again.
			eval "set -- \"\$$1\""
		fi
	done || vewarn "Invalid argument given to yesno (expected a boolean-like or a legal name)"
	return 1
}

#
#    use the system logger to log a message
#
esyslog()
{
	local pri tag msg

	if [ "$#" -lt 2 ]; then
		printf 'Too few arguments for esyslog (got %d, expected at least 2)\n' "$#" >&2
		return 1
	elif [ -n "${EINFO_LOG}" ] && hash logger 2>/dev/null; then
		pri=$1
		tag=$2
		shift 2
		msg=$*
		if _is_visible "${msg}"; then
			# This is not strictly portable because POSIX defines
			# no options whatsoever for logger(1).
			logger -p "${pri}" -t "${tag}" -- "${msg}"
		fi
	fi
}

#
#    show an informative message (without a newline)
#
einfon()
{
	if ! yesno "${EINFO_QUIET}"; then
		_eprint "${GOOD}" "$@"
		genfun_lastcall="einfon"
	fi
}

#
#    show an informative message (with a newline)
#
einfo()
{
	einfon "$*\\n"
	genfun_lastcall="einfo"
}

#
#    show a warning message (without a newline) and log it
#
ewarnn()
{
	if ! yesno "${EINFO_QUIET}"; then
		_eprint "${WARN}" "$@" >&2
		esyslog "daemon.warning" "${0##*/}" "$@"
		genfun_lastcall="ewarnn"
	fi
}

#
#    show a warning message (with a newline) and log it
#
ewarn()
{
	ewarnn "$*\\n"
	genfun_lastcall="ewarn"
}

#
#    show an error message (without a newline) and log it
#
eerrorn()
{
	if ! yesno "${EERROR_QUIET}"; then
		_eprint "${BAD}" "$@" >&2
		esyslog "daemon.err" "${0##*/}" "$@"
		genfun_lastcall="eerrorn"
	fi
	return 1
}

#
#    show an error message (with a newline) and log it
#
eerror()
{
	eerrorn "$*\\n"
	genfun_lastcall="eerror"
	return 1
}

#
#    show a message indicating the start of a process
#
ebegin()
{
	local msg

	if ! yesno "${EINFO_QUIET}"; then
		msg="$* ..."
		_eprint "${GOOD}" "${msg}"
		if [ -n "${genfun_endcol}" ]; then
			printf '\n'
		fi
		genfun_lastbegun_strlen="$(( 3 + ${#genfun_indent} + ${#msg} ))"
		genfun_lastcall="ebegin"
	fi
}

#
#    indicate the completion of process, called from eend/ewend
#    if error, show errstr via efunc
#
#    This function is private to functions.sh.  Do not call it from a
#    script.
#
_eend()
{
	local efunc msg retval

	efunc=$1
	shift
	if [ "$#" -eq 0 ]; then
		retval=0
	elif ! is_int "$1" || [ "$1" -lt 0 ]; then
		printf 'Invalid argument given to %s (the exit status code must be an integer >= 0)\n' "${CALLER}" >&2
		retval=0
		shift
	else
		retval=$1
		shift
	fi

	if [ "${retval}" -ne 0 ]; then
		if _is_visible "$*"; then
			"${efunc}" "$*"
		fi
		msg="${BRACKET}[ ${BAD}!!${BRACKET} ]${NORMAL}"
	elif yesno "${EINFO_QUIET}"; then
		return "${retval}"
	else
		msg="${BRACKET}[ ${GOOD}ok${BRACKET} ]${NORMAL}"
	fi

	if [ -n "${genfun_endcol}" ]; then
		printf "${genfun_endcol}  ${msg}\n"
	else
		[ "${genfun_lastcall}" = ebegin ] || genfun_lastbegun_strlen=0
		printf "%$(( genfun_cols - genfun_lastbegun_strlen - 6 ))s%b\n" '' "${msg}"
	fi

	return "${retval}"
}

#
#    indicate the completion of process
#    if error, show errstr via eerror
#
eend()
{
	local retval

	CALLER=${CALLER:-eend} _eend eerror "$@"
	retval=$?
	genfun_lastcall="eend"
	return "${retval}"
}

#
#    indicate the completion of process
#    if error, show errstr via ewarn
#
ewend()
{
	local retval

	CALLER=${CALLER:-ewend} _eend ewarn "$@"
	retval=$?
	genfun_lastcall="ewend"
	return "${retval}"
}

# v-e-commands honor EINFO_VERBOSE which defaults to no.
veinfo()
{
	if yesno "${EINFO_VERBOSE}"; then
		einfo "$@"
	fi
}

veinfon()
{
	if yesno "${EINFO_VERBOSE}"; then
		einfon "$@"
	fi
}

vewarn()
{
	if yesno "${EINFO_VERBOSE}"; then
		ewarn "$@"
	fi
}

veerror()
{
	if yesno "${EINFO_VERBOSE}"; then
		eerror "$@"
	fi
}

vebegin()
{
	if yesno "${EINFO_VERBOSE}"; then
		ebegin "$@"
	fi
}

veend()
{
	if yesno "${EINFO_VERBOSE}"; then
		CALLER=veend eend "$@"
	elif [ "$#" -gt 0 ] && { ! is_int "$1" || [ "$1" -lt 0 ]; }; then
		printf 'Invalid argument given to veend (the exit status code must be an integer >= 0)\n' >&2
	else
		return "$1"
	fi
}

vewend()
{
	if yesno "${EINFO_VERBOSE}"; then
		CALLER=vewend ewend "$@"
	elif [ "$#" -gt 0 ] && { ! is_int "$1" || [ "$1" -lt 0 ]; }; then
		printf 'Invalid argument given to vewend (the exit status code must be an integer >= 0)\n' >&2
	else
		return "$1"
	fi
}

veindent()
{
	if yesno "${EINFO_VERBOSE}"; then
		eindent "$@"
	fi
}

veoutdent()
{
	if yesno "${EINFO_VERBOSE}"; then
		eoutdent "$@"
	fi
}

#
#   return 0 if gentoo=param was passed to the kernel
#
#   EXAMPLE:  if get_bootparam "nodevfs" ; then ....
#
get_bootparam()
(
	# Gentoo cmdline parameters are comma-delimited, so a search
	# string containing a comma must not be allowed to match.
	# Similarly, the empty string must not be allowed to match.
	case $1 in ''|*,*) return 1 ;; esac

	if [ "${TEST_GENFUNCS}" = 1 ]; then
		read -r cmdline
	else
		read -r cmdline < /proc/cmdline
	fi || return

	# Disable pathname expansion. The definition of this function
	# is a compound command that incurs a subshell. Therefore, the
	# prior state of the option does not need to be recalled.
	set -f
	for opt in ${cmdline}; do
		gentoo_opt=${opt#gentoo=}
		if [ "${opt}" != "${gentoo_opt}" ]; then
			case ,${gentoo_opt}, in
				*,"$1",*) return 0
			esac
		fi
	done
	return 1
)

#
#   return 0 if any of the files/dirs are newer than
#   the reference file
#
#   EXAMPLE: if is_older_than a.out *.o ; then ...
is_older_than()
{
	local ref has_gfind

	if [ "$#" -lt 2 ]; then
		printf 'Too few arguments for is_older_than (got %d, expected at least 2)\n' "$#" >&2
		return 1
	elif [ -e "$1" ]; then
		ref=$1
	else
		ref=
	fi
	shift

	# Consult the hash table in the present shell, prior to forking.
	hash gfind 2>/dev/null; has_gfind=$(( $? == 0 ))

	for path; do
		if [ -e "${path}" ]; then
			printf '%s\0' "${path}"
		fi
	done |
	{
		set -- -L -files0-from - ${ref:+-newermm} ${ref:+"${ref}"} -printf '\n' -quit
		if [ "${has_gfind}" -eq 1 ]; then
			gfind "$@"
		else
			find "$@"
		fi
	} |
	read -r _
}

#
#   Determine whether the first operand is in the form of an integer. A leading
#   <hypen-minus> shall be permitted. Thereafter, leading zeroes shall not be
#   permitted because the string might later be considered to be octal in an
#   arithmetic context, causing the shell to exit if the number be invalid.
#
is_int() {
	set -- "${1#-}"
	case $1 in
		''|*[!0123456789]*)
			false
			;;
		0)
			true
			;;
		*)
			test "$1" = "${1#0}"
	esac
}

#
#   Determine whether the first operand contains any visible characters. This
#   is intended to be a private function.
#
_is_visible() {
	! case $1 in *[[:graph:]]*) false ;; esac
}

# This is the main script, please add all functions above this point!

# Dont output to stdout?
EINFO_QUIET="${EINFO_QUIET:-no}"
EINFO_VERBOSE="${EINFO_VERBOSE:-no}"

# Should we use color?
RC_NOCOLOR="${RC_NOCOLOR:-no}"

# Can the terminal handle endcols? Begin by assuming not.
unset -v genfun_endcol

# Set the initial value for e-message indentation.
genfun_indent=

# If either STDOUT or STDERR is not a tty, disable coloured output. A useful
# improvement for  the future would be to have the individual logging functions
# act as they should. For example, ewarn prints to STDOUT whereas eerror prints
# to STDERR. For now, this is a reasonable compromise.
if [ ! -t 1 ] || [ ! -t 2 ]; then
	RC_NOCOLOR="yes"
	genfun_endcol=
fi

for arg in "$@" ; do
	case "${arg}" in
		# Lastly check if the user disabled it with --nocolor argument
		--nocolor|--nocolour|-nc|-C)
			RC_NOCOLOR="yes"
			break
			;;
	esac
done

# Define genfun_cols and genfun_endcol so that eend can line up the [ ok ].
# shellcheck disable=3044
if [ -n "${BASH}" ] && shopt -s checkwinsize 2>/dev/null; then
	# As is documented, running an external command will cause bash to set
	# the COLUMNS variable. This technique is effective for >=4.3, though
	# it requires for the checkwinsize shopt to be enabled. By default, it
	# is only enabled for >=5.0.
	/bin/true
fi
if is_int "${COLUMNS}" && [ "${COLUMNS}" -gt 0 ]; then
	# The value of COLUMNS was likely set by a shell such as bash or mksh.
	genfun_cols=${COLUMNS}
else
	# Try to use stty(1) to determine the number of columns. The use of the
	# size operand is not portable.
	genfun_cols=$(
		stty size 2>/dev/null | {
			if read -r _ cols _; then
				printf '%s\n' "${cols}"
			fi
		}
	)
	if ! is_int "${genfun_cols}" || [ "${genfun_cols}" -le 0 ]; then
		# Give up and assume 80 available columns.
		genfun_cols=80
	fi
fi

if [ -z "${genfun_endcol+set}" ]; then
	if hash tput 2>/dev/null; then
		genfun_endcol="$(tput cuu1)$(tput cuf $(( genfun_cols - 8 )) )"
	else
		genfun_endcol='\033[A\033['$(( genfun_cols - 8 ))'C'
	fi
fi

# Setup the colors so our messages all look pretty
if yesno "${RC_NOCOLOR}"; then
	unset -v BAD BRACKET GOOD HILITE NORMAL WARN
elif { hash tput && tput colors >/dev/null; } 2>/dev/null; then
	genfun_bold=$(tput bold) genfun_norm=$(tput sgr0)
	BAD="${genfun_norm}${genfun_bold}$(tput setaf 1)"
	BRACKET="${genfun_norm}${genfun_bold}$(tput setaf 4)"
	GOOD="${genfun_norm}${genfun_bold}$(tput setaf 2)"
	HILITE="${genfun_norm}${genfun_bold}$(tput setaf 6)"
	NORMAL="${genfun_norm}"
	WARN="${genfun_norm}${genfun_bold}$(tput setaf 3)"
	unset -v genfun_bold genfun_norm
else
	BAD=$(printf '\033[31;01m')
	BRACKET=$(printf '\033[34;01m')
	GOOD=$(printf '\033[32;01m')
	HILITE=$(printf '\033[36;01m')
	NORMAL=$(printf '\033[0m')
	WARN=$(printf '\033[33;01m')
fi

# vim:ts=4