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