xref: /freebsd/usr.sbin/bsdconfig/share/common.subr (revision 95d45410b5100e07f6f98450bcd841a8945d4726)
1if [ ! "$_COMMON_SUBR" ]; then _COMMON_SUBR=1
2#
3# Copyright (c) 2012 Ron McDowell
4# Copyright (c) 2012-2014 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_M="$( uname -m )" # Machine platform (i.e. i386)
64export UNAME_R="$( uname -r )" # Release Level (i.e. X.Y-RELEASE)
65
66#
67# Default behavior is to call f_debug_init() automatically when loaded.
68#
69: ${DEBUG_SELF_INITIALIZE=1}
70
71#
72# Default behavior of f_debug_init() is to truncate $debugFile (set to NULL to
73# disable truncating the debug file when initializing). To get child processes
74# to append to the same log file, export this variarable (with a NULL value)
75# and also export debugFile with the desired value.
76#
77: ${DEBUG_INITIALIZE_FILE=1}
78
79#
80# Define standard optstring arguments that should be supported by all programs
81# using this include (unless DEBUG_SELF_INITIALIZE is set to NULL to prevent
82# f_debug_init() from autamatically processing "$@" for the below arguments):
83#
84# 	d	Sets $debug to 1
85# 	D:	Sets $debugFile to $OPTARG
86#
87GETOPTS_STDARGS="dD:"
88
89#
90# The getopts builtin will return 1 either when the end of "$@" or the first
91# invalid flag is reached. This makes it impossible to determine if you've
92# processed all the arguments or simply have hit an invalid flag. In the cases
93# where we want to tolerate invalid flags (f_debug_init() for example), the
94# following variable can be appended to your optstring argument to getopts,
95# preventing it from prematurely returning 1 before the end of the arguments.
96#
97# NOTE: This assumes that all unknown flags are argument-less.
98#
99GETOPTS_ALLFLAGS="abcdefghijklmnopqrstuvwxyz"
100GETOPTS_ALLFLAGS="${GETOPTS_ALLFLAGS}ABCDEFGHIJKLMNOPQRSTUVWXYZ"
101GETOPTS_ALLFLAGS="${GETOPTS_ALLFLAGS}0123456789"
102
103#
104# When we get included, f_debug_init() will fire (unless $DEBUG_SELF_INITIALIZE
105# is set to disable automatic initialization) and process "$@" for a few global
106# options such as `-d' and/or `-D file'. However, if your program takes custom
107# flags that take arguments, this automatic processing may fail unexpectedly.
108#
109# The solution to this problem is to pre-define (before including this file)
110# the following variable (which defaults to NULL) to indicate that there are
111# extra flags that should be considered when performing automatic processing of
112# globally persistent flags.
113#
114: ${GETOPTS_EXTRA:=}
115
116############################################################ FUNCTIONS
117
118# f_dprintf $format [$arguments ...]
119#
120# Sensible debug function. Override in ~/.bsdconfigrc if desired.
121# See /usr/share/examples/bsdconfig/bsdconfigrc for example.
122#
123# If $debug is set and non-NULL, prints DEBUG info using printf(1) syntax:
124# 	+ To $debugFile, if set and non-NULL
125# 	+ To standard output if $debugFile is either NULL or unset
126# 	+ To both if $debugFile begins with a single plus-sign (`+')
127#
128f_dprintf()
129{
130	[ "$debug" ] || return $SUCCESS
131	local fmt="$1"; shift
132	case "$debugFile" in ""|+*)
133	printf "DEBUG: $fmt${fmt:+\n}" "$@" >&${TERMINAL_STDOUT_PASSTHRU:-1}
134	esac
135	[ "${debugFile#+}" ] &&
136		printf "DEBUG: $fmt${fmt:+\n}" "$@" >> "${debugFile#+}"
137	return $SUCCESS
138}
139
140# f_debug_init
141#
142# Initialize debugging. Truncates $debugFile to zero bytes if set.
143#
144f_debug_init()
145{
146	#
147	# Process stored command-line arguments
148	#
149	set -- $ARGV
150	local OPTIND OPTARG flag
151	f_dprintf "f_debug_init: ARGV=[%s] GETOPTS_STDARGS=[%s]" \
152	          "$ARGV" "$GETOPTS_STDARGS"
153	while getopts "$GETOPTS_STDARGS$GETOPTS_EXTRA$GETOPTS_ALLFLAGS" flag \
154	> /dev/null; do
155		case "$flag" in
156		d) debug=1 ;;
157		D) debugFile="$OPTARG" ;;
158		esac
159	done
160	shift $(( $OPTIND - 1 ))
161	f_dprintf "f_debug_init: debug=[%s] debugFile=[%s]" \
162	          "$debug" "$debugFile"
163
164	#
165	# Automagically enable debugging if debugFile is set (and non-NULL)
166	#
167	[ "$debugFile" ] && { [ "${debug+set}" ] || debug=1; }
168
169	#
170	# Make debugging persistant if set
171	#
172	[ "$debug" ] && export debug
173	[ "$debugFile" ] && export debugFile
174
175	#
176	# Truncate debug file unless requested otherwise. Note that we will
177	# trim a leading plus (`+') from the value of debugFile to support
178	# persistant meaning that f_dprintf() should print both to standard
179	# output and $debugFile (minus the leading plus, of course).
180	#
181	local _debug_file="${debugFile#+}"
182	if [ "$_debug_file" -a "$DEBUG_INITIALIZE_FILE" ]; then
183		if ( umask 022 && :> "$_debug_file" ); then
184			f_dprintf "Successfully initialized debugFile \`%s'" \
185			          "$_debug_file"
186			f_isset debug || debug=1 # turn debugging on if not set
187		else
188			unset debugFile
189			f_dprintf "Unable to initialize debugFile \`%s'" \
190			          "$_debug_file"
191		fi
192	fi
193}
194
195# f_err $format [$arguments ...]
196#
197# Print a message to stderr (fd=2).
198#
199f_err()
200{
201	printf "$@" >&2
202}
203
204# f_quietly $command [$arguments ...]
205#
206# Run a command quietly (quell any output to stdout or stderr)
207#
208f_quietly()
209{
210	"$@" > /dev/null 2>&1
211}
212
213# f_have $anything ...
214#
215# A wrapper to the `type' built-in. Returns true if argument is a valid shell
216# built-in, keyword, or externally-tracked binary, otherwise false.
217#
218f_have()
219{
220	f_quietly type "$@"
221}
222
223# f_which $anything [$var_to_set]
224#
225# A fast built-in replacement for syntaxes such as foo=$( which bar ). In a
226# comparison of 10,000 runs of this function versus which, this function
227# completed in under 3 seconds, while `which' took almost a full minute.
228#
229# If $var_to_set is missing or NULL, output is (like which) to standard out.
230# Returns success if a match was found, failure otherwise.
231#
232f_which()
233{
234	local __name="$1" __var_to_set="$2"
235	case "$__name" in */*|'') return $FAILURE; esac
236	local __p IFS=":" __found=
237	for __p in $PATH; do
238		local __exec="$__p/$__name"
239		[ -f "$__exec" -a -x "$__exec" ] && __found=1 && break
240	done
241	if [ "$__found" ]; then
242		if [ "$__var_to_set" ]; then
243			setvar "$__var_to_set" "$__exec"
244		else
245			echo "$__exec"
246		fi
247		return $SUCCESS
248	fi
249	return $FAILURE
250}
251
252# f_getvar $var_to_get [$var_to_set]
253#
254# Utility function designed to go along with the already-builtin setvar.
255# Allows clean variable name indirection without forking or sub-shells.
256#
257# Returns error status if the requested variable ($var_to_get) is not set.
258#
259# If $var_to_set is missing or NULL, the value of $var_to_get is printed to
260# standard output for capturing in a sub-shell (which is less-recommended
261# because of performance degredation; for example, when called in a loop).
262#
263f_getvar()
264{
265	local __var_to_get="$1" __var_to_set="$2"
266	[ "$__var_to_set" ] || local value
267	eval [ \"\${$__var_to_get+set}\" ]
268	local __retval=$?
269	eval ${__var_to_set:-value}=\"\${$__var_to_get}\"
270	eval f_dprintf '"f_getvar: var=[%s] value=[%s] r=%u"' \
271		\"\$__var_to_get\" \"\$${__var_to_set:-value}\" \$__retval
272	[ "$__var_to_set" ] || { [ "$value" ] && echo "$value"; }
273	return $__retval
274}
275
276# f_isset $var
277#
278# Check if variable $var is set. Returns success if variable is set, otherwise
279# returns failure.
280#
281f_isset()
282{
283	eval [ \"\${${1%%[$IFS]*}+set}\" ]
284}
285
286# f_die [$status [$format [$arguments ...]]]
287#
288# Abruptly terminate due to an error optionally displaying a message in a
289# dialog box using printf(1) syntax.
290#
291f_die()
292{
293	local status=$FAILURE
294
295	# If there is at least one argument, take it as the status
296	if [ $# -gt 0 ]; then
297		status=$1
298		shift 1 # status
299	fi
300
301	# If there are still arguments left, pass them to f_show_msg
302	[ $# -gt 0 ] && f_show_msg "$@"
303
304	# Optionally call f_clean_up() function if it exists
305	f_have f_clean_up && f_clean_up
306
307	exit $status
308}
309
310# f_interrupt
311#
312# Interrupt handler.
313#
314f_interrupt()
315{
316	exec 2>&1 # fix sh(1) bug where stderr gets lost within async-trap
317	f_die
318}
319
320# f_show_info $format [$arguments ...]
321#
322# Display a message in a dialog infobox using printf(1) syntax.
323#
324f_show_info()
325{
326	local msg
327	msg=$( printf "$@" )
328
329	#
330	# Use f_dialog_infobox from dialog.subr if possible, otherwise fall
331	# back to dialog(1) (without options, making it obvious when using
332	# un-aided system dialog).
333	#
334	if f_have f_dialog_info; then
335		f_dialog_info "$msg"
336	else
337		dialog --infobox "$msg" 0 0
338	fi
339}
340
341# f_show_msg $format [$arguments ...]
342#
343# Display a message in a dialog box using printf(1) syntax.
344#
345f_show_msg()
346{
347	local msg
348	msg=$( printf "$@" )
349
350	#
351	# Use f_dialog_msgbox from dialog.subr if possible, otherwise fall
352	# back to dialog(1) (without options, making it obvious when using
353	# un-aided system dialog).
354	#
355	if f_have f_dialog_msgbox; then
356		f_dialog_msgbox "$msg"
357	else
358		dialog --msgbox "$msg" 0 0
359	fi
360}
361
362# f_show_err $format [$arguments ...]
363#
364# Display a message in a dialog box with ``Error'' i18n title (overridden by
365# setting msg_error) using printf(1) syntax.
366#
367f_show_err()
368{
369	local msg
370	msg=$( printf "$@" )
371
372	: ${msg:=${msg_an_unknown_error_occurred:-An unknown error occurred}}
373
374	if [ "$_DIALOG_SUBR" ]; then
375		f_dialog_title "${msg_error:-Error}"
376		f_dialog_msgbox "$msg"
377		f_dialog_title_restore
378	else
379		dialog --title "${msg_error:-Error}" --msgbox "$msg" 0 0
380	fi
381	return $SUCCESS
382}
383
384# f_yesno $format [$arguments ...]
385#
386# Display a message in a dialog yes/no box using printf(1) syntax.
387#
388f_yesno()
389{
390	local msg
391	msg=$( printf "$@" )
392
393	#
394	# Use f_dialog_yesno from dialog.subr if possible, otherwise fall
395	# back to dialog(1) (without options, making it obvious when using
396	# un-aided system dialog).
397	#
398	if f_have f_dialog_yesno; then
399		f_dialog_yesno "$msg"
400	else
401		dialog --yesno "$msg" 0 0
402	fi
403}
404
405# f_noyes $format [$arguments ...]
406#
407# Display a message in a dialog yes/no box using printf(1) syntax.
408# NOTE: THis is just like the f_yesno function except "No" is default.
409#
410f_noyes()
411{
412	local msg
413	msg=$( printf "$@" )
414
415	#
416	# Use f_dialog_noyes from dialog.subr if possible, otherwise fall
417	# back to dialog(1) (without options, making it obvious when using
418	# un-aided system dialog).
419	#
420	if f_have f_dialog_noyes; then
421		f_dialog_noyes "$msg"
422	else
423		dialog --defaultno --yesno "$msg" 0 0
424	fi
425}
426
427# f_show_help $file
428#
429# Display a language help-file. Automatically takes $LANG and $LC_ALL into
430# consideration when displaying $file (suffix ".$LC_ALL" or ".$LANG" will
431# automatically be added prior to loading the language help-file).
432#
433# If a language has been requested by setting either $LANG or $LC_ALL in the
434# environment and the language-specific help-file does not exist we will fall
435# back to $file without-suffix.
436#
437# If the language help-file does not exist, an error is displayed instead.
438#
439f_show_help()
440{
441	local file="$1"
442	local lang="${LANG:-$LC_ALL}"
443
444	[ -f "$file.$lang" ] && file="$file.$lang"
445
446	#
447	# Use f_dialog_textbox from dialog.subr if possible, otherwise fall
448	# back to dialog(1) (without options, making it obvious when using
449	# un-aided system dialog).
450	#
451	if f_have f_dialog_textbox; then
452		f_dialog_textbox "$file"
453	else
454		dialog --msgbox "$( cat "$file" 2>&1 )" 0 0
455	fi
456}
457
458# f_include $file
459#
460# Include a shell subroutine file.
461#
462# If the subroutine file exists but returns error status during loading, exit
463# is called and execution is prematurely terminated with the same error status.
464#
465f_include()
466{
467	local file="$1"
468	f_dprintf "f_include: file=[%s]" "$file"
469	. "$file" || exit $?
470}
471
472# f_include_lang $file
473#
474# Include a language file. Automatically takes $LANG and $LC_ALL into
475# consideration when including $file (suffix ".$LC_ALL" or ".$LANG" will
476# automatically by added prior to loading the language file).
477#
478# No error is produced if (a) a language has been requested (by setting either
479# $LANG or $LC_ALL in the environment) and (b) the language file does not
480# exist -- in which case we will fall back to loading $file without-suffix.
481#
482# If the language file exists but returns error status during loading, exit
483# is called and execution is prematurely terminated with the same error status.
484#
485f_include_lang()
486{
487	local file="$1"
488	local lang="${LANG:-$LC_ALL}"
489
490	f_dprintf "f_include_lang: file=[%s] lang=[%s]" "$file" "$lang"
491	if [ -f "$file.$lang" ]; then
492		. "$file.$lang" || exit $?
493	else
494		. "$file" || exit $?
495	fi
496}
497
498# f_usage $file [$key1 $value1 ...]
499#
500# Display USAGE file with optional pre-processor macro definitions. The first
501# argument is the template file containing the usage text to be displayed. If
502# $LANG or $LC_ALL (in order of preference, respectively) is set, ".encoding"
503# will automatically be appended as a suffix to the provided $file pathname.
504#
505# When processing $file, output begins at the first line containing that is
506# (a) not a comment, (b) not empty, and (c) is not pure-whitespace. All lines
507# appearing after this first-line are output, including (a) comments (b) empty
508# lines, and (c) lines that are purely whitespace-only.
509#
510# If additional arguments appear after $file, substitutions are made while
511# printing the contents of the USAGE file. The pre-processor macro syntax is in
512# the style of autoconf(1), for example:
513#
514# 	f_usage $file "FOO" "BAR"
515#
516# Will cause instances of "@FOO@" appearing in $file to be replaced with the
517# text "BAR" before being printed to the screen.
518#
519# This function is a two-parter. Below is the awk(1) portion of the function,
520# afterward is the sh(1) function which utilizes the below awk script.
521#
522f_usage_awk='
523BEGIN { found = 0 }
524{
525	if ( !found && $0 ~ /^[[:space:]]*($|#)/ ) next
526	found = 1
527	print
528}
529'
530f_usage()
531{
532	local file="$1"
533	local lang="${LANG:-$LC_ALL}"
534
535	f_dprintf "f_usage: file=[%s] lang=[%s]" "$file" "$lang"
536
537	shift 1 # file
538
539	local usage
540	if [ -f "$file.$lang" ]; then
541		usage=$( awk "$f_usage_awk" "$file.$lang" ) || exit $FAILURE
542	else
543		usage=$( awk "$f_usage_awk" "$file" ) || exit $FAILURE
544	fi
545
546	while [ $# -gt 0 ]; do
547		local key="$1"
548		export value="$2"
549		usage=$( echo "$usage" | awk \
550			"{ gsub(/@$key@/, ENVIRON[\"value\"]); print }" )
551		shift 2
552	done
553
554	f_err "%s\n" "$usage"
555
556	exit $FAILURE
557}
558
559# f_index_file $keyword [$var_to_set]
560#
561# Process all INDEX files known to bsdconfig and return the path to first file
562# containing a menu_selection line with a keyword portion matching $keyword.
563#
564# If $LANG or $LC_ALL (in order of preference, respectively) is set,
565# "INDEX.encoding" files will be searched first.
566#
567# If no file is found, error status is returned along with the NULL string.
568#
569# If $var_to_set is NULL or missing, output is printed to stdout (which is less
570# recommended due to performance degradation; in a loop for example).
571#
572# This function is a two-parter. Below is the awk(1) portion of the function,
573# afterward is the sh(1) function which utilizes the below awk script.
574#
575f_index_file_awk='
576# Variables that should be defined on the invocation line:
577# 	-v keyword="keyword"
578BEGIN { found = 0 }
579( $0 ~ "^menu_selection=\"" keyword "\\|" ) {
580	print FILENAME
581	found++
582	exit
583}
584END { exit ! found }
585'
586f_index_file()
587{
588	local __keyword="$1" __var_to_set="$2"
589	local __lang="${LANG:-$LC_ALL}"
590	local __indexes="$BSDCFG_LIBE${BSDCFG_LIBE:+/}*/INDEX"
591
592	f_dprintf "f_index_file: keyword=[%s] lang=[%s]" "$__keyword" "$__lang"
593
594	if [ "$__lang" ]; then
595		if [ "$__var_to_set" ]; then
596			eval "$__var_to_set"='"$( awk -v keyword="$__keyword" \
597				"$f_index_file_awk" $__indexes.$__lang
598			)"' && return $SUCCESS
599		else
600			awk -v keyword="$__keyword" "$f_index_file_awk" \
601				$__indexes.$__lang && return $SUCCESS
602		fi
603		# No match, fall-thru to non-i18n sources
604	fi
605	if [ "$__var_to_set" ]; then
606		eval "$__var_to_set"='"$( awk -v keyword="$__keyword" \
607			"$f_index_file_awk" $__indexes )"' && return $SUCCESS
608	else
609		awk -v keyword="$__keyword" "$f_index_file_awk" $__indexes &&
610			return $SUCCESS
611	fi
612
613	# No match? Fall-thru to `local' libexec sources (add-on modules)
614
615	[ "$BSDCFG_LOCAL_LIBE" ] || return $FAILURE
616	__indexes="$BSDCFG_LOCAL_LIBE/*/INDEX"
617	if [ "$__lang" ]; then
618		if [ "$__var_to_set" ]; then
619			eval "$__var_to_set"='"$( awk -v keyword="$__keyword" \
620				"$f_index_file_awk" $__indexes.$__lang
621			)"' && return $SUCCESS
622		else
623			awk -v keyword="$__keyword" "$f_index_file_awk" \
624				$__indexes.$__lang && return $SUCCESS
625		fi
626		# No match, fall-thru to non-i18n sources
627	fi
628	if [ "$__var_to_set" ]; then
629		eval "$__var_to_set"='$( awk -v keyword="$__keyword" \
630			"$f_index_file_awk" $__indexes )"'
631	else
632		awk -v keyword="$__keyword" "$f_index_file_awk" $__indexes
633	fi
634}
635
636# f_index_menusel_keyword $indexfile $pgm [$var_to_set]
637#
638# Process $indexfile and return only the keyword portion of the menu_selection
639# line with a command portion matching $pgm.
640#
641# This function is for internationalization (i18n) mapping of the on-disk
642# scriptname ($pgm) into the localized language (given language-specific
643# $indexfile). If $LANG or $LC_ALL (in orderder of preference, respectively) is
644# set, ".encoding" will automatically be appended as a suffix to the provided
645# $indexfile pathname.
646#
647# If, within $indexfile, multiple $menu_selection values map to $pgm, only the
648# first one will be returned. If no mapping can be made, the NULL string is
649# returned.
650#
651# If $indexfile does not exist, error status is returned with NULL.
652#
653# If $var_to_set is NULL or missing, output is printed to stdout (which is less
654# recommended due to performance degradation; in a loop for example).
655#
656# This function is a two-parter. Below is the awk(1) portion of the function,
657# afterward is the sh(1) function which utilizes the below awk script.
658#
659f_index_menusel_keyword_awk='
660# Variables that should be defined on the invocation line:
661# 	-v pgm="program_name"
662#
663BEGIN {
664	prefix = "menu_selection=\""
665	plen = length(prefix)
666	found = 0
667}
668{
669	if (!match($0, "^" prefix ".*\\|.*\"")) next
670
671	keyword = command = substr($0, plen + 1, RLENGTH - plen - 1)
672	sub(/^.*\|/, "", command)
673	sub(/\|.*$/, "", keyword)
674
675	if ( command == pgm )
676	{
677		print keyword
678		found++
679		exit
680	}
681}
682END { exit ! found }
683'
684f_index_menusel_keyword()
685{
686	local __indexfile="$1" __pgm="$2" __var_to_set="$3"
687	local __lang="${LANG:-$LC_ALL}" __file="$__indexfile"
688
689	[ -f "$__indexfile.$__lang" ] && __file="$__indexfile.$__lang"
690	f_dprintf "f_index_menusel_keyword: index=[%s] pgm=[%s] lang=[%s]" \
691	          "$__file" "$__pgm" "$__lang"
692
693	if [ "$__var_to_set" ]; then
694		setvar "$__var_to_set" "$( awk \
695		    -v pgm="$__pgm" "$f_index_menusel_keyword_awk" "$__file"
696		)"
697	else
698		awk -v pgm="$__pgm" "$f_index_menusel_keyword_awk" "$__file"
699	fi
700}
701
702# f_index_menusel_command $indexfile $keyword [$var_to_set]
703#
704# Process $indexfile and return only the command portion of the menu_selection
705# line with a keyword portion matching $keyword.
706#
707# This function is for mapping [possibly international] keywords into the
708# command to be executed. If $LANG or $LC_ALL (order of preference) is set,
709# ".encoding" will automatically be appended as a suffix to the provided
710# $indexfile pathname.
711#
712# If, within $indexfile, multiple $menu_selection values map to $keyword, only
713# the first one will be returned. If no mapping can be made, the NULL string is
714# returned.
715#
716# If $indexfile doesn't exist, error status is returned with NULL.
717#
718# If $var_to_set is NULL or missing, output is printed to stdout (which is less
719# recommended due to performance degradation; in a loop for example).
720#
721# This function is a two-parter. Below is the awk(1) portion of the function,
722# afterward is the sh(1) function which utilizes the below awk script.
723#
724f_index_menusel_command_awk='
725# Variables that should be defined on the invocation line:
726# 	-v key="keyword"
727#
728BEGIN {
729	prefix = "menu_selection=\""
730	plen = length(prefix)
731	found = 0
732}
733{
734	if (!match($0, "^" prefix ".*\\|.*\"")) next
735
736	keyword = command = substr($0, plen + 1, RLENGTH - plen - 1)
737	sub(/^.*\|/, "", command)
738	sub(/\|.*$/, "", keyword)
739
740	if ( keyword == key )
741	{
742		print command
743		found++
744		exit
745	}
746}
747END { exit ! found }
748'
749f_index_menusel_command()
750{
751	local __indexfile="$1" __keyword="$2" __var_to_set="$3" __command
752	local __lang="${LANG:-$LC_ALL}" __file="$__indexfile"
753
754	[ -f "$__indexfile.$__lang" ] && __file="$__indexfile.$__lang"
755	f_dprintf "f_index_menusel_command: index=[%s] key=[%s] lang=[%s]" \
756	          "$__file" "$__keyword" "$__lang"
757
758	[ -f "$__file" ] || return $FAILURE
759	__command=$( awk -v key="$__keyword" \
760		"$f_index_menusel_command_awk" "$__file" ) || return $FAILURE
761
762	#
763	# If the command pathname is not fully qualified fix-up/force to be
764	# relative to the $indexfile directory.
765	#
766	case "$__command" in
767	/*) : already fully qualified ;;
768	*)
769		local __indexdir="${__indexfile%/*}"
770		[ "$__indexdir" != "$__indexfile" ] || __indexdir="."
771		__command="$__indexdir/$__command"
772	esac
773
774	if [ "$__var_to_set" ]; then
775		setvar "$__var_to_set" "$__command"
776	else
777		echo "$__command"
778	fi
779}
780
781# f_running_as_init
782#
783# Returns true if running as init(1).
784#
785f_running_as_init()
786{
787	#
788	# When a custom init(8) performs an exec(3) to invoke a shell script,
789	# PID 1 becomes sh(1) and $PPID is set to 1 in the executed script.
790	#
791	[ ${PPID:-0} -eq 1 ] # Return status
792}
793
794# f_mounted $local_directory
795# f_mounted -b $device
796#
797# Return success if a filesystem is mounted on a particular directory. If `-b'
798# is present, instead check that the block device (or a partition thereof) is
799# mounted.
800#
801f_mounted()
802{
803	local OPTIND OPTARG flag use_device=
804	while getopts b flag; do
805		case "$flag" in
806		b) use_device=1 ;;
807		esac
808	done
809	shift $(( $OPTIND - 1 ))
810	if [ "$use_device" ]; then
811		local device="$1"
812		mount | grep -Eq \
813			"^$device([[:space:]]|p[0-9]|s[0-9]|\.nop|\.eli)"
814	else
815		[ -d "$dir" ] || return $FAILURE
816		mount | grep -Eq " on $dir \([^)]+\)$"
817	fi
818	# Return status is that of last grep(1)
819}
820
821# f_eval_catch [-de] [-k $var_to_set] $funcname $utility \
822#              $format [$arguments ...]
823#
824# Silently evaluate a command in a sub-shell and test for error. If debugging
825# is enabled a copy of the command and its output is sent to debug (either
826# stdout or file depending on environment). If an error occurs, output of the
827# command is displayed in a dialog(1) msgbox using the [above] f_show_err()
828# function (unless optional `-d' flag is given, then no dialog).
829#
830# The $funcname argument is sent to debugging while the $utility argument is
831# used in the title of the dialog box. The command that is executed as well as
832# sent to debugging with $funcname is the product of the printf(1) syntax
833# produced by $format with optional $arguments.
834#
835# The following options are supported:
836#
837# 	-d	Do not use dialog(1).
838# 	-e	Produce error text from failed command on stderr.
839# 	-k var	Save output from the command in var.
840#
841# Example 1:
842#
843# 	debug=1
844# 	f_eval_catch myfunc echo 'echo "%s"' "Hello, World!"
845#
846# 	Produces the following debug output:
847#
848# 		DEBUG: myfunc: echo "Hello, World!"
849# 		DEBUG: myfunc: retval=0 <output below>
850# 		Hello, World!
851#
852# Example 2:
853#
854# 	debug=1
855# 	f_eval_catch -k contents myfunc cat 'cat "%s"' /some/file
856# 	# dialog(1) Error ``cat: /some/file: No such file or directory''
857# 	# contents=[cat: /some/file: No such file or directory]
858#
859# 	Produces the following debug output:
860#
861# 		DEBUG: myfunc: cat "/some/file"
862# 		DEBUG: myfunc: retval=1 <output below>
863# 		cat: /some/file: No such file or directory
864#
865# Example 3:
866#
867# 	debug=1
868# 	echo 123 | f_eval_catch myfunc rev rev
869#
870# 	Produces the following debug output:
871#
872# 		DEBUG: myfunc: rev
873# 		DEBUG: myfunc: retval=0 <output below>
874# 		321
875#
876# Example 4:
877#
878# 	debug=1
879# 	f_eval_catch myfunc true true
880#
881# 	Produces the following debug output:
882#
883# 		DEBUG: myfunc: true
884# 		DEBUG: myfunc: retval=0 <no output>
885#
886# Example 5:
887#
888# 	f_eval_catch -de myfunc ls 'ls "%s"' /some/dir
889# 	# Output on stderr ``ls: /some/dir: No such file or directory''
890#
891# Example 6:
892#
893# 	f_eval_catch -dek contents myfunc ls 'ls "%s"' /etc
894# 	# Output from `ls' sent to stderr and also saved in $contents
895#
896f_eval_catch()
897{
898	local __no_dialog= __show_err= __var_to_set=
899
900	#
901	# Process local function arguments
902	#
903	local OPTIND OPTARG __flag
904	while getopts "dek:" __flag > /dev/null; do
905		case "$__flag" in
906		d) __no_dialog=1 ;;
907		e) __show_err=1 ;;
908		k) __var_to_set="$OPTARG" ;;
909		esac
910	done
911	shift $(( $OPTIND - 1 ))
912
913	local __funcname="$1" __utility="$2"; shift 2
914	local __cmd __output __retval
915
916	__cmd=$( printf -- "$@" )
917	f_dprintf "%s: %s" "$__funcname" "$__cmd" # Log command *before* eval
918	__output=$( exec 2>&1; eval "$__cmd" )
919	__retval=$?
920	if [ "$__output" ]; then
921		[ "$__show_err" ] && echo "$__output" >&2
922		f_dprintf "%s: retval=%i <output below>\n%s" "$__funcname" \
923		          $__retval "$__output"
924	else
925		f_dprintf "%s: retval=%i <no output>" "$__funcname" $__retval
926	fi
927
928	! [ "$__no_dialog" -o "$nonInteractive" -o $__retval -eq $SUCCESS ] &&
929		msg_error="${msg_error:-Error}${__utility:+: $__utility}" \
930			f_show_err "%s" "$__output"
931		# NB: f_show_err will handle NULL output appropriately
932
933	[ "$__var_to_set" ] && setvar "$__var_to_set" "$__output"
934
935	return $__retval
936}
937
938# f_count $var_to_set arguments ...
939#
940# Sets $var_to_set to the number of arguments minus one (the effective number
941# of arguments following $var_to_set).
942#
943# Example:
944# 	f_count count dog house # count=[2]
945#
946f_count()
947{
948	setvar "$1" $(( $# - 1 ))
949}
950
951# f_count_ifs $var_to_set string ...
952#
953# Sets $var_to_set to the number of words (split by the internal field
954# separator, IFS) following $var_to_set.
955#
956# Example 1:
957#
958# 	string="word1   word2   word3"
959# 	f_count_ifs count "$string" # count=[3]
960# 	f_count_ifs count $string # count=[3]
961#
962# Example 2:
963#
964# 	IFS=. f_count_ifs count www.freebsd.org # count=[3]
965#
966# NB: Make sure to use double-quotes if you are using a custom value for IFS
967# and you don't want the current value to effect the result. See example 3.
968#
969# Example 3:
970#
971# 	string="a-b c-d"
972# 	IFS=- f_count_ifs count "$string" # count=[3]
973# 	IFS=- f_count_ifs count $string # count=[4]
974#
975f_count_ifs()
976{
977	local __var_to_set="$1"
978	shift 1
979	set -- $*
980	setvar "$__var_to_set" $#
981}
982
983############################################################ MAIN
984
985#
986# Trap signals so we can recover gracefully
987#
988trap 'f_interrupt' SIGINT
989trap 'f_die' SIGTERM SIGPIPE SIGXCPU SIGXFSZ \
990             SIGFPE SIGTRAP SIGABRT SIGSEGV
991trap '' SIGALRM SIGPROF SIGUSR1 SIGUSR2 SIGHUP SIGVTALRM
992
993#
994# Clone terminal stdout/stderr so we can redirect to it from within sub-shells
995#
996eval exec $TERMINAL_STDOUT_PASSTHRU\>\&1
997eval exec $TERMINAL_STDERR_PASSTHRU\>\&2
998
999#
1000# Self-initialize unless requested otherwise
1001#
1002f_dprintf "%s: DEBUG_SELF_INITIALIZE=[%s]" \
1003          dialog.subr "$DEBUG_SELF_INITIALIZE"
1004case "$DEBUG_SELF_INITIALIZE" in
1005""|0|[Nn][Oo]|[Oo][Ff][Ff]|[Ff][Aa][Ll][Ss][Ee]) : do nothing ;;
1006*) f_debug_init
1007esac
1008
1009#
1010# Log our operating environment for debugging purposes
1011#
1012f_dprintf "UNAME_S=[%s] UNAME_P=[%s] UNAME_R=[%s]" \
1013          "$UNAME_S" "$UNAME_P" "$UNAME_R"
1014
1015f_dprintf "%s: Successfully loaded." common.subr
1016
1017fi # ! $_COMMON_SUBR
1018