1 if [ ! "$_COMMON_SUBR" ]; then _COMMON_SUBR=1
3 # Copyright (c) 2012 Ron McDowell
4 # Copyright (c) 2012-2013 Devin Teske
7 # Redistribution and use in source and binary forms, with or without
8 # modification, are permitted provided that the following conditions
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.
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
30 ############################################################ CONFIGURATION
33 # Default file descriptors to link to stdout/stderr for passthru allowing
34 # redirection within a sub-shell to bypass directly to the terminal.
36 : ${TERMINAL_STDOUT_PASSTHRU:=3}}
37 : ${TERMINAL_STDERR_PASSTHRU:=4}}
39 ############################################################ GLOBALS
53 # Global exit status variables
59 # Operating environment details
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)
66 # Default behavior is to call f_debug_init() automatically when loaded.
68 : ${DEBUG_SELF_INITIALIZE=1}
71 # Define standard optstring arguments that should be supported by all programs
72 # using this include (unless DEBUG_SELF_INITIALIZE is set to NULL to prevent
73 # f_debug_init() from autamatically processing "$@" for the below arguments):
76 # D: Sets $debugFile to $OPTARG
81 # The getopts builtin will return 1 either when the end of "$@" or the first
82 # invalid flag is reached. This makes it impossible to determine if you've
83 # processed all the arguments or simply have hit an invalid flag. In the cases
84 # where we want to tolerate invalid flags (f_debug_init() for example), the
85 # following variable can be appended to your optstring argument to getopts,
86 # preventing it from prematurely returning 1 before the end of the arguments.
88 # NOTE: This assumes that all unknown flags are argument-less.
90 GETOPTS_ALLFLAGS="abcdefghijklmnopqrstuvwxyz"
91 GETOPTS_ALLFLAGS="${GETOPTS_ALLFLAGS}ABCDEFGHIJKLMNOPQRSTUVWXYZ"
92 GETOPTS_ALLFLAGS="${GETOPTS_ALLFLAGS}0123456789"
95 # When we get included, f_debug_init() will fire (unless $DEBUG_SELF_INITIALIZE
96 # is set to disable automatic initialization) and process "$@" for a few global
97 # options such as `-d' and/or `-D file'. However, if your program takes custom
98 # flags that take arguments, this automatic processing may fail unexpectedly.
100 # The solution to this problem is to pre-define (before including this file)
101 # the following variable (which defaults to NULL) to indicate that there are
102 # extra flags that should be considered when performing automatic processing of
103 # globally persistent flags.
107 ############################################################ FUNCTIONS
109 # f_dprintf $fmt [ $opts ... ]
111 # Sensible debug function. Override in ~/.bsdconfigrc if desired.
112 # See /usr/share/examples/bsdconfig/bsdconfigrc for example.
114 # If $debug is set and non-NULL, prints DEBUG info using printf(1) syntax:
115 # + To $debugFile, if set and non-NULL
116 # + To standard output if $debugFile is either NULL or unset
117 # + To both if $debugFile begins with a single plus-sign (`+')
121 [ "$debug" ] || return $SUCCESS
122 local fmt="$1"; shift
123 case "$debugFile" in ""|+*)
124 printf "DEBUG: $fmt${fmt:+\n}" "$@" >&${TERMINAL_STDOUT_PASSTHRU:-1}
126 [ "${debugFile#+}" ] &&
127 printf "DEBUG: $fmt${fmt:+\n}" "$@" >> "${debugFile#+}"
133 # Initialize debugging. Truncates $debugFile to zero bytes if set.
138 # Process stored command-line arguments
142 f_dprintf "f_debug_init: ARGV=[%s] GETOPTS_STDARGS=[%s]" \
143 "$ARGV" "$GETOPTS_STDARGS"
144 while getopts "$GETOPTS_STDARGS$GETOPTS_EXTRA$GETOPTS_ALLFLAGS" flag \
148 D) debugFile="$OPTARG" ;;
151 shift $(( $OPTIND - 1 ))
152 f_dprintf "f_debug_init: debug=[%s] debugFile=[%s]" \
153 "$debug" "$debugFile"
156 # Automagically enable debugging if debugFile is set (and non-NULL)
158 [ "$debugFile" ] && { [ "${debug+set}" ] || debug=1; }
161 # Make debugging persistant if set
163 [ "$debug" ] && export debug
164 [ "$debugFile" ] && export debugFile
167 # Truncate the debug file upon. Note that we will trim a leading plus
168 # (`+') from the value of debugFile to support persistant meaning that
169 # f_dprintf() should print both to standard output and $debugFile
170 # (minus the leading plus, of course).
172 local _debug_file="${debugFile#+}"
173 if [ "$_debug_file" ]; then
174 if ( umask 022 && :> "$_debug_file" ); then
175 f_dprintf "Successfully initialized debugFile \`%s'" \
177 [ "${debug+set}" ] ||
178 debug=1 # turn debugging on if not set
181 f_dprintf "Unable to initialize debugFile \`%s'" \
187 # f_err $fmt [ $opts ... ]
189 # Print a message to stderr (fd=2).
193 printf "$@" >&${TERMINAL_STDERR_PASSTHRU:-2}
196 # f_quietly $command [ $arguments ... ]
198 # Run a command quietly (quell any output to stdout or stderr)
202 "$@" > /dev/null 2>&1
205 # f_have $anything ...
207 # A wrapper to the `type' built-in. Returns true if argument is a valid shell
208 # built-in, keyword, or externally-tracked binary, otherwise false.
215 # f_which $anything [$var_to_set]
217 # A fast built-in replacement for syntaxes such as foo=$( which bar ). In a
218 # comparison of 10,000 runs of this function versus which, this function
219 # completed in under 3 seconds, while `which' took almost a full minute.
221 # If $var_to_set is missing or NULL, output is (like which) to standard out.
222 # Returns success if a match was found, failure otherwise.
226 local __name="$1" __var_to_set="$2"
227 case "$__name" in */*|'') return $FAILURE; esac
228 local __p IFS=":" __found=
230 local __exec="$__p/$__name"
231 [ -f "$__exec" -a -x "$__exec" ] && __found=1 && break
233 if [ "$__found" ]; then
234 if [ "$__var_to_set" ]; then
235 setvar "$__var_to_set" "$__exec"
244 # f_getvar $var_to_get [$var_to_set]
246 # Utility function designed to go along with the already-builtin setvar.
247 # Allows clean variable name indirection without forking or sub-shells.
249 # Returns error status if the requested variable ($var_to_get) is not set.
251 # If $var_to_set is missing or NULL, the value of $var_to_get is printed to
252 # standard output for capturing in a sub-shell (which is less-recommended
253 # because of performance degredation; for example, when called in a loop).
257 local __var_to_get="$1" __var_to_set="$2"
258 [ "$__var_to_set" ] || local value
259 eval ${__var_to_set:-value}=\"\${$__var_to_get}\"
260 eval [ \"\${$__var_to_get+set}\" ]
262 eval f_dprintf '"f_getvar: var=[%s] value=[%s] r=%u"' \
263 \"\$__var_to_get\" \"\$${__var_to_set:-value}\" \$__retval
264 [ "$__var_to_set" ] || { [ "$value" ] && echo "$value"; }
270 # Check if variable $var is set. Returns success if variable is set, otherwise
275 eval [ \"\${${1%%[$IFS]*}+set}\" ]
278 # f_die [ $status [ $fmt [ $opts ... ]]]
280 # Abruptly terminate due to an error optionally displaying a message in a
281 # dialog box using printf(1) syntax.
285 local status=$FAILURE
287 # If there is at least one argument, take it as the status
288 if [ $# -gt 0 ]; then
293 # If there are still arguments left, pass them to f_show_msg
294 [ $# -gt 0 ] && f_show_msg "$@"
296 # Optionally call f_clean_up() function if it exists
297 f_have f_clean_up && f_clean_up
308 exec 2>&1 # fix sh(1) bug where stderr gets lost within async-trap
312 # f_show_info $fmt [ $opts ... ]
314 # Display a message in a dialog infobox using printf(1) syntax.
322 # Use f_dialog_infobox from dialog.subr if possible, otherwise fall
323 # back to dialog(1) (without options, making it obvious when using
324 # un-aided system dialog).
326 if f_have f_dialog_info; then
329 dialog --infobox "$msg" 0 0
333 # f_show_msg $fmt [ $opts ... ]
335 # Display a message in a dialog box using printf(1) syntax.
343 # Use f_dialog_msgbox from dialog.subr if possible, otherwise fall
344 # back to dialog(1) (without options, making it obvious when using
345 # un-aided system dialog).
347 if f_have f_dialog_msgbox; then
348 f_dialog_msgbox "$msg"
350 dialog --msgbox "$msg" 0 0
355 # f_yesno $fmt [ $opts ... ]
357 # Display a message in a dialog yes/no box using printf(1) syntax.
365 # Use f_dialog_yesno from dialog.subr if possible, otherwise fall
366 # back to dialog(1) (without options, making it obvious when using
367 # un-aided system dialog).
369 if f_have f_dialog_yesno; then
370 f_dialog_yesno "$msg"
372 dialog --yesno "$msg" 0 0
376 # f_noyes $fmt [ $opts ... ]
378 # Display a message in a dialog yes/no box using printf(1) syntax.
379 # NOTE: THis is just like the f_yesno function except "No" is default.
387 # Use f_dialog_noyes from dialog.subr if possible, otherwise fall
388 # back to dialog(1) (without options, making it obvious when using
389 # un-aided system dialog).
391 if f_have f_dialog_noyes; then
392 f_dialog_noyes "$msg"
394 dialog --defaultno --yesno "$msg" 0 0
400 # Display a language help-file. Automatically takes $LANG and $LC_ALL into
401 # consideration when displaying $file (suffix ".$LC_ALL" or ".$LANG" will
402 # automatically be added prior to loading the language help-file).
404 # If a language has been requested by setting either $LANG or $LC_ALL in the
405 # environment and the language-specific help-file does not exist we will fall
406 # back to $file without-suffix.
408 # If the language help-file does not exist, an error is displayed instead.
413 local lang="${LANG:-$LC_ALL}"
415 [ -f "$file.$lang" ] && file="$file.$lang"
418 # Use f_dialog_textbox from dialog.subr if possible, otherwise fall
419 # back to dialog(1) (without options, making it obvious when using
420 # un-aided system dialog).
422 if f_have f_dialog_textbox; then
423 f_dialog_textbox "$file"
425 dialog --msgbox "$( cat "$file" 2>&1 )" 0 0
431 # Include a shell subroutine file.
433 # If the subroutine file exists but returns error status during loading, exit
434 # is called and execution is prematurely terminated with the same error status.
439 f_dprintf "f_include: file=[%s]" "$file"
443 # f_include_lang $file
445 # Include a language file. Automatically takes $LANG and $LC_ALL into
446 # consideration when including $file (suffix ".$LC_ALL" or ".$LANG" will
447 # automatically by added prior to loading the language file).
449 # No error is produced if (a) a language has been requested (by setting either
450 # $LANG or $LC_ALL in the environment) and (b) the language file does not
451 # exist -- in which case we will fall back to loading $file without-suffix.
453 # If the language file exists but returns error status during loading, exit
454 # is called and execution is prematurely terminated with the same error status.
459 local lang="${LANG:-$LC_ALL}"
461 f_dprintf "f_include_lang: file=[%s] lang=[%s]" "$file" "$lang"
462 if [ -f "$file.$lang" ]; then
463 . "$file.$lang" || exit $?
469 # f_usage $file [ $key1 $value1 ... ]
471 # Display USAGE file with optional pre-processor macro definitions. The first
472 # argument is the template file containing the usage text to be displayed. If
473 # $LANG or $LC_ALL (in order of preference, respectively) is set, ".encoding"
474 # will automatically be appended as a suffix to the provided $file pathname.
476 # When processing $file, output begins at the first line containing that is
477 # (a) not a comment, (b) not empty, and (c) is not pure-whitespace. All lines
478 # appearing after this first-line are output, including (a) comments (b) empty
479 # lines, and (c) lines that are purely whitespace-only.
481 # If additional arguments appear after $file, substitutions are made while
482 # printing the contents of the USAGE file. The pre-processor macro syntax is in
483 # the style of autoconf(1), for example:
485 # f_usage $file "FOO" "BAR"
487 # Will cause instances of "@FOO@" appearing in $file to be replaced with the
488 # text "BAR" before bering printed to the screen.
490 # This function is a two-parter. Below is the awk(1) portion of the function,
491 # afterward is the sh(1) function which utilizes the below awk script.
496 if ( !found && $0 ~ /^[[:space:]]*($|#)/ ) next
504 local lang="${LANG:-$LC_ALL}"
506 f_dprintf "f_usage: file=[%s] lang=[%s]" "$file" "$lang"
511 if [ -f "$file.$lang" ]; then
512 usage=$( awk "$f_usage_awk" "$file.$lang" ) || exit $FAILURE
514 usage=$( awk "$f_usage_awk" "$file" ) || exit $FAILURE
517 while [ $# -gt 0 ]; do
520 usage=$( echo "$usage" | awk \
521 "{ gsub(/@$key@/, ENVIRON[\"value\"]); print }" )
525 f_err "%s\n" "$usage"
530 # f_index_file $keyword
532 # Process all INDEX files known to bsdconfig and return the path to first file
533 # containing a menu_selection line with a keyword portion matching $keyword.
535 # If $LANG or $LC_ALL (in order of preference, respectively) is set,
536 # "INDEX.encoding" files will be searched first.
538 # If no file is found, error status is returned along with the NULL string.
540 # This function is a two-parter. Below is the awk(1) portion of the function,
541 # afterward is the sh(1) function which utilizes the below awk script.
544 # Variables that should be defined on the invocation line:
545 # -v keyword="keyword"
547 ( $0 ~ "^menu_selection=\"" keyword "\\|" ) {
557 local lang="${LANG:-$LC_ALL}"
559 f_dprintf "f_index_file: keyword=[%s] lang=[%s]" "$keyword" "$lang"
562 awk -v keyword="$keyword" "$f_index_file_awk" \
563 $BSDCFG_LIBE${BSDCFG_LIBE:+/}*/INDEX.$lang &&
565 # No match, fall-thru to non-i18n sources
567 awk -v keyword="$keyword" "$f_index_file_awk" \
568 $BSDCFG_LIBE${BSDCFG_LIBE:+/}*/INDEX && return $SUCCESS
570 # No match? Fall-thru to `local' libexec sources (add-on modules)
572 [ "$BSDCFG_LOCAL_LIBE" ] || return $FAILURE
574 awk -v keyword="$keyword" "$f_index_file_awk" \
575 $BSDCFG_LOCAL_LIBE/*/INDEX.$lang && return $SUCCESS
576 # No match, fall-thru to non-i18n sources
578 awk -v keyword="$keyword" "$f_index_file_awk" \
579 $BSDCFG_LOCAL_LIBE/*/INDEX
582 # f_index_menusel_keyword $indexfile $pgm
584 # Process $indexfile and return only the keyword portion of the menu_selection
585 # line with a command portion matching $pgm.
587 # This function is for internationalization (i18n) mapping of the on-disk
588 # scriptname ($pgm) into the localized language (given language-specific
589 # $indexfile). If $LANG or $LC_ALL (in orderder of preference, respectively) is
590 # set, ".encoding" will automatically be appended as a suffix to the provided
591 # $indexfile pathname.
593 # If, within $indexfile, multiple $menu_selection values map to $pgm, only the
594 # first one will be returned. If no mapping can be made, the NULL string is
597 # If $indexfile does not exist, error status is returned with NULL.
599 # This function is a two-parter. Below is the awk(1) portion of the function,
600 # afterward is the sh(1) function which utilizes the below awk script.
602 f_index_menusel_keyword_awk='
603 # Variables that should be defined on the invocation line:
604 # -v pgm="program_name"
607 prefix = "menu_selection=\""
608 plen = length(prefix)
612 if (!match($0, "^" prefix ".*\\|.*\"")) next
614 keyword = command = substr($0, plen + 1, RLENGTH - plen - 1)
615 sub(/^.*\|/, "", command)
616 sub(/\|.*$/, "", keyword)
618 if ( command == pgm )
627 f_index_menusel_keyword()
629 local indexfile="$1" pgm="$2"
630 local lang="${LANG:-$LC_ALL}"
632 f_dprintf "f_index_menusel_keyword: index=[%s] pgm=[%s] lang=[%s]" \
633 "$indexfile" "$pgm" "$lang"
635 if [ -f "$indexfile.$lang" ]; then
637 "$f_index_menusel_keyword_awk" \
639 elif [ -f "$indexfile" ]; then
641 "$f_index_menusel_keyword_awk" \
646 # f_index_menusel_command $indexfile $keyword
648 # Process $indexfile and return only the command portion of the menu_selection
649 # line with a keyword portion matching $keyword.
651 # This function is for mapping [possibly international] keywords into the
652 # command to be executed. If $LANG or $LC_ALL (order of preference) is set,
653 # ".encoding" will automatically be appended as a suffix to the provided
654 # $indexfile pathname.
656 # If, within $indexfile, multiple $menu_selection values map to $keyword, only
657 # the first one will be returned. If no mapping can be made, the NULL string is
660 # If $indexfile doesn't exist, error status is returned with NULL.
662 # This function is a two-parter. Below is the awk(1) portion of the function,
663 # afterward is the sh(1) function which utilizes the below awk script.
665 f_index_menusel_command_awk='
666 # Variables that should be defined on the invocation line:
670 prefix = "menu_selection=\""
671 plen = length(prefix)
675 if (!match($0, "^" prefix ".*\\|.*\"")) next
677 keyword = command = substr($0, plen + 1, RLENGTH - plen - 1)
678 sub(/^.*\|/, "", command)
679 sub(/\|.*$/, "", keyword)
681 if ( keyword == key )
690 f_index_menusel_command()
692 local indexfile="$1" keyword="$2" command
693 local lang="${LANG:-$LC_ALL}"
695 f_dprintf "f_index_menusel_command: index=[%s] key=[%s] lang=[%s]" \
696 "$indexfile" "$keyword" "$lang"
698 if [ -f "$indexfile.$lang" ]; then
699 command=$( awk -v key="$keyword" \
700 "$f_index_menusel_command_awk" \
701 "$indexfile.$lang" ) || return $FAILURE
702 elif [ -f "$indexfile" ]; then
703 command=$( awk -v key="$keyword" \
704 "$f_index_menusel_command_awk" \
705 "$indexfile" ) || return $FAILURE
711 # If the command pathname is not fully qualified fix-up/force to be
712 # relative to the $indexfile directory.
715 /*) : already fully qualified ;;
717 local indexdir="${indexfile%/*}"
718 [ "$indexdir" != "$indexfile" ] || indexdir="."
719 command="$indexdir/$command"
727 # Returns true if running as init(1).
732 # When a custom init(8) performs an exec(3) to invoke a shell script,
733 # PID 1 becomes sh(1) and $PPID is set to 1 in the executed script.
735 [ ${PPID:-0} -eq 1 ] # Return status
738 # f_mounted $local_directory
740 # Return success if a filesystem is mounted on a particular directory.
745 [ -d "$dir" ] || return $FAILURE
746 mount | grep -Eq " on $dir \([^)]+\)$"
749 ############################################################ MAIN
752 # Trap signals so we can recover gracefully
754 trap 'f_interrupt' SIGINT
755 trap 'f_die' SIGTERM SIGPIPE SIGXCPU SIGXFSZ \
756 SIGFPE SIGTRAP SIGABRT SIGSEGV
757 trap '' SIGALRM SIGPROF SIGUSR1 SIGUSR2 SIGHUP SIGVTALRM
760 # Clone terminal stdout/stderr so we can redirect to it from within sub-shells
762 eval exec $TERMINAL_STDOUT_PASSTHRU\>\&1
763 eval exec $TERMINAL_STDERR_PASSTHRU\>\&2
766 # Self-initialize unless requested otherwise
768 f_dprintf "%s: DEBUG_SELF_INITIALIZE=[%s]" \
769 dialog.subr "$DEBUG_SELF_INITIALIZE"
770 case "$DEBUG_SELF_INITIALIZE" in
771 ""|0|[Nn][Oo]|[Oo][Ff][Ff]|[Ff][Aa][Ll][Ss][Ee]) : do nothing ;;
776 # Log our operating environment for debugging purposes
778 f_dprintf "UNAME_S=[%s] UNAME_P=[%s] UNAME_R=[%s]" \
779 "$UNAME_S" "$UNAME_P" "$UNAME_R"
781 f_dprintf "%s: Successfully loaded." common.subr