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