]> CyberLeo.Net >> Repos - FreeBSD/releng/9.3.git/blob - usr.sbin/bsdconfig/share/common.subr
MFS9 r267683 (dteske):
[FreeBSD/releng/9.3.git] / usr.sbin / bsdconfig / share / common.subr
1 if [ ! "$_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 #
44 pgm="${0##*/}"
45
46 #
47 # Program arguments
48 #
49 ARGC="$#"
50 ARGV="$@"
51
52 #
53 # Global exit status variables
54 #
55 SUCCESS=0
56 FAILURE=1
57
58 #
59 # Operating environment details
60 #
61 export UNAME_S="$( uname -s )" # Operating System (i.e. FreeBSD)
62 export UNAME_P="$( uname -p )" # Processor Architecture (i.e. i386)
63 export UNAME_M="$( uname -m )" # Machine platform (i.e. i386)
64 export UNAME_R="$( uname -r )" # Release Level (i.e. X.Y-RELEASE)
65 if [ ! "${PKG_ABI+set}" ]; then
66         export PKG_ABI="$(
67                 ASSUME_ALWAYS_YES=1 pkg -vv 2> /dev/null |
68                         awk '$1=="ABI"{print $3;exit}'
69         )"
70 fi
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 #
93 GETOPTS_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 #
105 GETOPTS_ALLFLAGS="abcdefghijklmnopqrstuvwxyz"
106 GETOPTS_ALLFLAGS="${GETOPTS_ALLFLAGS}ABCDEFGHIJKLMNOPQRSTUVWXYZ"
107 GETOPTS_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 #
134 f_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 #
150 f_debug_init()
151 {
152         #
153         # Process stored command-line arguments
154         #
155         set -- $ARGV
156         local OPTIND OPTARG flag
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 #
205 f_err()
206 {
207         printf "$@" >&2
208 }
209
210 # f_quietly $command [$arguments ...]
211 #
212 # Run a command quietly (quell any output to stdout or stderr)
213 #
214 f_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 #
224 f_have()
225 {
226         f_quietly type "$@"
227 }
228
229 # f_getvar $var_to_get [$var_to_set]
230 #
231 # Utility function designed to go along with the already-builtin setvar.
232 # Allows clean variable name indirection without forking or sub-shells.
233 #
234 # Returns error status if the requested variable ($var_to_get) is not set.
235 #
236 # If $var_to_set is missing or NULL, the value of $var_to_get is printed to
237 # standard output for capturing in a sub-shell (which is less-recommended
238 # because of performance degredation; for example, when called in a loop).
239 #
240 f_getvar()
241 {
242         local __var_to_get="$1" __var_to_set="$2"
243         [ "$__var_to_set" ] || local value
244         eval [ \"\${$__var_to_get+set}\" ]
245         local __retval=$?
246         eval ${__var_to_set:-value}=\"\${$__var_to_get}\"
247         eval f_dprintf '"f_getvar: var=[%s] value=[%s] r=%u"' \
248                 \"\$__var_to_get\" \"\$${__var_to_set:-value}\" \$__retval
249         [ "$__var_to_set" ] || { [ "$value" ] && echo "$value"; }
250         return $__retval
251 }
252
253 # f_isset $var
254 #
255 # Check if variable $var is set. Returns success if variable is set, otherwise
256 # returns failure.
257 #
258 f_isset()
259 {
260         eval [ \"\${${1%%[$IFS]*}+set}\" ]
261 }
262
263 # f_die [$status [$format [$arguments ...]]]
264 #
265 # Abruptly terminate due to an error optionally displaying a message in a
266 # dialog box using printf(1) syntax.
267 #
268 f_die()
269 {
270         local status=$FAILURE
271
272         # If there is at least one argument, take it as the status
273         if [ $# -gt 0 ]; then
274                 status=$1
275                 shift 1 # status
276         fi
277
278         # If there are still arguments left, pass them to f_show_msg
279         [ $# -gt 0 ] && f_show_msg "$@"
280
281         # Optionally call f_clean_up() function if it exists
282         f_have f_clean_up && f_clean_up
283
284         exit $status
285 }
286
287 # f_interrupt
288 #
289 # Interrupt handler.
290 #
291 f_interrupt()
292 {
293         exec 2>&1 # fix sh(1) bug where stderr gets lost within async-trap
294         f_die
295 }
296
297 # f_show_info $format [$arguments ...]
298 #
299 # Display a message in a dialog infobox using printf(1) syntax.
300 #
301 f_show_info()
302 {
303         local msg
304         msg=$( printf "$@" )
305
306         #
307         # Use f_dialog_infobox 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_info; then
312                 f_dialog_info "$msg"
313         else
314                 dialog --infobox "$msg" 0 0
315         fi
316 }
317
318 # f_show_msg $format [$arguments ...]
319 #
320 # Display a message in a dialog box using printf(1) syntax.
321 #
322 f_show_msg()
323 {
324         local msg
325         msg=$( printf "$@" )
326
327         #
328         # Use f_dialog_msgbox from dialog.subr if possible, otherwise fall
329         # back to dialog(1) (without options, making it obvious when using
330         # un-aided system dialog).
331         #
332         if f_have f_dialog_msgbox; then
333                 f_dialog_msgbox "$msg"
334         else
335                 dialog --msgbox "$msg" 0 0
336         fi
337 }
338
339 # f_show_err $format [$arguments ...]
340 #
341 # Display a message in a dialog box with ``Error'' i18n title (overridden by
342 # setting msg_error) using printf(1) syntax.
343 #
344 f_show_err()
345 {
346         local msg
347         msg=$( printf "$@" )
348
349         : ${msg:=${msg_an_unknown_error_occurred:-An unknown error occurred}}
350
351         if [ "$_DIALOG_SUBR" ]; then
352                 f_dialog_title "${msg_error:-Error}"
353                 f_dialog_msgbox "$msg"
354                 f_dialog_title_restore
355         else
356                 dialog --title "${msg_error:-Error}" --msgbox "$msg" 0 0
357         fi
358         return $SUCCESS
359 }
360
361 # f_yesno $format [$arguments ...]
362 #
363 # Display a message in a dialog yes/no box using printf(1) syntax.
364 #
365 f_yesno()
366 {
367         local msg
368         msg=$( printf "$@" )
369
370         #
371         # Use f_dialog_yesno from dialog.subr if possible, otherwise fall
372         # back to dialog(1) (without options, making it obvious when using
373         # un-aided system dialog).
374         #
375         if f_have f_dialog_yesno; then
376                 f_dialog_yesno "$msg"
377         else
378                 dialog --yesno "$msg" 0 0
379         fi
380 }
381
382 # f_noyes $format [$arguments ...]
383 #
384 # Display a message in a dialog yes/no box using printf(1) syntax.
385 # NOTE: THis is just like the f_yesno function except "No" is default.
386 #
387 f_noyes()
388 {
389         local msg
390         msg=$( printf "$@" )
391
392         #
393         # Use f_dialog_noyes from dialog.subr if possible, otherwise fall
394         # back to dialog(1) (without options, making it obvious when using
395         # un-aided system dialog).
396         #
397         if f_have f_dialog_noyes; then
398                 f_dialog_noyes "$msg"
399         else
400                 dialog --defaultno --yesno "$msg" 0 0
401         fi
402 }
403
404 # f_show_help $file
405 #
406 # Display a language help-file. Automatically takes $LANG and $LC_ALL into
407 # consideration when displaying $file (suffix ".$LC_ALL" or ".$LANG" will
408 # automatically be added prior to loading the language help-file).
409 #
410 # If a language has been requested by setting either $LANG or $LC_ALL in the
411 # environment and the language-specific help-file does not exist we will fall
412 # back to $file without-suffix.
413 #
414 # If the language help-file does not exist, an error is displayed instead.
415 #
416 f_show_help()
417 {
418         local file="$1"
419         local lang="${LANG:-$LC_ALL}"
420
421         [ -f "$file.$lang" ] && file="$file.$lang"
422
423         #
424         # Use f_dialog_textbox from dialog.subr if possible, otherwise fall
425         # back to dialog(1) (without options, making it obvious when using
426         # un-aided system dialog).
427         #
428         if f_have f_dialog_textbox; then
429                 f_dialog_textbox "$file"
430         else
431                 dialog --msgbox "$( cat "$file" 2>&1 )" 0 0
432         fi
433 }
434
435 # f_include $file
436 #
437 # Include a shell subroutine file.
438 #
439 # If the subroutine file exists but returns error status during loading, exit
440 # is called and execution is prematurely terminated with the same error status.
441 #
442 f_include()
443 {
444         local file="$1"
445         f_dprintf "f_include: file=[%s]" "$file"
446         . "$file" || exit $?
447 }
448
449 # f_include_lang $file
450 #
451 # Include a language file. Automatically takes $LANG and $LC_ALL into
452 # consideration when including $file (suffix ".$LC_ALL" or ".$LANG" will
453 # automatically by added prior to loading the language file).
454 #
455 # No error is produced if (a) a language has been requested (by setting either
456 # $LANG or $LC_ALL in the environment) and (b) the language file does not
457 # exist -- in which case we will fall back to loading $file without-suffix.
458 #
459 # If the language file exists but returns error status during loading, exit
460 # is called and execution is prematurely terminated with the same error status.
461 #
462 f_include_lang()
463 {
464         local file="$1"
465         local lang="${LANG:-$LC_ALL}"
466
467         f_dprintf "f_include_lang: file=[%s] lang=[%s]" "$file" "$lang"
468         if [ -f "$file.$lang" ]; then
469                 . "$file.$lang" || exit $?
470         else
471                 . "$file" || exit $?
472         fi
473 }
474
475 # f_usage $file [$key1 $value1 ...]
476 #
477 # Display USAGE file with optional pre-processor macro definitions. The first
478 # argument is the template file containing the usage text to be displayed. If
479 # $LANG or $LC_ALL (in order of preference, respectively) is set, ".encoding"
480 # will automatically be appended as a suffix to the provided $file pathname.
481 #
482 # When processing $file, output begins at the first line containing that is
483 # (a) not a comment, (b) not empty, and (c) is not pure-whitespace. All lines
484 # appearing after this first-line are output, including (a) comments (b) empty
485 # lines, and (c) lines that are purely whitespace-only.
486 #
487 # If additional arguments appear after $file, substitutions are made while
488 # printing the contents of the USAGE file. The pre-processor macro syntax is in
489 # the style of autoconf(1), for example:
490 #
491 #       f_usage $file "FOO" "BAR"
492 #
493 # Will cause instances of "@FOO@" appearing in $file to be replaced with the
494 # text "BAR" before being printed to the screen.
495 #
496 # This function is a two-parter. Below is the awk(1) portion of the function,
497 # afterward is the sh(1) function which utilizes the below awk script.
498 #
499 f_usage_awk='
500 BEGIN { found = 0 }
501 {
502         if ( !found && $0 ~ /^[[:space:]]*($|#)/ ) next
503         found = 1
504         print
505 }
506 '
507 f_usage()
508 {
509         local file="$1"
510         local lang="${LANG:-$LC_ALL}"
511
512         f_dprintf "f_usage: file=[%s] lang=[%s]" "$file" "$lang"
513
514         shift 1 # file
515
516         local usage
517         if [ -f "$file.$lang" ]; then
518                 usage=$( awk "$f_usage_awk" "$file.$lang" ) || exit $FAILURE
519         else
520                 usage=$( awk "$f_usage_awk" "$file" ) || exit $FAILURE
521         fi
522
523         while [ $# -gt 0 ]; do
524                 local key="$1"
525                 export value="$2"
526                 usage=$( echo "$usage" | awk \
527                         "{ gsub(/@$key@/, ENVIRON[\"value\"]); print }" )
528                 shift 2
529         done
530
531         f_err "%s\n" "$usage"
532
533         exit $FAILURE
534 }
535
536 # f_index_file $keyword [$var_to_set]
537 #
538 # Process all INDEX files known to bsdconfig and return the path to first file
539 # containing a menu_selection line with a keyword portion matching $keyword.
540 #
541 # If $LANG or $LC_ALL (in order of preference, respectively) is set,
542 # "INDEX.encoding" files will be searched first.
543 #
544 # If no file is found, error status is returned along with the NULL string.
545 #
546 # If $var_to_set is NULL or missing, output is printed to stdout (which is less
547 # recommended due to performance degradation; in a loop for example).
548 #
549 # This function is a two-parter. Below is the awk(1) portion of the function,
550 # afterward is the sh(1) function which utilizes the below awk script.
551 #
552 f_index_file_awk='
553 # Variables that should be defined on the invocation line:
554 #       -v keyword="keyword"
555 BEGIN { found = 0 }
556 ( $0 ~ "^menu_selection=\"" keyword "\\|" ) {
557         print FILENAME
558         found++
559         exit
560 }
561 END { exit ! found }
562 '
563 f_index_file()
564 {
565         local __keyword="$1" __var_to_set="$2"
566         local __lang="${LANG:-$LC_ALL}"
567         local __indexes="$BSDCFG_LIBE${BSDCFG_LIBE:+/}*/INDEX"
568
569         f_dprintf "f_index_file: keyword=[%s] lang=[%s]" "$__keyword" "$__lang"
570
571         if [ "$__lang" ]; then
572                 if [ "$__var_to_set" ]; then
573                         eval "$__var_to_set"='"$( awk -v keyword="$__keyword" \
574                                 "$f_index_file_awk" $__indexes.$__lang
575                         )"' && return $SUCCESS
576                 else
577                         awk -v keyword="$__keyword" "$f_index_file_awk" \
578                                 $__indexes.$__lang && return $SUCCESS
579                 fi
580                 # No match, fall-thru to non-i18n sources
581         fi
582         if [ "$__var_to_set" ]; then
583                 eval "$__var_to_set"='"$( awk -v keyword="$__keyword" \
584                         "$f_index_file_awk" $__indexes )"' && return $SUCCESS
585         else
586                 awk -v keyword="$__keyword" "$f_index_file_awk" $__indexes &&
587                         return $SUCCESS
588         fi
589
590         # No match? Fall-thru to `local' libexec sources (add-on modules)
591
592         [ "$BSDCFG_LOCAL_LIBE" ] || return $FAILURE
593         __indexes="$BSDCFG_LOCAL_LIBE/*/INDEX"
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 )"'
608         else
609                 awk -v keyword="$__keyword" "$f_index_file_awk" $__indexes
610         fi
611 }
612
613 # f_index_menusel_keyword $indexfile $pgm [$var_to_set]
614 #
615 # Process $indexfile and return only the keyword portion of the menu_selection
616 # line with a command portion matching $pgm.
617 #
618 # This function is for internationalization (i18n) mapping of the on-disk
619 # scriptname ($pgm) into the localized language (given language-specific
620 # $indexfile). If $LANG or $LC_ALL (in orderder of preference, respectively) is
621 # set, ".encoding" will automatically be appended as a suffix to the provided
622 # $indexfile pathname.
623 #
624 # If, within $indexfile, multiple $menu_selection values map to $pgm, only the
625 # first one will be returned. If no mapping can be made, the NULL string is
626 # returned.
627 #
628 # If $indexfile does not exist, error status is returned with NULL.
629 #
630 # If $var_to_set is NULL or missing, output is printed to stdout (which is less
631 # recommended due to performance degradation; in a loop for example).
632 #
633 # This function is a two-parter. Below is the awk(1) portion of the function,
634 # afterward is the sh(1) function which utilizes the below awk script.
635 #
636 f_index_menusel_keyword_awk='
637 # Variables that should be defined on the invocation line:
638 #       -v pgm="program_name"
639 #
640 BEGIN {
641         prefix = "menu_selection=\""
642         plen = length(prefix)
643         found = 0
644 }
645 {
646         if (!match($0, "^" prefix ".*\\|.*\"")) next
647
648         keyword = command = substr($0, plen + 1, RLENGTH - plen - 1)
649         sub(/^.*\|/, "", command)
650         sub(/\|.*$/, "", keyword)
651
652         if ( command == pgm )
653         {
654                 print keyword
655                 found++
656                 exit
657         }
658 }
659 END { exit ! found }
660 '
661 f_index_menusel_keyword()
662 {
663         local __indexfile="$1" __pgm="$2" __var_to_set="$3"
664         local __lang="${LANG:-$LC_ALL}" __file="$__indexfile"
665
666         [ -f "$__indexfile.$__lang" ] && __file="$__indexfile.$__lang"
667         f_dprintf "f_index_menusel_keyword: index=[%s] pgm=[%s] lang=[%s]" \
668                   "$__file" "$__pgm" "$__lang"
669
670         if [ "$__var_to_set" ]; then
671                 setvar "$__var_to_set" "$( awk \
672                     -v pgm="$__pgm" "$f_index_menusel_keyword_awk" "$__file"
673                 )"
674         else
675                 awk -v pgm="$__pgm" "$f_index_menusel_keyword_awk" "$__file"
676         fi
677 }
678
679 # f_index_menusel_command $indexfile $keyword [$var_to_set]
680 #
681 # Process $indexfile and return only the command portion of the menu_selection
682 # line with a keyword portion matching $keyword.
683 #
684 # This function is for mapping [possibly international] keywords into the
685 # command to be executed. If $LANG or $LC_ALL (order of preference) is set,
686 # ".encoding" will automatically be appended as a suffix to the provided
687 # $indexfile pathname.
688 #
689 # If, within $indexfile, multiple $menu_selection values map to $keyword, only
690 # the first one will be returned. If no mapping can be made, the NULL string is
691 # returned.
692 #
693 # If $indexfile doesn't exist, error status is returned with NULL.
694 #
695 # If $var_to_set is NULL or missing, output is printed to stdout (which is less
696 # recommended due to performance degradation; in a loop for example).
697 #
698 # This function is a two-parter. Below is the awk(1) portion of the function,
699 # afterward is the sh(1) function which utilizes the below awk script.
700 #
701 f_index_menusel_command_awk='
702 # Variables that should be defined on the invocation line:
703 #       -v key="keyword"
704 #
705 BEGIN {
706         prefix = "menu_selection=\""
707         plen = length(prefix)
708         found = 0
709 }
710 {
711         if (!match($0, "^" prefix ".*\\|.*\"")) next
712
713         keyword = command = substr($0, plen + 1, RLENGTH - plen - 1)
714         sub(/^.*\|/, "", command)
715         sub(/\|.*$/, "", keyword)
716
717         if ( keyword == key )
718         {
719                 print command
720                 found++
721                 exit
722         }
723 }
724 END { exit ! found }
725 '
726 f_index_menusel_command()
727 {
728         local __indexfile="$1" __keyword="$2" __var_to_set="$3" __command
729         local __lang="${LANG:-$LC_ALL}" __file="$__indexfile"
730
731         [ -f "$__indexfile.$__lang" ] && __file="$__indexfile.$__lang"
732         f_dprintf "f_index_menusel_command: index=[%s] key=[%s] lang=[%s]" \
733                   "$__file" "$__keyword" "$__lang"
734
735         [ -f "$__file" ] || return $FAILURE
736         __command=$( awk -v key="$__keyword" \
737                 "$f_index_menusel_command_awk" "$__file" ) || return $FAILURE
738
739         #
740         # If the command pathname is not fully qualified fix-up/force to be
741         # relative to the $indexfile directory.
742         #
743         case "$__command" in
744         /*) : already fully qualified ;;
745         *)
746                 local __indexdir="${__indexfile%/*}"
747                 [ "$__indexdir" != "$__indexfile" ] || __indexdir="."
748                 __command="$__indexdir/$__command"
749         esac
750
751         if [ "$__var_to_set" ]; then
752                 setvar "$__var_to_set" "$__command"
753         else
754                 echo "$__command"
755         fi
756 }
757
758 # f_running_as_init
759 #
760 # Returns true if running as init(1).
761 #
762 f_running_as_init()
763 {
764         #
765         # When a custom init(8) performs an exec(3) to invoke a shell script,
766         # PID 1 becomes sh(1) and $PPID is set to 1 in the executed script.
767         #
768         [ ${PPID:-0} -eq 1 ] # Return status
769 }
770
771 # f_mounted $local_directory
772 # f_mounted -b $device
773 #
774 # Return success if a filesystem is mounted on a particular directory. If `-b'
775 # is present, instead check that the block device (or a partition thereof) is
776 # mounted.
777 #
778 f_mounted()
779 {
780         local OPTIND OPTARG flag use_device=
781         while getopts b flag; do
782                 case "$flag" in
783                 b) use_device=1 ;;
784                 esac
785         done
786         shift $(( $OPTIND - 1 ))
787         if [ "$use_device" ]; then
788                 local device="$1"
789                 mount | grep -Eq \
790                         "^$device([[:space:]]|p[0-9]|s[0-9]|\.nop|\.eli)"
791         else
792                 [ -d "$dir" ] || return $FAILURE
793                 mount | grep -Eq " on $dir \([^)]+\)$"
794         fi
795         # Return status is that of last grep(1)
796 }
797
798 # f_eval_catch [-de] [-k $var_to_set] $funcname $utility \
799 #              $format [$arguments ...]
800 #
801 # Silently evaluate a command in a sub-shell and test for error. If debugging
802 # is enabled a copy of the command and its output is sent to debug (either
803 # stdout or file depending on environment). If an error occurs, output of the
804 # command is displayed in a dialog(1) msgbox using the [above] f_show_err()
805 # function (unless optional `-d' flag is given, then no dialog).
806 #
807 # The $funcname argument is sent to debugging while the $utility argument is
808 # used in the title of the dialog box. The command that is executed as well as
809 # sent to debugging with $funcname is the product of the printf(1) syntax
810 # produced by $format with optional $arguments.
811 #
812 # The following options are supported:
813 #
814 #       -d      Do not use dialog(1).
815 #       -e      Produce error text from failed command on stderr.
816 #       -k var  Save output from the command in var.
817 #
818 # Example 1:
819 #
820 #       debug=1
821 #       f_eval_catch myfunc echo 'echo "%s"' "Hello, World!"
822 #
823 #       Produces the following debug output:
824 #
825 #               DEBUG: myfunc: echo "Hello, World!"
826 #               DEBUG: myfunc: retval=0 <output below>
827 #               Hello, World!
828 #
829 # Example 2:
830 #
831 #       debug=1
832 #       f_eval_catch -k contents myfunc cat 'cat "%s"' /some/file
833 #       # dialog(1) Error ``cat: /some/file: No such file or directory''
834 #       # contents=[cat: /some/file: No such file or directory]
835 #
836 #       Produces the following debug output:
837 #
838 #               DEBUG: myfunc: cat "/some/file"
839 #               DEBUG: myfunc: retval=1 <output below>
840 #               cat: /some/file: No such file or directory
841 #
842 # Example 3:
843 #
844 #       debug=1
845 #       echo 123 | f_eval_catch myfunc rev rev
846 #
847 #       Produces the following debug output:
848 #
849 #               DEBUG: myfunc: rev
850 #               DEBUG: myfunc: retval=0 <output below>
851 #               321
852 #
853 # Example 4:
854 #
855 #       debug=1
856 #       f_eval_catch myfunc true true
857 #
858 #       Produces the following debug output:
859 #
860 #               DEBUG: myfunc: true
861 #               DEBUG: myfunc: retval=0 <no output>
862 #
863 # Example 5:
864 #
865 #       f_eval_catch -de myfunc ls 'ls "%s"' /some/dir
866 #       # Output on stderr ``ls: /some/dir: No such file or directory''
867 #
868 # Example 6:
869 #
870 #       f_eval_catch -dek contents myfunc ls 'ls "%s"' /etc
871 #       # Output from `ls' sent to stderr and also saved in $contents
872 #
873 f_eval_catch()
874 {
875         local __no_dialog= __show_err= __var_to_set=
876
877         #
878         # Process local function arguments
879         #
880         local OPTIND OPTARG __flag
881         while getopts "dek:" __flag > /dev/null; do
882                 case "$__flag" in
883                 d) __no_dialog=1 ;;
884                 e) __show_err=1 ;;
885                 k) __var_to_set="$OPTARG" ;;
886                 esac
887         done
888         shift $(( $OPTIND - 1 ))
889
890         local __funcname="$1" __utility="$2"; shift 2
891         local __cmd __output __retval
892
893         __cmd=$( printf -- "$@" )
894         f_dprintf "%s: %s" "$__funcname" "$__cmd" # Log command *before* eval
895         __output=$( exec 2>&1; eval "$__cmd" )
896         __retval=$?
897         if [ "$__output" ]; then
898                 [ "$__show_err" ] && echo "$__output" >&2
899                 f_dprintf "%s: retval=%i <output below>\n%s" "$__funcname" \
900                           $__retval "$__output"
901         else
902                 f_dprintf "%s: retval=%i <no output>" "$__funcname" $__retval
903         fi
904
905         ! [ "$__no_dialog" -o "$nonInteractive" -o $__retval -eq $SUCCESS ] &&
906                 msg_error="${msg_error:-Error}${__utility:+: $__utility}" \
907                         f_show_err "%s" "$__output"
908                 # NB: f_show_err will handle NULL output appropriately
909
910         [ "$__var_to_set" ] && setvar "$__var_to_set" "$__output"
911
912         return $__retval
913 }
914
915 # f_count $var_to_set arguments ...
916 #
917 # Sets $var_to_set to the number of arguments minus one (the effective number
918 # of arguments following $var_to_set).
919 #
920 # Example:
921 #       f_count count dog house # count=[2]
922 #
923 f_count()
924 {
925         setvar "$1" $(( $# - 1 ))
926 }
927
928 # f_count_ifs $var_to_set string ...
929 #
930 # Sets $var_to_set to the number of words (split by the internal field
931 # separator, IFS) following $var_to_set.
932 #
933 # Example 1:
934 #
935 #       string="word1   word2   word3"
936 #       f_count_ifs count "$string" # count=[3]
937 #       f_count_ifs count $string # count=[3]
938 #
939 # Example 2:
940 #
941 #       IFS=. f_count_ifs count www.freebsd.org # count=[3]
942 #
943 # NB: Make sure to use double-quotes if you are using a custom value for IFS
944 # and you don't want the current value to effect the result. See example 3.
945 #
946 # Example 3:
947 #
948 #       string="a-b c-d"
949 #       IFS=- f_count_ifs count "$string" # count=[3]
950 #       IFS=- f_count_ifs count $string # count=[4]
951 #
952 f_count_ifs()
953 {
954         local __var_to_set="$1"
955         shift 1
956         set -- $*
957         setvar "$__var_to_set" $#
958 }
959
960 ############################################################ MAIN
961
962 #
963 # Trap signals so we can recover gracefully
964 #
965 trap 'f_interrupt' SIGINT
966 trap 'f_die' SIGTERM SIGPIPE SIGXCPU SIGXFSZ \
967              SIGFPE SIGTRAP SIGABRT SIGSEGV
968 trap '' SIGALRM SIGPROF SIGUSR1 SIGUSR2 SIGHUP SIGVTALRM
969
970 #
971 # Clone terminal stdout/stderr so we can redirect to it from within sub-shells
972 #
973 eval exec $TERMINAL_STDOUT_PASSTHRU\>\&1
974 eval exec $TERMINAL_STDERR_PASSTHRU\>\&2
975
976 #
977 # Self-initialize unless requested otherwise
978 #
979 f_dprintf "%s: DEBUG_SELF_INITIALIZE=[%s]" \
980           dialog.subr "$DEBUG_SELF_INITIALIZE"
981 case "$DEBUG_SELF_INITIALIZE" in
982 ""|0|[Nn][Oo]|[Oo][Ff][Ff]|[Ff][Aa][Ll][Ss][Ee]) : do nothing ;;
983 *) f_debug_init
984 esac
985
986 #
987 # Log our operating environment for debugging purposes
988 #
989 f_dprintf "UNAME_S=[%s] UNAME_P=[%s] UNAME_R=[%s]" \
990           "$UNAME_S" "$UNAME_P" "$UNAME_R"
991
992 f_dprintf "%s: Successfully loaded." common.subr
993
994 fi # ! $_COMMON_SUBR