xref: /freebsd/usr.sbin/bsdconfig/share/common.subr (revision 76c853ae6729e9f33895dbed9b3cc88632cb3af9)
1if [ ! "$_COMMON_SUBR" ]; then _COMMON_SUBR=1
2#
3# Copyright (c) 2012 Ron McDowell
4# Copyright (c) 2012-2013 Devin Teske
5# All rights reserved.
6#
7# Redistribution and use in source and binary forms, with or without
8# modification, are permitted provided that the following conditions
9# are met:
10# 1. Redistributions of source code must retain the above copyright
11#    notice, this list of conditions and the following disclaimer.
12# 2. Redistributions in binary form must reproduce the above copyright
13#    notice, this list of conditions and the following disclaimer in the
14#    documentation and/or other materials provided with the distribution.
15#
16# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26# SUCH DAMAGE.
27#
28# $FreeBSD$
29#
30############################################################ CONFIGURATION
31
32#
33# Default file descriptors to link to stdout/stderr for passthru allowing
34# redirection within a sub-shell to bypass directly to the terminal.
35#
36: ${TERMINAL_STDOUT_PASSTHRU:=3}}
37: ${TERMINAL_STDERR_PASSTHRU:=4}}
38
39############################################################ GLOBALS
40
41#
42# Program name
43#
44pgm="${0##*/}"
45
46#
47# Program arguments
48#
49ARGC="$#"
50ARGV="$@"
51
52#
53# Global exit status variables
54#
55SUCCESS=0
56FAILURE=1
57
58#
59# Operating environment details
60#
61export UNAME_S="$(uname -s)" # Operating System (i.e. FreeBSD)
62export UNAME_P="$(uname -p)" # Processor Architecture (i.e. i386)
63export UNAME_R="$(uname -r)" # Release Level (i.e. X.Y-RELEASE)
64
65#
66# Default behavior is to call f_debug_init() automatically when loaded.
67#
68: ${DEBUG_SELF_INITIALIZE=1}
69
70############################################################ FUNCTIONS
71
72# f_dprintf $fmt [ $opts ... ]
73#
74# Sensible debug function. Override in ~/.bsdconfigrc if desired.
75# See /usr/share/examples/bsdconfig/bsdconfigrc for example.
76#
77# If $debug is set and non-NULL, prints DEBUG info using printf(1) syntax:
78# 	+ To $debugFile, if set and non-NULL
79# 	+ To standard output if $debugFile is either NULL or unset
80# 	+ To both if $debugFile begins with a single plus-sign (`+')
81#
82f_dprintf()
83{
84	[ "$debug" ] || return $SUCCESS
85	local fmt="$1"; shift
86	case "$debugFile" in ""|+*)
87	printf "DEBUG: $fmt${fmt:+\n}" "$@" >&${TERMINAL_STDOUT_PASSTHRU:-1}
88	esac
89	[ "${debugFile#+}" ] &&
90		printf "DEBUG: $fmt${fmt:+\n}" "$@" >> "${debugFile#+}"
91	return $SUCCESS
92}
93
94# f_debug_init
95#
96# Initialize debugging. Truncates $debugFile to zero bytes if set.
97#
98f_debug_init()
99{
100	#
101	# Process stored command-line arguments
102	#
103	set -- $ARGV
104	local OPTIND
105	while getopts dD: flag > /dev/null; do
106		case "$flag" in
107		d) debug=1;;
108		D) debugFile="$OPTARG";;
109		\?) continue;;
110		esac
111	done
112	shift $(( $OPTIND - 1 ))
113
114	#
115	# Automagically enable debugging if debugFile is set (and non-NULL)
116	#
117	[ "$debugFile" ] && { [ "${debug+set}" ] || debug=1; }
118
119	#
120	# Make debugging persistant if set
121	#
122	[ "$debug" ] && export debug
123	[ "$debugFile" ] && export debugFile
124
125	#
126	# Truncate the debug file upon. Note that we will trim a leading plus
127	# (`+') from the value of debugFile to support persistant meaning that
128	# f_dprintf() should print both to standard output and $debugFile
129	# (minus the leading plus, of course).
130	#
131	local _debug_file="${debugFile#+}"
132	if [ "$_debug_file" ]; then
133		if ( umask 022 && :> "$_debug_file" ); then
134			f_dprintf "Successfully initialized debugFile \`%s'" \
135			          "$_debug_file"
136			[ "${debug+set}" ] ||
137				debug=1 # turn debugging on if not set
138		else
139			unset debugFile
140			f_dprintf "Unable to initialize debugFile \`%s'" \
141			          "$_debug_file"
142		fi
143	fi
144}
145
146# f_err $fmt [ $opts ... ]
147#
148# Print a message to stderr (fd=2).
149#
150f_err()
151{
152	printf "$@" >&${TERMINAL_STDERR_PASSTHRU:-2}
153}
154
155# f_quietly $command [ $arguments ... ]
156#
157# Run a command quietly (quell any output to stdout or stderr)
158#
159f_quietly()
160{
161	"$@" > /dev/null 2>&1
162}
163
164# f_have $anything ...
165#
166# A wrapper to the `type' built-in. Returns true if argument is a valid shell
167# built-in, keyword, or externally-tracked binary, otherwise false.
168#
169f_have()
170{
171	f_quietly type "$@"
172}
173
174# f_getvar $var_to_get [$var_to_set]
175#
176# Utility function designed to go along with the already-builtin setvar.
177# Allows clean variable name indirection without forking or sub-shells.
178#
179# Returns error status if the requested variable ($var_to_get) is not set.
180#
181# If $var_to_set is missing or NULL, the value of $var_to_get is printed to
182# standard output for capturing in a sub-shell (which is less-recommended
183# because of performance degredation; for example, when called in a loop).
184#
185f_getvar()
186{
187	local __var_to_get="$1" __var_to_set="$2"
188	[ "$__var_to_set" ] || local value
189	eval ${__var_to_set:-value}=\"\${$__var_to_get}\"
190	eval [ \"\${$__var_to_get+set}\" ]
191	local __retval=$?
192	eval f_dprintf '"f_getvar: var=[%s] value=[%s] r=%u"' \
193		\"\$__var_to_get\" \"\$${__var_to_set:-value}\" \$__retval
194	[ "$__var_to_set" ] || { [ "$value" ] && echo "$value"; }
195	return $__retval
196}
197
198# f_die [ $status [ $fmt [ $opts ... ]]]
199#
200# Abruptly terminate due to an error optionally displaying a message in a
201# dialog box using printf(1) syntax.
202#
203f_die()
204{
205	local status=$FAILURE
206
207	# If there is at least one argument, take it as the status
208	if [ $# -gt 0 ]; then
209		status=$1
210		shift 1 # status
211	fi
212
213	# If there are still arguments left, pass them to f_show_msg
214	[ $# -gt 0 ] && f_show_msg "$@"
215
216	# Optionally call f_clean_up() function if it exists
217	f_have f_clean_up && f_clean_up
218
219	exit $status
220}
221
222# f_interrupt
223#
224# Interrupt handler.
225#
226f_interrupt()
227{
228	exec 2>&1 # fix sh(1) bug where stderr gets lost within async-trap
229	f_die
230}
231
232# f_show_info $fmt [ $opts ... ]
233#
234# Display a message in a dialog infobox using printf(1) syntax.
235#
236f_show_info()
237{
238	local msg
239	msg=$( printf "$@" )
240
241	#
242	# Use f_dialog_infobox from dialog.subr if possible, otherwise fall
243	# back to dialog(1) (without options, making it obvious when using
244	# un-aided system dialog).
245	#
246	if f_have f_dialog_info; then
247		f_dialog_info "$msg"
248	else
249		dialog --infobox "$msg" 0 0
250	fi
251}
252
253# f_show_msg $fmt [ $opts ... ]
254#
255# Display a message in a dialog box using printf(1) syntax.
256#
257f_show_msg()
258{
259	local msg
260	msg=$( printf "$@" )
261
262	#
263	# Use f_dialog_msgbox from dialog.subr if possible, otherwise fall
264	# back to dialog(1) (without options, making it obvious when using
265	# un-aided system dialog).
266	#
267	if f_have f_dialog_msgbox; then
268		f_dialog_msgbox "$msg"
269	else
270		dialog --msgbox "$msg" 0 0
271	fi
272}
273
274
275# f_yesno $fmt [ $opts ... ]
276#
277# Display a message in a dialog yes/no box using printf(1) syntax.
278#
279f_yesno()
280{
281	local msg
282	msg=$( printf "$@" )
283
284	#
285	# Use f_dialog_yesno from dialog.subr if possible, otherwise fall
286	# back to dialog(1) (without options, making it obvious when using
287	# un-aided system dialog).
288	#
289	if f_have f_dialog_yesno; then
290		f_dialog_yesno "$msg"
291	else
292		dialog --yesno "$msg" 0 0
293	fi
294}
295
296# f_noyes $fmt [ $opts ... ]
297#
298# Display a message in a dialog yes/no box using printf(1) syntax.
299# NOTE: THis is just like the f_yesno function except "No" is default.
300#
301f_noyes()
302{
303	local msg
304	msg=$( printf "$@" )
305
306	#
307	# Use f_dialog_noyes from dialog.subr if possible, otherwise fall
308	# back to dialog(1) (without options, making it obvious when using
309	# un-aided system dialog).
310	#
311	if f_have f_dialog_noyes; then
312		f_dialog_noyes "$msg"
313	else
314		dialog --defaultno --yesno "$msg" 0 0
315	fi
316}
317
318# f_show_help $file
319#
320# Display a language help-file. Automatically takes $LANG and $LC_ALL into
321# consideration when displaying $file (suffix ".$LC_ALL" or ".$LANG" will
322# automatically be added prior to loading the language help-file).
323#
324# If a language has been requested by setting either $LANG or $LC_ALL in the
325# environment and the language-specific help-file does not exist we will fall
326# back to $file without-suffix.
327#
328# If the language help-file does not exist, an error is displayed instead.
329#
330f_show_help()
331{
332	local file="$1"
333	local lang="${LANG:-$LC_ALL}"
334
335	[ -f "$file.$lang" ] && file="$file.$lang"
336
337	#
338	# Use f_dialog_textbox from dialog.subr if possible, otherwise fall
339	# back to dialog(1) (without options, making it obvious when using
340	# un-aided system dialog).
341	#
342	if f_have f_dialog_textbox; then
343		f_dialog_textbox "$file"
344	else
345		dialog --msgbox "$( cat "$file" 2>&1 )" 0 0
346	fi
347}
348
349# f_include $file
350#
351# Include a shell subroutine file.
352#
353# If the subroutine file exists but returns error status during loading, exit
354# is called and execution is prematurely terminated with the same error status.
355#
356f_include()
357{
358	local file="$1"
359	f_dprintf "f_include: file=[%s]" "$file"
360	. "$file" || exit $?
361}
362
363# f_include_lang $file
364#
365# Include a language file. Automatically takes $LANG and $LC_ALL into
366# consideration when including $file (suffix ".$LC_ALL" or ".$LANG" will
367# automatically by added prior to loading the language file).
368#
369# No error is produced if (a) a language has been requested (by setting either
370# $LANG or $LC_ALL in the environment) and (b) the language file does not
371# exist -- in which case we will fall back to loading $file without-suffix.
372#
373# If the language file exists but returns error status during loading, exit
374# is called and execution is prematurely terminated with the same error status.
375#
376f_include_lang()
377{
378	local file="$1"
379	local lang="${LANG:-$LC_ALL}"
380
381	f_dprintf "f_include_lang: file=[%s] lang=[%s]" "$file" "$lang"
382	if [ -f "$file.$lang" ]; then
383		. "$file.$lang" || exit $?
384	else
385		. "$file" || exit $?
386	fi
387}
388
389# f_usage $file [ $key1 $value1 ... ]
390#
391# Display USAGE file with optional pre-processor macro definitions. The first
392# argument is the template file containing the usage text to be displayed. If
393# $LANG or $LC_ALL (in order of preference, respectively) is set, ".encoding"
394# will automatically be appended as a suffix to the provided $file pathname.
395#
396# When processing $file, output begins at the first line containing that is
397# (a) not a comment, (b) not empty, and (c) is not pure-whitespace. All lines
398# appearing after this first-line are output, including (a) comments (b) empty
399# lines, and (c) lines that are purely whitespace-only.
400#
401# If additional arguments appear after $file, substitutions are made while
402# printing the contents of the USAGE file. The pre-processor macro syntax is in
403# the style of autoconf(1), for example:
404#
405# 	f_usage $file "FOO" "BAR"
406#
407# Will cause instances of "@FOO@" appearing in $file to be replaced with the
408# text "BAR" before bering printed to the screen.
409#
410# This function is a two-parter. Below is the awk(1) portion of the function,
411# afterward is the sh(1) function which utilizes the below awk script.
412#
413f_usage_awk='
414BEGIN { found = 0 }
415{
416	if ( !found && $0 ~ /^[[:space:]]*($|#)/ ) next
417	found = 1
418	print
419}
420'
421f_usage()
422{
423	local file="$1"
424	local lang="${LANG:-$LC_ALL}"
425
426	f_dprintf "f_usage: file=[%s] lang=[%s]" "$file" "$lang"
427
428	shift 1 # file
429
430	local usage
431	if [ -f "$file.$lang" ]; then
432		usage=$( awk "$f_usage_awk" "$file.$lang" ) || exit $FAILURE
433	else
434		usage=$( awk "$f_usage_awk" "$file" ) || exit $FAILURE
435	fi
436
437	while [ $# -gt 0 ]; do
438		local key="$1"
439		export value="$2"
440		usage=$( echo "$usage" | awk \
441			"{ gsub(/@$key@/, ENVIRON[\"value\"]); print }" )
442		shift 2
443	done
444
445	f_err "%s\n" "$usage"
446
447	exit $FAILURE
448}
449
450# f_index_file $keyword
451#
452# Process all INDEX files known to bsdconfig and return the path to first file
453# containing a menu_selection line with a keyword portion matching $keyword.
454#
455# If $LANG or $LC_ALL (in order of preference, respectively) is set,
456# "INDEX.encoding" files will be searched first.
457#
458# If no file is found, error status is returned along with the NULL string.
459#
460# This function is a two-parter. Below is the awk(1) portion of the function,
461# afterward is the sh(1) function which utilizes the below awk script.
462#
463f_index_file_awk='
464# Variables that should be defined on the invocation line:
465# 	-v keyword="keyword"
466BEGIN { found = 0 }
467( $0 ~ "^menu_selection=\"" keyword "\\|" ) {
468	print FILENAME
469	found++
470	exit
471}
472END { exit ! found }
473'
474f_index_file()
475{
476	local keyword="$1"
477	local lang="${LANG:-$LC_ALL}"
478
479	f_dprintf "f_index_file: keyword=[%s] lang=[%s]" "$keyword" "$lang"
480
481	if [ "$lang" ]; then
482		awk -v keyword="$keyword" "$f_index_file_awk" \
483			$BSDCFG_LIBE${BSDCFG_LIBE:+/}*/INDEX.$lang &&
484			return
485		# No match, fall-thru to non-i18n sources
486	fi
487	awk -v keyword="$keyword" "$f_index_file_awk" \
488		$BSDCFG_LIBE${BSDCFG_LIBE:+/}*/INDEX
489}
490
491# f_index_menusel_keyword $indexfile $pgm
492#
493# Process $indexfile and return only the keyword portion of the menu_selection
494# line with a command portion matching $pgm.
495#
496# This function is for internationalization (i18n) mapping of the on-disk
497# scriptname ($pgm) into the localized language (given language-specific
498# $indexfile). If $LANG or $LC_ALL (in orderder of preference, respectively) is
499# set, ".encoding" will automatically be appended as a suffix to the provided
500# $indexfile pathname.
501#
502# If, within $indexfile, multiple $menu_selection values map to $pgm, only the
503# first one will be returned. If no mapping can be made, the NULL string is
504# returned.
505#
506# If $indexfile does not exist, error status is returned with NULL.
507#
508# This function is a two-parter. Below is the awk(1) portion of the function,
509# afterward is the sh(1) function which utilizes the below awk script.
510#
511f_index_menusel_keyword_awk='
512# Variables that should be defined on the invocation line:
513# 	-v pgm="program_name"
514#
515BEGIN {
516	prefix = "menu_selection=\""
517	plen = length(prefix)
518	found = 0
519}
520{
521	if (!match($0, "^" prefix ".*\\|.*\"")) next
522
523	keyword = command = substr($0, plen + 1, RLENGTH - plen - 1)
524	sub(/^.*\|/, "", command)
525	sub(/\|.*$/, "", keyword)
526
527	if ( command == pgm )
528	{
529		print keyword
530		found++
531		exit
532	}
533}
534END { exit ! found }
535'
536f_index_menusel_keyword()
537{
538	local indexfile="$1" pgm="$2"
539	local lang="${LANG:-$LC_ALL}"
540
541	f_dprintf "f_index_menusel_keyword: index=[%s] pgm=[%s] lang=[%s]" \
542	          "$indexfile" "$pgm" "$lang"
543
544	if [ -f "$indexfile.$lang" ]; then
545		awk -v pgm="$pgm" \
546			"$f_index_menusel_keyword_awk" \
547			"$indexfile.$lang"
548	elif [ -f "$indexfile" ]; then
549		awk -v pgm="$pgm" \
550			"$f_index_menusel_keyword_awk" \
551			"$indexfile"
552	fi
553}
554
555# f_index_menusel_command $indexfile $keyword
556#
557# Process $indexfile and return only the command portion of the menu_selection
558# line with a keyword portion matching $keyword.
559#
560# This function is for mapping [possibly international] keywords into the
561# command to be executed. If $LANG or $LC_ALL (order of preference) is set,
562# ".encoding" will automatically be appended as a suffix to the provided
563# $indexfile pathname.
564#
565# If, within $indexfile, multiple $menu_selection values map to $keyword, only
566# the first one will be returned. If no mapping can be made, the NULL string is
567# returned.
568#
569# If $indexfile doesn't exist, error status is returned with NULL.
570#
571# This function is a two-parter. Below is the awk(1) portion of the function,
572# afterward is the sh(1) function which utilizes the below awk script.
573#
574f_index_menusel_command_awk='
575# Variables that should be defined on the invocation line:
576# 	-v key="keyword"
577#
578BEGIN {
579	prefix = "menu_selection=\""
580	plen = length(prefix)
581	found = 0
582}
583{
584	if (!match($0, "^" prefix ".*\\|.*\"")) next
585
586	keyword = command = substr($0, plen + 1, RLENGTH - plen - 1)
587	sub(/^.*\|/, "", command)
588	sub(/\|.*$/, "", keyword)
589
590	if ( keyword == key )
591	{
592		print command
593		found++
594		exit
595	}
596}
597END { exit ! found }
598'
599f_index_menusel_command()
600{
601	local indexfile="$1" keyword="$2" command
602	local lang="${LANG:-$LC_ALL}"
603
604	f_dprintf "f_index_menusel_command: index=[%s] key=[%s] lang=[%s]" \
605	          "$indexfile" "$keyword" "$lang"
606
607	if [ -f "$indexfile.$lang" ]; then
608		command=$( awk -v key="$keyword" \
609				"$f_index_menusel_command_awk" \
610				"$indexfile.$lang" ) || return $FAILURE
611	elif [ -f "$indexfile" ]; then
612		command=$( awk -v key="$keyword" \
613				"$f_index_menusel_command_awk" \
614				"$indexfile" ) || return $FAILURE
615	else
616		return $FAILURE
617	fi
618
619	#
620	# If the command pathname is not fully qualified fix-up/force to be
621	# relative to the $indexfile directory.
622	#
623	case "$command" in
624	/*) : already fully qualified ;;
625	*)
626		local indexdir="${indexfile%/*}"
627		[ "$indexdir" != "$indexfile" ] || indexdir="."
628		command="$indexdir/$command"
629	esac
630
631	echo "$command"
632}
633
634# f_running_as_init
635#
636# Returns true if running as init(1).
637#
638f_running_as_init()
639{
640	#
641	# When a custom init(8) performs an exec(3) to invoke a shell script,
642	# PID 1 becomes sh(1) and $PPID is set to 1 in the executed script.
643	#
644	[ ${PPID:-0} -eq 1 ] # Return status
645}
646
647# f_mounted $local_directory
648#
649# Return success if a filesystem is mounted on a particular directory.
650#
651f_mounted()
652{
653	local dir="$1"
654	[ -d "$dir" ] || return $FAILURE
655	mount | grep -Eq " on $dir \([^)]+\)$"
656}
657
658############################################################ MAIN
659
660#
661# Trap signals so we can recover gracefully
662#
663trap 'f_interrupt' SIGINT
664trap 'f_die' SIGTERM SIGPIPE SIGXCPU SIGXFSZ \
665             SIGFPE SIGTRAP SIGABRT SIGSEGV
666trap '' SIGALRM SIGPROF SIGUSR1 SIGUSR2 SIGHUP SIGVTALRM
667
668#
669# Clone terminal stdout/stderr so we can redirect to it from within sub-shells
670#
671eval exec $TERMINAL_STDOUT_PASSTHRU\>\&1
672eval exec $TERMINAL_STDERR_PASSTHRU\>\&2
673
674#
675# Self-initialize unless requested otherwise
676#
677f_dprintf "%s: DEBUG_SELF_INITIALIZE=[%s]" \
678          dialog.subr "$DEBUG_SELF_INITIALIZE"
679case "$DEBUG_SELF_INITIALIZE" in
680""|0|[Nn][Oo]|[Oo][Ff][Ff]|[Ff][Aa][Ll][Ss][Ee]) : do nothing ;;
681*) f_debug_init
682esac
683
684#
685# Log our operating environment for debugging purposes
686#
687f_dprintf "UNAME_S=[%s] UNAME_P=[%s] UNAME_R=[%s]" \
688          "$UNAME_S" "$UNAME_P" "$UNAME_R"
689
690f_dprintf "%s: Successfully loaded." common.subr
691
692fi # ! $_COMMON_SUBR
693