#!/usr/bin/bash

### See Conventions, Notes for purpose of open bracket at end of this line     {
### There should be nothing before this except the code to cause this
### script to be executed under bash.

### See documentation on cmd_ECHO elsewhere.
declare -r -i RET_RUNTIME_NOECHO=100
echo &>/dev/null || exit $RET_RUNTIME_NOECHO

### Treat unset variables as an error when performing parameter expansion.
### If expansion is attempted on an unset variable, the shell prints an
### error message, and, if not interactive, exits with a non-zero status.
### Same as setting -u on bash call to script.
set -o nounset

### SECTION: Conventions, Notes ###############################################{

### - You will note comments of the form #{, #}{ and #}. These are simply to
###   allow bracket matching in editors that support it (such as vi) to make
###   it easier to navigate blocks of text. If it is necessary to introduce
###   extra { or } characters into the script for whatever reason (such as was
###   done in this very comment!), a matching bracket should be introduced as
###   well. You will note there is an open bracket near the beginning of this
###   script, and a close bracket as the last line. These should always match.
###   If not, there is an extraneous bracket in the script.
###
### - Related to the preceding bullet, sections have a name and have a matching
###   set of brackets at the start and end of the section. Search for SECTION
###   (all uppercase) in the text.
###
### - Comments are always introduced by three leading hash signs. This is to
###   differentiate hash used in the script for commenting out code
###   sections temporarily from true comments, and also to aid searching
###   for hash characters used in the script for purposes other than comments,
###   such as the #{ and #} constructs mentioned above.
###
### - There are a number of variable naming rules (conventions) put in place
###   for:
###   - readability
###   - to differentiate script variables from environment variables
###   - to designate variables as global, local, function arguments,
###     function arguments representing passback (volatile) variables.
###
###   The rules are outlined here:
###
###   - Local variable names are preceded with '_' (underscore) so a local
###     variable for storing a birthday might be _birthday
###
###   - An extension of the '_' prefix rule for local variables is that
###     function "parameters" are prepended with '_arg_'. The reason parameters
###     is in quotes in the preceding sentence is that technically, function
###     parameters in bash script are named $1, $2, etc., but we copy those
###     values to variables at the beginning of the functions for readability
###     later in the functions. It's these variables that use the '_arg_'
###     prefix rule.
###
###   - Global variable names are preceded with 'g_' so a global variable
###     for storing a verbosity flag might be g_verbosity.
###
###   - Global variables that modify script behaviour are preceded with 'gscr_'.
###
###   - Script return values, although global, do not use the 'g_' rule, and
###     instead have the prefix 'RET_" with the remainder of the variable being
###     an uppercase descriptive string for the exit value.
###
###   - Command definitions also break from the 'g_' rule and are named
###     using the prefix 'cmd_' with the remainder of the variable being
###     the uppercase equivalent of the command you are defining, e.g,
###     you use '$cmd_RM' instead of 'rm'. See SECTION "Commands" for
###     more information.
###
###   - Variables are made read-only (constant) when possible. This is done
###     with the 'declare -r' or 'local -r' construct. Global read only
###     variables have names that are all uppercase, e.g., g_NULL.
###
###   - For variables that will be used to hold integer only values, they are
###     defined as such using the 'declare -i' or 'local -i' construct. There's
###     a catch to this though; when comparing integers for anything other than
###     equality, you must use the '-ge', '-gt', '-le' or '-lt' comparators and
###     not the '>' or '<' comparators. The latter will cause the comparison to
###     be done on the string value and not the integer value, so '2 > 17' would
###     be true while '2 -gt 17' would be false.
###
### - Functions names are preceded with 'fn_', so a function for clearing the
###   screen might be called 'fn_clearscreen'. You will also note that the open
###   bracket { and the close bracket } appear in column zero, i.e., as the
###   first character of the line. This is so the '[[' shortcut in vi will
###   work to find the beginning of the function you are in.
###
### - To differentiate '>' meaning 'greater than' (lexical comparison)
###   from '>' meaning 'redirect output to file', and to aid searching for
###   either explicitly, the former meaning will have a leading and trailing
###   space and the latter meaning (and its derivatives) will be immediately
###   followed by the file name with no intervening space. The same thing
###   will be done for '<' ('less than' or 'read from file') and its
###   derivatives.
###
### - There are several sed ($cmd_SED actually) lines where instead of the
###   usual forward slash ('/') as a delimiter, the tilde ('~') character is
###   used. This is legal sed, and gives us the benefit of being able to use
###   the forward slash in file path names without having to escape the slashes
###   with the backslash ('\') character. This means we can use the global
###   definitions for file and path names, rather than have to have specially
###   defined values. Let's make an example to clarify. Suppose we wanted to
###   change occurrences of "/var/log/" to "/var/oldlog/" in a file. Using
###   forward slash as our delimiter, we would have to write
###   sed "s/\/var\/log\//\/var\/oldlog\//". Using tilde as our delimiter
###   however, we can write sed "s~/var/log/~/var/oldlog/~", which is not only
###   more readable, but if we had a variable g_LOG defined as "/var/log/"
###   and another g_OLDLOG defined as "/var/oldlog/", we can use them in the
###   sed line like so: sed "s~$g_LOG~$g_OLDLOG~". This allows us to use our
###   global variables everywhere and not have to worry about manually updating
###   the sed lines, or maintaining two global variables for each path (one
###   defined as usual, and one defined with the forward slashes escaped.)
###
### - Script lines are limited to a maximum of 80 characters, where possible,
###   to aid readability, which results in easier maintenance of the script.
###   The following exceptions to this rule are permitted:
###   - If making a line meet this length limitation makes it LESS readable,
###     the rule is ignored as the overriding goal here is readability.
###   - Code that is called often, such as fn_chkargs and the logging
###     functions are allowed to cross the boundary for performance reasons.
###     Believe it or not, code that crosses a single line using the line
###     continuation character ('/') runs slightly slower. For code that is
###     called often, these slight delays add up. There is an additional
###     reason to allow the logging functions to cross the boundary, and
###     that is so developers can search complete error strings without
###     concern for words splitting across lines.
###
### - The construct '&>filepath' is used to redirect standard error (file
###   descriptor 2) and standard out (file descriptor 1) to the file
###   "filepath". The '&' and '>' must appear together with no space between,
###   so as to not be interpreted as "run this command in the background and
###   redirect stdout". In other words 'ls &>/dev/null' is not the same as
###   'ls & >/dev/null'
###
### - The $(command) construct is used rather than the `command` construct
###   to execute commands for the following reasons:
###   - There is support for bracket matching in most editors (such as the
###     % command in vi.)
###   - You don't have to use escape like you do on the back quote when
###     nesting, e.g., you can say $(command1 $(command2)) rather than
###     `command1 \`command2\``
###   - You don't have to escape lexical comparators '<' and '>'.
###
### - IMPORTANT! bash has a nasty habit of allowing local variables to a
###   function to be inherited by children. i.e., if fn_a() declares local
###   variable '_a', and fn_a() calls fn_b(), then '_a' will be in scope
###   within fn_b() and changes to it will be propagated back to fn_a().
###   Worse, if fn_b() also declares local variable '_a', then any changes
###   to '_a' within fn_b() will not be propagated back to fn_a(), which is
###   expected, except that if we use parameter dereferencing to set '_a'
###   within fn_b() *by reference* we would expect that it would be changes
###   within fn_a(), but in fact it's not! This causes a problem when we pass
###   in a passback variable to a function, and the name of the variable
###   happens to be the same as the name of the temporary variable used to
###   store the value we are gathering to later modify in the dereference.
###   We handle this by either including the function name in temporary
###   variable names, or by dereferencing the passed value directly and
###   not using temporary variables.
###
### - We use the [[ ]] test construct rather than the more common [ ]. The
###   main reasons we do this are:
###   - It has syntax and parameter checking, so you don't need to use quotes,
###     nor do you need to do things like comparing "X$var" to "Xval", you can
###     instead compare $var to val without any problems. This may seem trivial
###     at first, until you consider that the old style does not do this, and
###     you must always remember to protect the tests lest your code fail when
###     a value is null.
###   - Related to the preceding point, you can do simple existence tests by
###     saying [[ $var ]] rather than the less readable [ -n "X$var" ]
###   - It supports || and && within the test so it's more readable than the
###     -o and -a constructs.
###
### - Because many of the data files are XML formatted, and because we
###   sometimes have complex queries for these files, we use XPath queries
###   (with the tool xpathparse). XPath is a language for addressing parts
###   of an XML document, and is standardized as a W3C Recommendation. See
###   http://www.w3.org/TR/xpath and the Wikipedia entry for XPath.
###
### - You will see the terms "patch", "package", "UMD", and "RPM" used quite a
###   bit in this script, so let's clarify their meaning. A patch is expressed
###   by a UMD file, so the terms are often used interchangeably. It (that is,
###   the UMD or patch) is a collection of packages, where a package is nothing
###   more than an RPM file (so the term package and RPM are also used somewhat
###   interchangeably.)
###
### - Download and apply times (aonly, donly, apply) are expressed in the
###   following format: "Thu Jul 24 16:50:35 1969", specifically:
###   - Three character day of week (Mon, Tue, etc.)
###   - Three character month (Nov, Dec, etc.)
###   - One or two characters representing the day of the month
###   - The time in 24 hour format in the form HH:MM:SS
###   - Four characters representing the year.

### END-SECTION: Conventions, Notes ###########################################}


### SECTION: TODO #############################################################{

### This section contains documentation of general issues remaining outstanding
### with this script. The script itself also contains TODO notes where there is
### a specific issue with the script.
###
### - Come up with naming convention for all arguments passed to functions that
###   eval them (i.e., passback variables) to draw attention to the fact that
###   they are modified outside the function.
###
### - Revisit all calls to 'read' to see if/how error conditions are handled.
###
### - Make sure the M50R3 softinv agrees with the M50R2 softinv upon which
###   this was based, otherwise, we need to incorporate the changes.
###
### - See if we handle .sig files correctly.
###
### - Speedups: This script is too slow, so some things that need to be
###   investigated to see if it can be sped up are:
###   - See if the creation of the temporary directory could be changed to use
###     the same directory every time.
###   - Some functions don't use the passed in LINENO. Determine what these
###     functions are, and remove the extra parameter. This may only result
###     in a speedup if the value is assigned to another variable.

### END-SECTION: TODO #########################################################}


### SECTION: Global Variables #################################################{

### To differentiate script variables from environment variables, global
### variable names are preceded with 'g_' so a local variable for storing a
### birthday might be _birthday, and a global variable for storing a verbosity
### flag might be g_verbosity.
###
### Note that some global variables are special, in that they are designed
### to change the behaviour of the script and so are prepended with 'gscr_'
### instead of just 'g_'.

### If you add a new 'gscr_' value, be sure to check for its setting in
### fn_setup, and determine if it's a sane value.

### See documentation under fn_log() for explanation of g_LOG* values.
### See also the documentation for $gscr_DEBUG below.
declare -r -i g_LOGALWAYS=0     ### Will always log with this value, even
                                ###   if logging is off, i.e., even if
                                ###   $gscr_DEBUG = 0
declare -r -i g_LOGCOND=0       ### See documentation under fn_log() for an
                                ###   explanation of why $g_LOGALWAYS and
                                ###   $g_LOGCOND are set to the same value.
declare -r -i g_LOGVERBOSE=1    ### Will always log when logging is on,
                                ###   i.e., when $gscr_DEBUG != 0
declare -r -i g_LOGWARN=2
declare -r -i g_LOGINFO=9       ### Only log when maximum log verbosity enabled.

### New variable to turn off many of the debugging features of the script
declare -r -i gscr_ENABLE_GLOBAL_DEBUG=0

### $gscr_DEBUG is an integer that indicates the debug logging verbosity. To
### turn debug logging off, set $gscr_DEBUG to 0. Higher numbers produce less
### debug log output. Note that the value must be set to an integer between
### 0 and 9, or the script will exit with script error RET_SCRIPT_DEBUGINVALID.
### Simply copy and uncomment one of the following:
declare -r -i gscr_DEBUG=0                ### Log only $g_LOGALWAYS,
                                            ###   essentially turning logging
                                            ###   off for all but the most
                                            ###   serious messages.
# declare -r -i gscr_DEBUG=$g_LOGVERBOSE    ### Log ALL messages.
# declare -r -i gscr_DEBUG=$g_LOGWARN       ### Log only $g_LOGALWAYS,
                                            ###   $g_LOGWARN and $g_LOGINFO.
# declare -r -i gscr_DEBUG=$g_LOGINFO       ### Log only $g_LOGALWAYS
                                            ###   and $g_LOGINFO
#declare -r -i gscr_DEBUG=$g_LOGVERBOSE

### If $gscr_CHECKSIG is set to 'no', we don't check the signatures in the
### umd/uxd files. Normally, we want to check the signature of the umd/uxd
### files so the default behaviour is to check them but this conditional
### behaviour allows us to test with unsigned files during development. Note
### that the value must be set to 'yes' or 'no', or the script will exit with
### script error RET_SCRIPT_CHECKUMDSIGINVALID.
# declare -r gscr_CHECKSIG=yes
declare -r gscr_CHECKSIG=yes

declare -r g_VERSION="1.1.84" ### TODO how to get version # in code?
declare -r g_NULL=/dev/null
declare -r g_PROGPATH=$0
declare -r g_PROGNAME=$(basename $0)
declare -r g_PATCHDIR=/nn/patches
declare -r g_INFODIR=$g_PATCHDIR/info
declare -r g_READMEDIR=$g_INFODIR/readme
declare -r g_PATCHTMPDIR=$g_PATCHDIR/tmp
declare -r g_RPMCOMP=$g_PATCHDIR/rpmcomp.txt
declare -r g_INVENTORYLOG="$g_INFODIR/softwareinventory.log"
declare -r g_PATCHCACHE="$g_INFODIR/cache.log"
declare -r g_LOGFILE="/var/log/softwareupdates.log"
declare -r g_LOGFILE_BASENAME=$(basename $g_LOGFILE)
declare -r g_PATCHHISTORY="$g_INFODIR/history.log"
declare -r g_LOG=/var/log/softinv.log
declare -r g_WGETLOG=$g_INFODIR/wget.log
declare -r g_RBACKLOG=$g_PATCHDIR/rback.log
declare -r g_RPMLOG=$g_INFODIR/rpm.log
### TODO there is only one copy of g_LOCATIONLOG file. This will be a
### problem if you have scheduled applications from different locations.
declare -r g_LOCATIONLOG=$g_INFODIR/location.log
declare -r g_SMBCLIENTLOG=$g_INFODIR/smbclient.log
declare -r g_ACTIVESTATUS=$g_INFODIR/active.status
declare -r g_BLOCKINGFLAG=$g_PATCHDIR/blocking_flag
### TODO there is only one copy of g_ACTIVEPATCH file. This could create
### concurrency problems.
declare -r g_ACTIVEPATCH=$g_INFODIR/active
declare -r g_RUNNINGPKG=$g_INFODIR/running_package

### This is not actually a real file, but is used as a lock file to prevent
### concurrent access to the scheduler.
declare -r g_SCHEDULER=$g_INFODIR/scheduler

### Used to handshake with the --status instance of softinv when the software
### update has applied successful and just before the system is rebooted
declare -r g_APPLY_SUCCESS_FLAG=$g_PATCHTMPDIR/applysuccess.status

### Be careful when modifying code that affects the $g_CRONTAB_LOG file.
### The format of the file is important for two reasons:
### (1) It's a crontab file, so must be conformant to crons rules.
### (2) It's modified in various places in this script using sed, so the
###     format of the lines must be matched by the sed lines, else the sed
###     commands would break.
###
### The crontab file may contain comment lines, which start with '#', or
### cron job entries, which are in the following format:
###   min hour DOM month DOW cmd
###    |   |    |    |    |   |
###    |   |    |    |    |   +- command to be executed
###    |   |    |    |    +----- day of week (0-6) (Sunday=0)
###    |   |    |    +---------- month (1-12)
###    |   |    +--------------- day of month (1-31)
###    |   +-------------------- hour (0-23)
###    +------------------------ min (0-59)
###
### - A '*' in the value field above means all legal values as in braces for
###   that column.
### - The value column can have a '*' or a list of elements separated by commas.
### - An element is either a number in the ranges shown above or two numbers
###   in the range separated by a hyphen (meaning an inclusive range).
### - The specification of days can be made in two fields: month day and
###   weekday. If both are specified in an entry, they are cumulative meaning
###   both of the entries will get executed .
declare -r g_CRONTAB_LOG=$g_INFODIR/crontab.log

### The tool $cmd_RPMCOMPARE compares RPM versions given two RPM names,
### RPM_L and RPM_R. It is documented to return:
###   -1    RPM_L older than RPM_R
###    0    RPM_L = RPM_R
###    1    RPM_L more recent (newer) than RPM_R
### -100    version comparison failed, or bad
### but negative shell return values may be interpreted differently, so
### these values will be massaged by a call to fn_massage_ret() before
### they are used.
### Note also that if either RPM_L or RPM_R includes the .$g_arch.rpm
### extension, then both RPM_L and RPM_R must includes the .$g_arch.rpm
### extension, otherwise, you will get 255 or 1 when you should get 0.
### TODO: Note that $cmd_RPMCOMPARE does not correctly handle RELEASE at
### this time.
declare -i g_RPMCOMPARE_RET_OLDER=-1
declare -i g_RPMCOMPARE_RET_EQUAL=0
declare -i g_RPMCOMPARE_RET_NEWER=1
declare -i g_RPMCOMPARE_RET_ERR=-100

### g_usbdev and g_arch get set in fn_setup()
declare g_usbdev=
declare g_arch=

### g_tmp_dir gets set in fn_make_temp_dir(). Not to be confused
### with g_PATCHTMPDIR, the directory indicated by $g_tmp_dir gets
### generated at run time whereas $g_PATCHTMPDIR is a fixed (read-only)
### declaration.
declare g_tmp_dir=

### Rather than simply exit $val, we set g_exitval=$val, then exit $g_exitval.
### Why? So the fn_trap exit handler will always pass back the correct value.
declare -i g_exitval=0

### Extension for file locks.
declare -r g_LOCK=".lock"

### Although testing has shown some versions of bash have 64 bit signed
### integers, bash documentation states they are 32 bits signed, so we
### will use 2147483647, or 0x7FFFFFFF as the top of the range.
declare -r -i g_INTMAX=2147483647

### g_gutv_DOWNCASE, g_gutv_UPCASE and g_gutv_RAW are for fn_get_umd_tag_value
declare -r -i g_gutv_DOWNCASE=-1
declare -r -i g_gutv_UPCASE=1
declare -r -i g_gutv_RAW=0

### There are a number of times we need a variable to satisfy function calls,
### but the variables value is of no interest to us. g_dummy is for that.
declare g_dummy=

### When the script has an application error, i.e., it exits with a
### RET_SCRIPT_* value (explained below), we want to preface the error
### message to indicate it's an application error. That's what
### $g_SCRIPTERR_PREFIX is for. Similarly, we have $g_RUNTIMEERR_PREFIX
### for runtime errors.
declare -r g_SCRIPTERR_PREFIX="APPLICATION ERROR:"
declare -r g_RUNTIMEERR_PREFIX="RUNTIME ERROR:"

### Some functions need to be able to have certain behaviours forced
### conditionally by way of function parameters. These definitions
### are used to express the values for such cases in a more readable
### way than simply passing YES/NO or 0/1.
declare -r g_NOFORCE=NoForce
declare -r g_FORCE=Force

### New reboot Metadata is been implemented in the UMD files after this date.
### so all the new patches released after this date is checked for the new meta data 
### for smart reboot display.
declare -r g_PATCH_REL_DATE="2008/04/18"

### END-SECTION: Global Variables #############################################}


### SECTION: Return Codes #####################################################{

### Return codes (also used as exit values) are defined script global as
### RET_NAME where NAME is a descriptive string for the exit value. Make
### sure to only use values in the range 0 to 256. All return codes must
### be unique.

### EM will process values of 2 or more as errors. TODO explain better.

### You can see the descriptions in fn_errors(), or you can run the script
### with --errors to itemize the return values.
### IMPORTANT! fn_errors() relies on the format of these declarations. It
### looks for lines in this script of the form 'declare -r -i RET_X=Y',
### where:
### - 'X' is the name of the value.
### - 'Y' is the numerical value it is set to.
### - The line starts in the leftmost column.
### - The line has no extraneous spaces

### RET_OK is used to indicate success. Most of the other return codes
### indicate some kind of error condition.
declare -r -i RET_OK=0

declare -r -i RET_NOCOMPONENTS=1
declare -r -i RET_CMD_MKTEMP=2
declare -r -i RET_FILES_NOLIST=3
declare -r -i RET_MAKE_TEMP_DIR=4
declare -r -i RET_NOTROOT=5
declare -r -i RET_NOTSOURCEABLE=6
declare -r -i RET_UNKNOWN_ARCH=7

declare -r -i RET_USAGE=10 ### do not change for legacy reasons
declare -r -i RET_FTP=11
declare -r -i RET_SAMBA=12
declare -r -i RET_APPLY=13
declare -r -i RET_DOWNLOAD=14
declare -r -i RET_DONLY=15
declare -r -i RET_AONLY=16
declare -r -i RET_RBACK=17
declare -r -i RET_HTTP=18
declare -r -i RET_USB=19
declare -r -i RET_EM=20
declare -r -i RET_BUILD_LIST=21
declare -r -i RET_DATE_TZ=22
declare -r -i RET_FILES_NO_TAGVALUE=23

### NOTE: 24 through 37 inclusive are reserved for multi-selection.

declare -r -i RET_RSCHED_GEN=38

declare -r -i RET_SCHED_GEN=39
declare -r -i RET_SCHED_DLAFTERAPPLY=40
declare -r -i RET_SCHED_INPAST=41
declare -r -i RET_SCHED_TRANS2SHORT=42
declare -r -i RET_SCHED_ALREADYSCHED=43
declare -r -i RET_SCHED_INTRNLERROR=44

declare -r -i RET_MSCHED_GEN=45
declare -r -i RET_MSCHED_DLAFTERAPPLY=46
declare -r -i RET_MSCHED_INPAST=47
declare -r -i RET_MSCHED_TRANS2SHORT=48
declare -r -i RET_MSCHED_INTRNLERROR=49
declare -r -i RET_MSCHED_PATCHMISMATCH=50

### Runtime return codes start at $RETSTART_RUNTIME. These codes indicate
### something in the script is behaving in an unexpected manner, but they
### are not necessarily programmer (i.e., application) errors. An example
### is an expected command on the system was not found.
### Note that value 100 has already been declared at the top of the script,
### as RET_RUNTIME_NOECHO=100. It is reserved for problems with echo (see
### documentation on cmd_ECHO elsewhere).
### NOTE: 104 and 105 are reserved for multi-selection.
declare -r -i RETSTART_RUNTIME=100 ### Start of runtime errors
declare -r -i RET_RUNTIME_NOINDEX=101
declare -r -i RET_RUNTIME_FAILENCRYPT=102
declare -r -i RET_RUNTIME_CMDNOEX=103
declare -r -i RET_RUNTIME_MAIN_PROTO_BADMETHOD=106
declare -r -i RET_RUNTIME_MAIN_SELECT_BADMETHOD=107
declare -r -i RET_RUNTIME_SED_FAILED=108
declare -r -i RET_RUNTIME_RPMCOMPARE_FAILED=109
declare -r -i RET_RUNTIME_NOPACKAGES=110

### Script return codes start at $RETSTART_SCRIPT. These codes indicate
### something in the script is behaving in an unexpected (and not accounted
### for) manner, such as calling a function with an incorrect number of
### arguments. These generally indicate a change in the script has broken
### some existing behaviour or introduced new behaviour that negates
### previously correct assumptions, in other words, they are usually
### introduced by the programmer.
### NOTE: 210 and 211 are reserved for multi-selection.
declare -r -i RETSTART_SCRIPT=200 ### Start of application errors
declare -r -i RET_SCRIPT_BADARGS=200
declare -r -i RET_SCRIPT_MAKE_TEMP_DIR_NON_REENTRANT=201
declare -r -i RET_SCRIPT_PARSE_PROTOCOL=202
declare -r -i RET_SCRIPT_FNLOG_BADARGS=203
declare -r -i RET_SCRIPT_FNEXIT_BADARGS=204
declare -r -i RET_SCRIPT_DEBUGINVALID=205
declare -r -i RET_SCRIPT_CHECKUMDSIGINVALID=206
declare -r -i RET_SCRIPT_GETUMDTAGVAL_BADARGS=207
declare -r -i RET_SCRIPT_DECLMISMATCH=208
declare -r -i RET_SCRIPT_RECURSIVELOCK=209

### END-SECTION: Return Codes #################################################}


### SECTION: Script setup #####################################################{

### The default $PATH variable for the BCM (when called by the provider)
### contains (in order) /sbin, /usr/sbin, /bin, /usr/bin and /usr/X11R6/bin.
### We need some additional paths so we will creat a $PATH variable here.
### Note that we could simply build upon the existing $PATH variable by
### checking for the existence of each of the required paths, adding them as
### needed, but in the interest of execution efficiency, we define the value
### of $PATH absolutely.
PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/X11R6/bin:/nn/sbin:/nn/bin:/usr/local/bin:/opt/bin:/opt/sbin

### END-SECTION: Script setup #################################################}


### SECTION: Commands #########################################################{
### Commands are named in the form cmd_X, where X is an uppercase string
### that describes the command. For instance, the ls command is named cmd_LS.
### We could just test that the commands exist and use them natively, but
### setting the cmd_X variables lets us change the behaviour of command X
### globally by changing a single line of the script. It also gets rid of
### the need to search the $PATH variable for the executable.
### TODO: See if the dereference of a variable is in fact faster than
### searching the path for the executable.

### Note that there is no cmd_ECHO. If 'echo' is not present, we can't build
### $PATH properly (as it's done above) and then we couldn't search $PATH to
### find the 'echo' command! In other words, 'echo' presents a chicken-and-egg
### scenario. It's true that we could still use 'which' to try to find the
### 'echo' command, but if 'echo' is missing we have to jump through hoops to
### even report it, so the most we do is test for it and if it's missing, we
### simply return a fatal error (exit with value $RET_RUNTIME_NOECHO). We
### could use 'print' or some other facility to report the condition, but
### what if it's missing too? Suffice it to say, the best we can do is do a
### simple test for 'echo' and if it's missing, we exit with a fatal error.

### OK, let's build up the commands. For each of the items in the list
### below, a corresponding cmd_X will be created where X is the uppercase
### equivalent of the element, with any dashes removed. For example,
### SomeCommand would generates cmd_SOMECOMMAND while command-with-dashes
### would generate cmd_COMMANDWITHDASHES.
###
### Note that we don't have to worry about the following commands as they
### are bash builtins: basename, exec, exit, eval, popd, printf, pushd, read,
### trap, wait.

declare -r cmd_ADDNNUDIAGLOG=/nn/bin/AddNnuDiagLog
declare -r cmd_BASE64=/nn/bin/base64
declare -r cmd_BASH=/bin/bash
declare -r cmd_CAT=/bin/cat
declare -r cmd_CHMOD=/bin/chmod
declare -r cmd_CHOWN=/bin/chown
declare -r cmd_CFSGETCODE=/nn/bin/cfsgetcode
declare -r cmd_CFSSERVER=/nn/sbin/cfsserver
declare -r cmd_CP=/bin/cp
declare -r cmd_CPIO=/opt/bin/cpio
declare -r cmd_CRONTAB=/usr/bin/crontab
declare -r cmd_CUT=/bin/cut
declare -r cmd_DATE=/bin/date
declare -r cmd_DD=/bin/dd
declare -r cmd_DU=/usr/bin/du
declare -r cmd_EGREP=/bin/egrep
declare -r cmd_EXPR=/bin/expr
declare -r cmd_GAPCYPERFILE=/nn/sbin/GapCyperFile
declare -r cmd_GAWK=/opt/bin/gawk
declare -r cmd_GREP=/bin/grep
declare -r cmd_LS=/bin/ls
declare -r cmd_MKTEMP=/bin/mktemp
declare -r cmd_MKDIR=/bin/mkdir
declare -r cmd_MONIT=/opt/sbin/monit
declare -r cmd_MONITGUARD=/nn/sbin/MonitGuard
declare -r cmd_MOUNT=/bin/mount
declare -r cmd_MOUNTUSB=/nn/sbin/mountusb
declare -r cmd_MV=/bin/mv
declare -r cmd_NICE=/bin/nice
declare -r cmd_PROCESSCONTROL=/nn/bin/processcontrol
declare -r cmd_PS=/bin/ps
declare -r cmd_RM=/bin/rm
declare -r cmd_RPM=/usr/local/bin/rpm
declare -r cmd_RPM2CPIO=/usr/local/bin/rpm2cpio
declare -r cmd_RPMCOMPARE=/nn/bin/rpmcompare
declare -r cmd_SED=/bin/sed
declare -r cmd_SHUTDOWN=/sbin/shutdown
declare -r cmd_SMBCLIENT=/opt/bin/smbclient
declare -r cmd_SORT=/bin/sort
declare -r cmd_SOFTINV=/nn/bin/softinv
declare -r cmd_SYNC=/bin/sync
declare -r cmd_TAR=/bin/tar
declare -r cmd_TEE=/bin/tee
declare -r cmd_TOUCH=/bin/touch
declare -r cmd_TR=/usr/bin/tr
declare -r cmd_UMD_SIGN=/nn/bin/umd_sign
declare -r cmd_UMOUNTUSB=/nn/sbin/umountusb
declare -r cmd_UNAME=/bin/uname
declare -r cmd_WC=/opt/bin/wc
declare -r cmd_WGET=/usr/bin/wget
declare -r cmd_XPATHPARSE=/nn/sbin/xpathparse

### TODO: Determine why this is not /nn/bin/strtree
declare -r cmd_STRTREE=$g_PATCHDIR/strtree

### END-SECTION: Commands #####################################################}


################################################################################
### Purpose: This function formats and logs output to the log file.
### Args:    $1 min debug level. The message will be logged if the value is
###             $g_LOGALWAYS, or is greater than or equal to $gscr_DEBUG
###          $2 calling $FUNCNAME (set to "MAIN" if not called from
###             within a function)
###          $3 calling $LINENO
###          $4 text to display
### Returns: 0
###          May exit with $RET_SCRIPT_FNLOG_BADARGS if incorrect number of
###          arguments passed in.
### Note:    Occasionally there is a block of code that is wrapped in a
###          condition on the value of $gscr_DEBUG, and there are calls to
###          fn_log within that block. So that the threshold only has to be
###          changed in one place, those calls to fn_log will set the min
###          debug level to g_LOGALWAYS. Because the block itself is
###          conditional on the $gscr_DEBUG level, there is no danger of
###          extraneous calls to fn_log. In order to highlight those cases,
###          rather than using g_LOGALWAYS, we use g_LOGCOND, which is in
###          fact the same as g_LOGALWAYS.
fn_log()
{

    if [[ $gscr_ENABLE_GLOBAL_DEBUG -eq 1 ]]
    then
      ### We can't call fn_chkargs here because it uses fn_log, so we may end up
      ### with a recursive call.
      if [[ $# != 4 ]]
      then #{
        ### We need to send the output to file descriptor 6, which is where
        ### stdout was preserved to when I/O redirection was turned on as well
        ### as sending it to $g_LOG. Note we don't check $gscr_DEBUG since no
        ### matter what the value, this is an error message and so must be sent
        ### to the log.
        echo "$g_SCRIPTERR_PREFIX $FUNCNAME:$LINENO incorrect number of parameters (passed [$*]), exiting with RET_SCRIPT_FNLOG_BADARGS=$RET_SCRIPT_FNLOG_BADARGS" | $cmd_TEE -a $g_LOG >&6
        g_exitval=$RET_SCRIPT_FNLOG_BADARGS
        exit $g_exitval
      fi #}

      ### Note in this function we don't assign the parameters to variables.
      ### This is for performance reasons, as this method is called frequently.

      ### We log if:
      ###   $1 = $g_LOGALWAYS
      ### -OR-
      ###   $1 greater than or equal to $gscr_DEBUG -AND- $gscr_DEBUG != 0
      if [[       $1          ==  $g_LOGALWAYS    \
          ||  $1          -ge $gscr_DEBUG     \
          &&  $gscr_DEBUG !=  0               ]]
      then #{
        ### Now generate the output. Because of I/O redirection, this will
        ### end up in $g_LOG. $$ is the process id.
        printf "%5.5d %s <%d:%s %s\n" $$ $($cmd_DATE '+%R:%S') $3 $2 "$4"

        ### Since stdout and stderr are redirected to a file, we want to
        ### flush any output.
        $cmd_SYNC
      fi #}
    fi

    return 0
}

################################################################################
### Purpose: This function calls fn_log and exits the script with the fatal
###          error code.
### Args:    $1 calling $FUNCNAME (set to "MAIN" if not called from
###             within a function)
###          $2 calling $LINENO
###          $3 return value for exiting the code.
###          $4 text to display
### Returns: nothing, exits with passed exit value.
fn_exit()
{
    ### We can't call fn_chkargs here because it uses fn_log, so we may end up
    ### with a recursive call.
    if [[ $# != 4 ]]
    then #{
        ### We need to send the output to file descriptor 6, which is where
        ### stdout was preserved to when I/O redirection was turned on as well
        ### as sending it to $g_LOG. Note we don't check $gscr_DEBUG since no
        ### matter what the value, this is an error message and so must be sent
        ### to the log.
        echo "$g_SCRIPTERR_PREFIX $FUNCNAME:$LINENO incorrect number of parameters, exiting with RET_SCRIPT_FNEXIT_BADARGS=$RET_SCRIPT_FNEXIT_BADARGS" | $cmd_TEE -a $g_LOG >&6
        g_exitval=$RET_SCRIPT_FNEXIT_BADARGS
        exit $g_exitval
    fi #}

    local -r    _arg_exit_funcname=$1
    local -r -i _arg_exit_lineno=$2
    local -r    _arg_exit_displaytext=$4
    g_exitval=$3

    if [[ $g_exitval -ge $RETSTART_SCRIPT ]]
    then #{
        fn_log $g_LOGALWAYS $_arg_exit_funcname $_arg_exit_lineno "$g_SCRIPTERR_PREFIX $_arg_exit_displaytext, exit script with $g_exitval"
    elif [[ $g_exitval -ge $RETSTART_RUNTIME ]]; then #}{
        fn_log $g_LOGALWAYS $_arg_exit_funcname $_arg_exit_lineno "$g_RUNTIMEERR_PREFIX $_arg_exit_displaytext, exit script with $g_exitval"
    elif [[ $g_exitval -ne $RET_USAGE ]]; then #}{
        fn_log $g_LOGALWAYS $_arg_exit_funcname $_arg_exit_lineno "$_arg_exit_displaytext, exit script with $g_exitval"
    fi #}

    exit $g_exitval
}

################################################################################
### Purpose: At the beginning of the functions, the number of args are checked
###          using this function. If there is an error, we report it.
### Example: We might make the following calls:
###          fn_chkargs $FUNCNAME $LINENO $# 2 2 "name, phone"
###          fn_chkargs $FUNCNAME $LINENO $# 2 3 "name, phone, cell (optional)"
### Args:    $1 calling $FUNCNAME
###          $2 calling $LINENO
###          $3 number_of_args (as $#)
###          $4 expected_min_number_of_args
###          $5 expected_max_number_of_args, $g_INTMAX if no maximum
###          $6 expected_args_string
### Returns: 0 on success
###          On failure, exits script with $RET_SCRIPT_BADARGS
fn_chkargs()
{
    ### Function fn_chkargs() expects 6 arguments.
    [[ $# != 6 ]] && fn_exit $FUNCNAME $LINENO RET_SCRIPT_BADARGS "$FUNCNAME takes 6 arguments"

    local -r    _arg_chkargs_funcname=$1
    local -r -i _arg_chkargs_lineno=$2
    local -r -i _arg_chkargs_number_of_args=$3
    local -r -i _arg_chkargs_min_number_of_args=$4
    local -r -i _arg_chkargs_max_number_of_args=$5

    [[ $_arg_chkargs_min_number_of_args -gt $_arg_chkargs_max_number_of_args ]] && fn_exit $FUNCNAME $LINENO RET_SCRIPT_BADARGS "_arg_chkargs_min_number_of_args=\"$_arg_chkargs_min_number_of_args\" is greater than _arg_chkargs_max_number_of_args=\"$_arg_chkargs_max_number_of_args\""

    local -r _arg_expected_args_string=$6

    [[      $_arg_chkargs_number_of_args -ge $_arg_chkargs_min_number_of_args \
        &&  $_arg_chkargs_number_of_args -le $_arg_chkargs_max_number_of_args ]] \
            && return 0

    if [[       $_arg_chkargs_number_of_args     != 0 \
            &&  $_arg_chkargs_min_number_of_args == 0 \
            &&  $_arg_chkargs_max_number_of_args == 0 ]]
    then #{
        fn_exit $FUNCNAME $LINENO RET_SCRIPT_BADARGS "$_arg_chkargs_funcname:$_arg_chkargs_lineno takes no args but $_arg_chkargs_number_of_args was passed"
    elif [[ $_arg_chkargs_number_of_args -lt $_arg_chkargs_min_number_of_args ]]; then #}{
        fn_exit $FUNCNAME $LINENO RET_SCRIPT_BADARGS "$_arg_chkargs_funcname:$_arg_chkargs_lineno takes at least $_arg_chkargs_min_number_of_args arguments but $_arg_chkargs_number_of_args was passed, expected $_arg_expected_args_string"
    elif [[ $_arg_chkargs_number_of_args -gt $_arg_chkargs_max_number_of_args ]]; then #}{
        fn_exit $FUNCNAME $LINENO RET_SCRIPT_BADARGS "$_arg_chkargs_funcname:$_arg_chkargs_lineno takes at most $_arg_chkargs_max_number_of_args arguments but $_arg_chkargs_number_of_args was passed, expected $_arg_expected_args_string"
    else #}{
        ### This else is impossible. Why? Because tests have already
        ### been done showing $_arg_chkargs_number_of_args is not in
        ### the range $_arg_chkargs_min_number_of_args to
        ### $_arg_chkargs_max_number_of_args (inclusive), and tests
        ### have also already been done to see if $_arg_chkargs_number_of_args
        ### is outside the range $_arg_chkargs_min_number_of_args to
        ### $_arg_chkargs_max_number_of_args. We add this else to ensure
        ### no one changes the algorithm and breaks the code.
        fn_exit $FUNCNAME $LINENO RET_SCRIPT_BADARGS "an algorithm change has broken the script"
    fi #}
}

################################################################################
### Purpose: This function seems simple at first. Its purpose is to simply
###          "say", i.e., echo things. So why not just use echo then? Well
###          there's two reasons. First, this script has stdout (and stderr)
###          redirected to a log file, so if we simply use echo, this script
###          will send the output to the log file. This function sends the
###          output then to the log file, but also to the preserved stdout
###          vector, so we can still "echo" things to the non redirected
###          stdout. It also formats the output differently for the log file
###          than for stdout.
### Args:    $1 calling $FUNCNAME (set to "MAIN" if not called from
###             within a function)
###          $2 calling $LINENO
###          $3 text to display
### Returns: 0
fn_say()
{
    fn_chkargs $FUNCNAME $LINENO $# 3 3 "FUNCNAME, LINENO, display_text"

    ### Note in this function we don't assign the parameters to variables.
    ### This is for performance reasons, as this method is called frequently.
    ### Because of I/O redirection, this output will end up in $g_LOG. $$ is
    ### the process id.

    if [[ $gscr_ENABLE_GLOBAL_DEBUG -eq 1 ]]
    then
        printf "%5.5d %s %s:%d stdout> %s\n" $$ $($cmd_DATE '+%R:%S') $1 $2 "$3"
    fi

    ### We also send the output unformatted to file descriptor 6,
    ### which is where stdout was preserved to when I/O redirection was
    ### turned on.
    echo $3 >&6

    ### Since stdout and stderr are redirected to a file, we want to flush any
    ### output.
    $cmd_SYNC

    return 0
}

################################################################################
### Purpose: Executables and functions may return integer values that get
###          reinterpreted. For instance, for some versions of bash, a
###          return value of -1 is interpreted as 255. This method allows
###          the script to determine what the "massaged" value is. You call
###          it with the calling line number and the value to massage, and
###          it will return the massaged value.
###          Sometimes, return negative values
### Args:    $1 calling $LINENO.
###          $2 value to return for massage.
### Returns: Massaged value.
fn_massage_ret()
{
    fn_chkargs $FUNCNAME $LINENO $# 2 2 "LINENO, retval"

    return ${!2}
}

################################################################################
### Purpose: Locks a file against concurrent access. Does this by creating a
###          file with the same name as the file we want to lock with $g_LOCK
###          appended to the name. That file contains the process id of the
###          instance of this script that locked it. It can also be used for
###          creating a lock against concurrent behaviour. In this case, pass
###          a fake but unique file name which again will be used to create a
###          lock. You can see an example of this latter usage with the "file"
###          $g_SCHEDULER.
### Args:    $1 calling $LINENO
###          $2 name of file to lock.
### Returns: 0 once file is locked.
fn_lockfile()
{
    fn_chkargs $FUNCNAME $LINENO $# 2 2 "LINENO, filename"

    ### To ease cleanup, all the lock files are created in
    ### directory $g_PATCHTMPDIR.
    local -r _arg_lockfilename=$g_PATCHTMPDIR/$(basename $2)$g_LOCK

    ### If lock file doesn't exist, we simply create it and we're done.
    ### The file contains the process id of this script instance.
    if [[ ! -f $_arg_lockfilename ]]
    then #{
        echo $$ > $_arg_lockfilename
        return 0
    fi #}

    ### Lock file exists, read the process id from it.
    local _lockfile_pid=
    read _lockfile_pid <$_arg_lockfilename

    ### We don't currently support nesting of locks with the same pid.
    ### i.e., if we already locked the file, it means there is an
    ### application error.
    [[ $_lockfile_pid == $$ ]] && fn_exit $FUNCNAME $LINENO RET_SCRIPT_RECURSIVELOCK "nesting of calls to $FUNCNAME on the same file ($_arg_lockfilename) not permitted"

    ### If the process id read is an instance of this script, we wait for
    ### the script to exit. If it's not, we can ignore it as the lock is
    ### stale, i.e., it didn't get cleaned up on exit of a prior instance
    ### of this script, and we will overwrite it in subsequent code.
    while [[ $($cmd_PS --pid $_lockfile_pid | $cmd_GREP "$g_PROGNAME" 2>/dev/null) ]]
    do #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Waiting for process $_lockfile_pid to release lock file $_arg_lockfilename"
        sleep 1
        ### Re-read the lockfile because it could be removed but the PID
        ### could stay around for a long time (especially if we are doing
        ### an apply)
        _lockfile_pid=
        read _lockfile_pid <$_arg_lockfilename
        if [[ ! $_lockfile_pid ]]; then
          break
        fi

    done #}

    ### OK, now we can create our lock.
    echo $$ > $_arg_lockfilename

    return 0
}

################################################################################
### Purpose: Unlocks a file previously locked with fn_lockfile().
### Args:    $1 calling $LINENO
###          $2 name of file to unlock.
### Returns: 0
fn_unlockfile()
{
    fn_chkargs $FUNCNAME $LINENO $# 2 2 "LINENO, filename"

    ### To ease cleanup, all the lock files are created in
    ### directory $g_PATCHTMPDIR.
    local -r _arg_unlockfilename=$g_PATCHTMPDIR/$(basename $2)$g_LOCK

    ### If the lock file doesn't exist, we don't care why (since our job was
    ### to remove it) so we just return.
    [[ ! -e $_arg_unlockfilename ]] && return 0

    ### If we get to here, the lock file exists. We try to remove it and
    ### check the return value of the remove command. We do that rather
    ### than test to see if the file exists, because the file may have
    ### been created by a new instance of this script--that's the whole
    ### point of the lock file--it gets created when a lock is needed.
    ### So, we'll try to remove the file, then check the return value
    ### of the remove command, and if that indicates success, we know
    ### we removed the file, so we return.
    $cmd_RM -f $_arg_unlockfilename &>$g_NULL && return 0

    ### OK, if we get here, the remove failed. Let's check to see if the
    ### lock file is present. If it's not, we don't care why, we're happy
    ### it's gone, so we just return.
    [[ ! -e $_arg_unlockfilename ]] && return 0

    ### OK, if we get to here, it means the lock file still exists,
    ### despite our attempt to remove it. All we can do is log the
    ### issue and return.
    fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Unable to remove lock file $_arg_unlockfilename, skipping attempt to remove"

    return 0
}

################################################################################
### Purpose: Creates temporary directory and sets g_tmp_dir. May not be called
###          again until g_tmp_dir is removed and variable g_tmp_dir is cleared;
###          will exit with RET_SCRIPT_MAKE_TEMP_DIR_NON_REENTRANT if
###          you try to do so.
### Args:    $1 calling $LINENO
### Returns: 0 on success
###          Exits with RET_MAKE_TEMP_DIR on failure to make
###          temporary directory.
###          Exits with RET_SCRIPT_MAKE_TEMP_DIR_NON_REENTRANT if
###          fn_make_temp_dir() is called redundantly.
### Note:    Sets global g_tmp_dir
fn_make_temp_dir()
{
    fn_chkargs $FUNCNAME $LINENO $# 1 1 "LINENO"

    [[ $g_tmp_dir ]] && fn_exit $FUNCNAME $LINENO RET_SCRIPT_MAKE_TEMP_DIR_NON_REENTRANT "$g_tmp_dir already set"

    ### Because we need to check the value of $?, we can't combine the local
    ### declaration with the call.
    local _make_temp_dir_tmp=
    _make_temp_dir_tmp=$($cmd_MKTEMP -q -d /tmp/$g_PROGNAME.XXXXXX)

    [[ $? != 0 ]] && fn_exit $FUNCNAME $LINENO RET_MAKE_TEMP_DIR "$cmd_MKTEMP Problem creating temporary directory"

    g_tmp_dir=$_make_temp_dir_tmp

    return 0
}

################################################################################
### Purpose: Creates temporary file and sets passback value.
### Args:    $1 calling $LINENO
###          $2 passback variable for filename
### Returns: 0 on success
###          Exits with RET_CMD_MKTEMP on failure to make
###          temporary file.
fn_make_temp_file()
{
    fn_chkargs $FUNCNAME $LINENO $# 2 2 "LINENO, passback_filename"
    local -r _arg_passback_filename=$2
    eval "${_arg_passback_filename}=\"\""

    ### Because we need to check the value of $?, we can't combine the local
    ### declaration with the call.
    local _make_temp_file_tmpfile=
    _make_temp_file_tmpfile=$($cmd_MKTEMP -q /tmp/$g_PROGNAME.XXXXXX)
    [[ $? != 0 ]] && fn_exit $FUNCNAME $LINENO RET_CMD_MKTEMP "$cmd_MKTEMP Problem creating temporary file"

    eval "${_arg_passback_filename}=\"${_make_temp_file_tmpfile}\""

    return 0
}

################################################################################
### Purpose: Creates directory and sets permissions.
### Args:    $1 calling $LINENO
###          $2 directory to make.
###          $3 permissions
### Returns: 0
fn_mkdir_perms()
{
    fn_chkargs $FUNCNAME $LINENO $# 3 3 "LINENO, dirname, permissions"

    local -r _arg_dirname=$2
    local -r _arg_perms=$3

    ### TODO test that directory starts with a '/'.

    ### Make the directory.
    $cmd_MKDIR -p $_arg_dirname &>$g_NULL

    ### Given a directory of for example /nn/patches/tmp, this will break it
    ### down into /nn, then /nn/patches and then /nn/patches/tmp and chmod
    ### each directory as indicated by _arg_perms.

    local    _dir_component=
    local -i _depth=1

    while [[ $_dir_component != $_arg_dirname ]]
    do #{
        ((_depth++))
        _dir_component=$(echo $_arg_dirname | cut -d'/' -f1-$_depth)
        $cmd_CHMOD $_arg_perms $_dir_component &>$g_NULL
    done #}

    return 0
}

################################################################################
### Purpose: Simplifies the code where we want to cat a file to stdout
###          and optionally display it in the log.
### Args:    $1 calling $LINENO
###          $2 loglevel
###          $3 file to cat to.
### Returns: 0
fn_cat()
{
    fn_chkargs $FUNCNAME $LINENO $# 3 3 "LINENO, loglevel, filename"

    local -r -i _arg_catfile_calling_lineno=$1
    local -r -i _arg_catfile_loglevel=$2
    local -r    _arg_catfile_filename=$3

    if [[ $gscr_DEBUG == $g_LOGALWAYS || $_arg_catfile_loglevel -ge $gscr_DEBUG ]]
    then #{
        ### Capture the output to $g_LOG but also send it to stdout, which
        ### is file descriptor 6 due to I/O redirection.
        fn_log $g_LOGCOND $FUNCNAME $LINENO "<$_arg_catfile_calling_lineno Dumping output of $_arg_catfile_filename to log"
        $cmd_CAT $_arg_catfile_filename | $cmd_TEE -a $g_LOG >&6
        fn_log $g_LOGCOND $FUNCNAME $LINENO "<$_arg_catfile_calling_lineno Output of $_arg_catfile_filename dumped to log"
    else #}{
        ### Send output to stdout, which is file descriptor 6 due
        ### to I/O redirection.
        $cmd_CAT $_arg_catfile_filename >&6
    fi #}

    return 0
}

################################################################################
### Purpose: Calls $cmd_MONIT
### Args:    $1 calling $LINENO
### Returns: 0
fn_call_monit()
{
    fn_chkargs $FUNCNAME $LINENO $# 1 1 "LINENO"

    ### We need to send the output to file descriptor 6, which is where
    ### stdout was preserved to when I/O redirection was turned on as
    ### well as conditionally sending it to $g_LOG
    if [[ $gscr_DEBUG == $g_LOGALWAYS || $gscr_DEBUG -ge $g_LOGVERBOSE ]]
    then #{
        fn_log $g_LOGCOND $FUNCNAME $LINENO "<$1 Dumping result of $cmd_MONIT monitor all to log:"
        $cmd_MONIT monitor all | $cmd_TEE -a $g_LOG >&6
        fn_log $g_LOGCOND $FUNCNAME $LINENO "Result of $cmd_MONIT monitor all dumped to log"
    else #}{
        $cmd_MONIT monitor all >&6
    fi #}
}

################################################################################
### Purpose: Helper function for functions fn_scan_ftp_location()
###          and fn_scan_http_location().
### Args:    $1 calling $LINENO
###          $2 is the ip_address
###          $3 is the url
###          $4 is the rpath
###          $5 is the error message passback
### Notes:   If an error is detected, return value will be non-zero, and
###          $_arg_duu_passback_errmsg will be set to the error message.
### Returns: 0 on success, 1 on failure.
fn_download_umds_uxds()
{
    fn_chkargs $FUNCNAME $LINENO $# 5 5 "LINENO, ip_address, url, rpath, passback_errmsg"

    local -r _arg_duu_ipaddr=$2
    local -r _arg_duu_wget_url=$3
    local -r _arg_duu_rpath=$4
    local -r _arg_duu_passback_errmsg=$5
    eval "${_arg_duu_passback_errmsg}=\"\""
    local -i _duu_retval=

    fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "Downloading .umd and .uxd files"

    ### $cmd_WGET below will write HTML-ized index of the remote directory
    ### rooted at URL $_arg_duu_wget_url to the file $g_tmp_dir/index.html.
    $cmd_WGET --no-parent --directory-prefix=$g_tmp_dir -N $_arg_duu_wget_url/ &>$g_WGETLOG
    _duu_retval=$?
    local _duu_errmsg=
    if fn_found_error $LINENO $_duu_retval $g_WGETLOG _duu_errmsg
    then #{
        eval "${_arg_duu_passback_errmsg}=\"$_duu_errmsg\""
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$FUNCNAME returning 1, error \"${!_arg_duu_passback_errmsg}\""
        return 1
    fi #}

    if ! $cmd_GREP \"*\.$g_arch\.umd\" $g_tmp_dir/index.html \
            >$g_tmp_dir/umd.html
    then #{
        eval "${_arg_duu_passback_errmsg}=\"No_Files $cmd_GREP No umd files found in $g_tmp_dir/index.html \""
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$FUNCNAME returning 1, error \"${!_arg_duu_passback_errmsg}\""
        return 1
    fi #}

    local -i _duu_count_patches=$($cmd_GREP -c \"*\.$g_arch\.umd\" \
        $g_tmp_dir/index.html)

    fn_write_event $LINENO I -1 "Downloading $_duu_count_patches UMDs from $_arg_duu_ipaddr in $_arg_duu_rpath"

    $cmd_WGET -N -F -i "$g_tmp_dir/umd.html" --directory-prefix="$g_tmp_dir" \
        -B $_arg_duu_wget_url/ &>$g_WGETLOG
    _duu_retval=$?
    if fn_found_error $LINENO $_duu_retval $g_WGETLOG _duu_errmsg
    then #{
        eval "${_arg_duu_passback_errmsg}=\"$_duu_errmsg\""
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$FUNCNAME returning 1, error \"${!_arg_duu_passback_errmsg}\""
        return 1
    fi #}

    if ! $cmd_GREP \"*\.$g_arch\.uxd\" $g_tmp_dir/index.html \
                >$g_tmp_dir/uxd.html
    then #{
        eval "${_arg_duu_passback_errmsg}=\"No_Files Missing required files in specified location.\""
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$FUNCNAME returning 1, error \"${!_arg_duu_passback_errmsg}\""
        return 1
    fi #}

    _duu_count_patches=$($cmd_GREP -c \"*\.$g_arch\.uxd\" $g_tmp_dir/index.html)
    fn_write_event $LINENO I -1 "Downloading from $_arg_duu_ipaddr in $_arg_duu_rpath <- $LINENO of $g_PROGNAME"

    $cmd_WGET -N -F -i "$g_tmp_dir/uxd.html" --directory-prefix="$g_tmp_dir" \
        -B $_arg_duu_wget_url/ &>$g_WGETLOG
    _duu_retval=$?
    if fn_found_error $LINENO $_duu_retval $g_WGETLOG _duu_errmsg
    then #{
        eval "${_arg_duu_passback_errmsg}=\"Download error $_duu_retval\""
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$FUNCNAME returning 1, error \"${!_arg_duu_passback_errmsg}\""
        return 1
    fi #}

    return 0
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 is callback for url
###          $3 is ftp_ip_address
###          $4 is user_name
###          $5 is user_password
###          $6 is remote_path
### Returns: 0 on success
###          1 on failure
fn_scan_ftp_location()
{
    fn_chkargs $FUNCNAME $LINENO $# 6 6 "LINENO, passback_url, ftp_ip_address, user_name, user_password, remote_path"
    local -r _arg_sftploc_passback_url=$2
    eval "${_arg_sftploc_passback_url}=\"\""
    local -r _arg_sftploc_ipaddr=$3
    local -r _arg_sftploc_usr=$4
    local -r _arg_sftploc_passwd=$5
    local -r _arg_sftploc_rpath=$6

    local _sftploc_rpath_massaged="$_arg_sftploc_rpath"
    fn_massage_path $LINENO _sftploc_rpath_massaged

    eval "${_arg_sftploc_passback_url}=\"ftp://$_arg_sftploc_usr:$_arg_sftploc_passwd@$_arg_sftploc_ipaddr/$_sftploc_rpath_massaged\""

    echo $_arg_sftploc_ipaddr/$_arg_sftploc_rpath >$g_LOCATIONLOG

    local _sftploc_errmsg=
    if ! fn_download_umds_uxds $LINENO $_arg_sftploc_ipaddr \
            ${!_arg_sftploc_passback_url} $_arg_sftploc_rpath _sftploc_errmsg
    then #{
        fn_write_status $LINENO "$_sftploc_errmsg"
        fn_write_event $LINENO E -1 "$_sftploc_errmsg"
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "fn_download_umds_uxds $_arg_sftploc_ipaddr ${!_arg_sftploc_passback_url} $_arg_sftploc_rpath failed, $FUNCNAME returning 1"
        eval "${_arg_sftploc_passback_url}=\"\""
        return 1
    fi #}

    return 0
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 is callback for url
###          $3 is callback for patch_proto
###          $4 ipaddrr
###          $5 user
###          $6 password
###          $7 remotepath
###          $8 ssl (TRUE or FALSE)
### Returns: 1 on error, 0 on success
fn_scan_http_location()
{
    fn_chkargs $FUNCNAME $LINENO $# 8 8 "LINENO, passback_url, passback_patch_proto, ipaddrr, user, password, remotepath, ssl"
    local -r _arg_shttploc_passback_url=$2
    eval "${_arg_shttploc_passback_url}=\"\""
    local -r _arg_shttploc_passback_patch_proto=$3
    local -r _arg_shttploc_ipaddr=$4
    local -r _arg_shttploc_usr=$5
    local -r _arg_shttploc_passwd=$6
    local -r _arg_shttploc_rpath=$7
    local -r _arg_shttploc_ssl=$(echo "$8" | $cmd_TR '[:lower:]' '[:upper:]')

    local _shttploc_rpath_massaged="$_arg_shttploc_rpath"
    fn_massage_path $LINENO _shttploc_rpath_massaged

    if [[ $_arg_shttploc_ssl == TRUE ]]
    then #{
        eval "${_arg_shttploc_passback_patch_proto}=\"https\""
    else #}{
        eval "${_arg_shttploc_passback_patch_proto}=\"http\""
    fi #}
    eval "${_arg_shttploc_passback_url}=\"${!_arg_shttploc_passback_patch_proto}://$_arg_shttploc_usr:$_arg_shttploc_passwd@$_arg_shttploc_ipaddr/$_shttploc_rpath_massaged\""

    echo $_arg_shttploc_ipaddr\\$_arg_shttploc_rpath >$g_LOCATIONLOG

    local _shttploc_errmsg=
    if ! fn_download_umds_uxds $LINENO $_arg_shttploc_ipaddr \
            ${!_arg_shttploc_passback_url} $_arg_shttploc_rpath \
            _shttploc_errmsg
    then #{
        fn_write_status $LINENO "$_shttploc_errmsg"
        fn_write_event $LINENO E -1 "$_shttploc_errmsg"
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "fn_download_umds_uxds $_arg_shttploc_ipaddr ${!_arg_shttploc_passback_url} $_arg_shttploc_rpath failed, $FUNCNAME returning 1"
        eval "${_arg_shttploc_passback_url}=\"\""
        return 1
    fi #}

    return 0
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 is callback for url
###          $3 ipaddr
###          $4 user
###          $5 password
###          $6 rpath
### Returns: 0 on success, 1 on failure.
fn_scan_samba_location()
{
    #fn_chkargs $FUNCNAME $LINENO $# 6 6 "LINENO, passback_url, ipaddr, user, password, remotepath"
    local -r _arg_ssambaloc_passback_url=$2
    eval "${_arg_ssambaloc_passback_url}=\"\""
    local -r _arg_ssambaloc_ipaddr="$3"
    local -r _arg_ssambaloc_usr=$4 ### domain (if any) is part of _arg_ssambaloc_usr
    local -r _arg_ssambaloc_passwd=$5
    local   _arg_ssambaloc_rpath="$6"
    local    _ssambaloc_errmsg=
    local -r _URL="//${_arg_ssambaloc_ipaddr} -U ${_arg_ssambaloc_usr}%${_arg_ssambaloc_passwd}"
    if [ $6 == "." ]; then
      echo $_arg_ssambaloc_ipaddr >$g_LOCATIONLOG
    else 
      echo $_arg_ssambaloc_ipaddr\\$_arg_ssambaloc_rpath >$g_LOCATIONLOG
    fi
      eval "${_arg_ssambaloc_passback_url}=\"//$_arg_ssambaloc_ipaddr -U $_arg_ssambaloc_usr%$_arg_ssambaloc_passwd\""
    ### TODO what's $g_INFODIR/sambaddr used for
    echo $_arg_ssambaloc_ipaddr >$g_INFODIR/sambaddr


    ### There is a pushd here so the call to
    ### $cmd_SMBCLIENT will run in the right directory.
    pushd $g_tmp_dir &>$g_NULL #{
    if [[ $? != 0 ]]
    then #{
        _ssambaloc_errmsg="Failure to change to $g_tmp_dir"
        fn_write_status $LINENO "$_ssambaloc_errmsg"
        fn_write_event $LINENO E -1 "$_ssambaloc_errmsg"
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Failure to change to $g_tmp_dir"
        eval "${_arg_ssambaloc_passback_url}=\"\""
        return 1
    fi #}

    local -i _ssambaloc_retval=
    ### Get the uxd files.
    $cmd_SMBCLIENT -E $_URL -c "prompt; cd ${_arg_ssambaloc_rpath}; mget *.uxd"
    _ssambaloc_retval=$?
   
    if fn_found_error $LINENO $_ssambaloc_retval \
            $g_SMBCLIENTLOG _ssambaloc_errmsg
    then #{
        _ssambaloc_errmsg="$_ssambaloc_errmsg in SMB at $LINENO"
        fn_write_status $LINENO "$_ssambaloc_errmsg"
        fn_write_event $LINENO E -1 "$_ssambaloc_errmsg"
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "fn_found_error $_ssambaloc_retval $g_SMBCLIENTLOG failed, error message \"$_ssambaloc_errmsg\", $FUNCNAME returning 1"
        popd &>$g_NULL
        eval "${_arg_ssambaloc_passback_url}=\"\""
        return 1
    fi #}

    ### Get the umd files.
    $cmd_SMBCLIENT  $_URL -c "prompt; cd ${_arg_ssambaloc_rpath}; mget *.umd"
    _ssambaloc_retval=$?
   
    if fn_found_error $LINENO $_ssambaloc_retval \
            $g_SMBCLIENTLOG _ssambaloc_errmsg
    then #{
        _ssambaloc_errmsg="$_ssambaloc_errmsg SMB at $LINENO"
        fn_write_status $LINENO "$_ssambaloc_errmsg"
        fn_write_event $LINENO E -1 "$_ssambaloc_errmsg"
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "fn_found_error $_ssambaloc_retval $g_SMBCLIENTLOG failed, error message \"$_ssambaloc_errmsg\", $FUNCNAME returning 1"
        popd &>$g_NULL
        eval "${_arg_ssambaloc_passback_url}=\"\""
        return 1
    fi #}

    popd &>$g_NULL #}

    return 0
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 is callback for url
###          $3 rpath (usbpath)
### Returns: 0 on success, 1 on failure
fn_scan_usb_location()
{
    fn_chkargs $FUNCNAME $LINENO $# 3 3 "LINENO, passback_url, rpath"
    local -r _arg_susbloc_passback_url=$2
    eval "${_arg_susbloc_passback_url}=\"\""
    local -r _arg_susbloc_rpath=$3
    local    _susbloc_errmsg=

    local _scan_usb_location_rpath_massaged="$_arg_susbloc_rpath"
    fn_massage_path $LINENO _scan_usb_location_rpath_massaged

    echo $_arg_susbloc_rpath >$g_LOCATIONLOG
    ### TODO what is $g_INFODIR/usb used for
    echo $_scan_usb_location_rpath_massaged >$g_INFODIR/usb

    if ! $cmd_MOUNT | $cmd_GREP -q -s "$g_usbdev"
    then #{
        ### first try auto mount filesystem
        if ! $cmd_MOUNTUSB &>$g_NULL
        then #{
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "No usb device attached or it is already mounted --- Continuing ..."
        fi #}
    fi #}

    if [[ ! -e "/mnt/usb/$_scan_usb_location_rpath_massaged" ]]
    then #{
        _susbloc_errmsg="Directory_Not_Found (/mnt/usb/$_scan_usb_location_rpath_massaged)"
        fn_write_status $LINENO "$_susbloc_errmsg"
        fn_write_event $LINENO E -1 "$_susbloc_errmsg"
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "/mnt/usb/$_scan_usb_location_rpath_massaged missing, error message \"$_susbloc_errmsg\", $FUNCNAME returning 1"
        return 1
    fi #}

    if      ! $cmd_CP -f \
                /mnt/usb/$_scan_usb_location_rpath_massaged/*.umd $g_tmp_dir \
        ||  ! $cmd_CP -f \
                /mnt/usb/$_scan_usb_location_rpath_massaged/*.uxd $g_tmp_dir
    then #{
        _susbloc_errmsg="File_Not_Found $cmd_CP"
        fn_write_status $LINENO "$_susbloc_errmsg"
        fn_write_event $LINENO E -1 "$_susbloc_errmsg"
        $cmd_UMOUNTUSB
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$cmd_CP -f /mnt/usb/$_scan_usb_location_rpath_massaged/*.umd $g_tmp_dir or $cmd_CP -f /mnt/usb/$_scan_usb_location_rpath_massaged/*.uxd $g_tmp_dir failed, error message \"$_susbloc_errmsg\", $FUNCNAME returning 1"
        return 1
    fi #}

    $cmd_UMOUNTUSB
    eval "${_arg_susbloc_passback_url}=\"/mnt/usb/$_scan_usb_location_rpath_massaged\""
    return 0
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 is callback for url
### Returns: 0 on success, 1 on failure
fn_scan_EM_location()
{
    fn_chkargs $FUNCNAME $LINENO $# 2 2 "LINENO, passback_url"
    local -r _arg_sEMloc_passback_url=$2
    eval "${_arg_sEMloc_passback_url}=\"\""
    local _sEMloc_errmsg=

    echo "Local System" >$g_LOCATIONLOG

    if      ! $cmd_CP -f $g_PATCHTMPDIR/*.umd $g_tmp_dir \
        ||  ! $cmd_CP -f $g_PATCHTMPDIR/*.uxd $g_tmp_dir
    then #{
        _sEMloc_errmsg="File_Not_Found $cmd_CP"
        fn_write_status $LINENO "$_sEMloc_errmsg"
        fn_write_event $LINENO E -1 "$_sEMloc_errmsg"
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$cmd_CP -f $g_PATCHTMPDIR/*.umd $g_tmp_dir or $cmd_CP -f $g_PATCHTMPDIR/*.uxd $g_tmp_dir failed, error message \"$_sEMloc_errmsg\", $FUNCNAME returning 1"
        return 1
    fi #}

    $cmd_RM -f $g_PATCHTMPDIR/*.{umd,uxd,uxd.sig} &>$g_NULL

    eval "${_arg_sEMloc_passback_url}=\"$g_PATCHTMPDIR\""
    return 0
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 file_to_delete
### Returns: 1 on error, 0 on success
fn_delete_scrambled_shredded_file()
{
    fn_chkargs $FUNCNAME $LINENO $# 2 2 "LINENO, file_to_delete"

    local -r _arg_file=$2
    if [[ ! -e $_arg_file ]]
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$_arg_file missing, returning 1"
        return 1
    fi #}

    ### Field 5 is file length.
    local -r _flength=$($cmd_LS -l "$_arg_file" | $cmd_GAWK '{print $5}')
    if [[ ! $_flength ]]
    then #{

        fn_log $g_LOGWARN $FUNCNAME $LINENO "file $_arg_file is empty, we'll just remove it"

        ### Flush buffers.
        $cmd_SYNC &>$g_NULL \
            || fn_log $g_LOGALWAYS $FUNCNAME $LINENO "first $cmd_SYNC failed"

        ### Fill with random bytes.
        $cmd_DD if=/dev/urandom of=$_arg_file bs=1 count=$_flength &>$g_NULL
        if [[ $? != 0 ]]
        then #{
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$cmd_DD random on file $_arg_file count $_flength failed, returning 1"
            return 1
        fi #}

        ### Flush buffers again.
        $cmd_SYNC &>$g_NULL \
            || fn_log $g_LOGALWAYS $FUNCNAME $LINENO "second $cmd_SYNC failed"

        ### Fill with zeros.
        $cmd_DD if=/dev/zero of=$_arg_file bs=1 count=$_flength &>$g_NULL
        if [[ $? != 0 ]]
        then #{
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$cmd_DD 0 on file $_arg_file count $_flength failed, returning 1"
            return 1
        fi #}

        ### Flush buffers yet again.
        $cmd_SYNC &>$g_NULL \
            || fn_log $g_LOGALWAYS $FUNCNAME $LINENO "third $cmd_SYNC failed"

    fi #}

    ### Delete file.
    if ! $cmd_RM -f $_arg_file &>$g_NULL
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$cmd_RM -f $_arg_file failed"
        return 1
    fi #}

    ### Flush buffers a final time.
    if ! $cmd_SYNC &>$g_NULL
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "final $cmd_SYNC failed"
        return 1
    fi #}

    return 0
}

################################################################################
### Purpose: Reads the REBOOT flag from a XML file using the
###              fn_get_umd_tag_value function.
### Args:    $1 calling $FUNCNAME
###          $2 calling $LINENO
###          $3 location directory path
###          $4 xml file name
###          $5 passback for reboot flag, set to reboot if REBOOT flag is
###             present, and set to blank if flag is not present or can't
###             be read.
### Returns:  1 on error, 0 on success
fn_read_reboot()
{
    fn_chkargs $FUNCNAME $LINENO $# 5 5 "FUNCNAME, LINENO, location_directory_path, xml_file_name, passback_rebootflag"

    local -r    _arg_rr_funcname=$1
    local -r -i _arg_rr_lineno=$2
    local -r    _arg_rr_location_directory_path=$3
    local -r    _arg_rr_xml_file_name=$4
    local -r    _arg_rr_passback_rebootflag=$5
    local       _reboot_state
    local       _package_date
    local       _grep_return 
    local       _package_date_count
    local       _package_date_format
    local       _reboot_list_count

    eval "${_arg_rr_passback_rebootflag}=\"\""

    $cmd_XPATHPARSE $g_INFODIR/$_arg_rr_xml_file_name  "//PACKAGE[@reboot='yes']/text()"  >$g_INFODIR/reboot_list 
    
    _reboot_state=`$cmd_CAT $g_INFODIR/reboot_list | $cmd_SED -e "s/\.$g_arch\.rpm$//"`
    $cmd_GREP "$_reboot_state" $g_INFODIR/$_arg_rr_xml_file_name.rpms
    _grep_return=$? 
    _reboot_list_count=$($cmd_CAT $g_INFODIR/reboot_list | $cmd_SED -e "s/\.rpm$//" | wc -l) 
    ### Check if the new reboot meta-data is present in the umd file &
    ### listed in the rpms file to install.
    if [[ $_reboot_list_count  > 0 &&  $_grep_return == 0 ]]
    then #{ 
 
        fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_DOWNCASE \
            $_arg_rr_location_directory_path $_arg_rr_xml_file_name \
            "REBOOT" $_arg_rr_passback_rebootflag
 
        ## This is tocheck if the Reboot Flag is Blank
        if [[       reboot != ${!_arg_rr_passback_rebootflag} \
                &&  no     != ${!_arg_rr_passback_rebootflag} ]]
        then #{
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Called from $_arg_rr_funcname:$_arg_rr_lineno on path=\"$_arg_rr_location_directory_path\" file=\"$_arg_rr_xml_file_name\", expected value to be \"reboot\", \"no\" or blank, but was \"${!_arg_rr_passback_rebootflag}\""
        fi #}

        if [[  reboot != ${!_arg_rr_passback_rebootflag}  ]]
        then #{
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Called from $_arg_rr_funcname:$_arg_rr_lineno on path=\"$_arg_rr_location_directory_path\" file=\"$_arg_rr_xml_file_name\", expected value to be \"reboot\", but was \"{!_arg_rr_passback_rebootflag}\""
            eval "${_arg_rr_passback_rebootflag}=\"reboot\""
            return 1
        fi #}
    ### Check for old meta-data and verify for patch date     
    else  #}{

        ### Note how value of $_arg_rr_passback_rebootflag is passed, and not just
        ### the variable name. If this call fails, _arg_rr_passback_rebootflag will
        ### be blank as it was set to blank in the top of this function.
        fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_DOWNCASE \
                $_arg_rr_location_directory_path $_arg_rr_xml_file_name \
                "REBOOT" $_arg_rr_passback_rebootflag || return 0

        if [[ ! ${!_arg_rr_passback_rebootflag} ]]
        then #{
            fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "Called from $_arg_rr_funcname:$_arg_rr_lineno on path=\"$_arg_rr_location_directory_path\" file=\"$_arg_rr_xml_file_name\", returned empty string, reboot set to blank"
            return 0
        fi #}

        if [[       reboot != ${!_arg_rr_passback_rebootflag} \
                &&  no     != ${!_arg_rr_passback_rebootflag} ]]
        then #{
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Called from $_arg_rr_funcname:$_arg_rr_lineno on path=\"$_arg_rr_location_directory_path\" file=\"$_arg_rr_xml_file_name\", expected value to be \"reboot\", \"no\" or blank, but was \"${!_arg_rr_passback_rebootflag}\", setting to blank"
            eval "${_arg_rr_passback_rebootflag}=\"\""
        fi #}
        _package_date=$($cmd_XPATHPARSE $g_INFODIR/$_arg_rr_xml_file_name  "//PACKAGEDATE/text()")
        _package_date=$(echo $_package_date | cut -c7-10)/$(echo $_package_date | cut -c4-5)/$(echo $_package_date | cut -c1-2)
        
        _package_date_count=$(echo $_package_date | wc -c)
        echo $_package_date | grep [a-z]
        _package_date_format=$?
        if [[ ($_package_date_format == 0) || ($_package_date_count < 11) ]]
        then #{
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Called from $_arg_rr_funcname:$_arg_rr_lineno on path=\"$_arg_rr_location_directory_path\" file=\"$_arg_rr_xml_file_name\", The Package date for the Patch is not in the correct format DD/MM/YYYY "
            return 0
        else #}{
            ### The package is further checked below, if the package date is greater than the said g_PATCH_REL_DATE,
            ### reboot flag is futher checked for Smart Update packages & set to "no" if any patch errors are found.
            if [[ $_package_date > $g_PATCH_REL_DATE ]]
            then
                if [[ ( reboot == ${!_arg_rr_passback_rebootflag} && $_reboot_list_count > 0 ) ]]
                then #{
                    eval "${_arg_rr_passback_rebootflag}=\"no\""
                    return 0
                elif [[ ( no == ${!_arg_rr_passback_rebootflag} &&  $_reboot_list_count == 0 ) ]]
                    then #}{
                    return 0
                else #}{
                    fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Called from $_arg_rr_funcname:$_arg_rr_lineno on path=\"$_arg_rr_location_directory_path\" file=\"$_arg_rr_xml_file_name\", Patch was created after $g_PATCH_REL_DATE expected value to be \"no\", but was \"${!_arg_rr_passback_rebootflag}\""
                    eval "${_arg_rr_passback_rebootflag}=\"no\""
                    return 1
                fi #}
            fi
        fi #}
    fi #}
    return 0
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 passback for encryption_key
### Returns: 1 on error, 0 on success
fn_get_urandom_key()
{
    fn_chkargs $FUNCNAME $LINENO $# 2 2 "LINENO, passback_encryption_key"
    local -r _arg_passback_encryption_key=$2
    eval "${_arg_passback_encryption_key}=\"\""

    local _tmp_file=
    fn_make_temp_file $LINENO _tmp_file

    ### generate file of urandom numbers, random is apparently better but it
    ### is too slow
    $cmd_DD if=/dev/urandom of=$_tmp_file bs=1 count=500 &>$g_NULL
    if [[ $? != 0 ]]
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$cmd_DD failed on of $_tmp_file, returning 1"
        return 1
    fi #}

    ### take a checksum of the content of the file
    eval "${_arg_passback_encryption_key}=\"$(md5sum $_tmp_file | $cmd_GAWK '{print $1}')\""
    if [[ ! ${!_arg_passback_encryption_key} ]]
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Failed to generate urandom key, returning 1"
        return 1
    fi #}

    ### now, scramble, shred it and delete
    fn_delete_scrambled_shredded_file $LINENO $_tmp_file

    return 0
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 is the directory
###          $3 is the key.
### Returns: 1 on error, 0 on success
fn_hide_key()
{
    fn_chkargs $FUNCNAME $LINENO $# 3 3 "LINENO, dir, key"

    local -r _arg_hide_key_dir=$2
    local -r _arg_hide_key_key=$(echo "$3" | $cmd_SED -e 's/\([^ ]\)/\1:/g')

    ### Need to check that the massaged $_arg_hide_key_key is not blank.
    if [[ ! $_arg_hide_key_key ]]
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "_arg_hide_key_key passed in was massaged to remove extraneous characters, resulting in the value being null, returning 1"
        return 1
    fi #}

    local -i _hide_key_a=0
    local -i _hide_key_b=1
    local -i _hide_key_d=1
    local -i _hide_key_c=$((_hide_key_a + _hide_key_b))

    _hide_key_b=$_hide_key_a
    _hide_key_a=$_hide_key_c
    ((_hide_key_d++))
    _hide_key_c=$((_hide_key_a + _hide_key_b))
    _hide_key_b=$_hide_key_a
    _hide_key_a=$_hide_key_c
    ((_hide_key_d++))

    pushd $_arg_hide_key_dir &>$g_NULL #{
    if [[ $? != 0 ]]
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Failure to change to $_arg_hide_key_dir"
        return 1
    fi #}

    $cmd_RM -f [0-9]*\.[0-9a-zA-Z]* &>$g_NULL

    local -r _hide_key_ifs_sav=$IFS
    ### there's three spaces after the colon in the IFS redefinition, please
    ### don't remove them!
    IFS=':   '

    local _hide_key_char=
    for _hide_key_char in $_arg_hide_key_key
    do #{
        $cmd_TOUCH ./$_hide_key_c.$_hide_key_char &>$g_NULL
        _hide_key_c=$((_hide_key_a + _hide_key_b))
        _hide_key_b=$_hide_key_a
        _hide_key_a=$_hide_key_c
        ((_hide_key_d++))
    done #}

    IFS=$_hide_key_ifs_sav

    popd &>$g_NULL #}

    return 0
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 is dir
###          $3 is passback for tmp_key
### Returns: 1 on failure to change to dir in arg $2
###          0 on success
fn_unhide_key()
{
    fn_chkargs $FUNCNAME $LINENO $# 3 3 "LINENO, dir, passback_tmp_key"

    local -r _arg_unhide_key_dir=$2
    local -r _arg_unhide_key_passback_tmp_key=$3
    eval "${_arg_unhide_key_passback_tmp_key}=\"\""

    local _unhide_key_file=
    local _unhide_key_char=

    pushd $_arg_unhide_key_dir &>$g_NULL #{
    if [[ $? != 0 ]]
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "<$1 Failure to change to $_arg_unhide_key_dir"
        return 1
    fi #}

    for _unhide_key_file in $($cmd_LS [0-9]*\.[0-9a-zA-Z]* 2>$g_NULL | sort -n)
    do #{
        _unhide_key_char=$(echo "$_unhide_key_file" \
            | $cmd_SED -e 's/^[^.][^.]*\.//')
        eval "${_arg_unhide_key_passback_tmp_key}=\"${!_arg_unhide_key_passback_tmp_key}$_unhide_key_char\""
    done #}

    popd &>$g_NULL #}

    if [[ ! ${!_arg_unhide_key_passback_tmp_key} ]]
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$_arg_unhide_key_dir contains no files, so cannot determine key"
        return 1
    fi #}

    return 0
}

################################################################################
### Purpose: Given a key, some data and a file name, encrypt the data using
###          the key, and store the output in the indicated file.
### Args:    $1 calling $LINENO
###          $2 is the key
###          $3 is the data
###          $4 is the output file
### Returns: 1 on error, 0 on success
fn_encrypt_data()
{
    fn_chkargs $FUNCNAME $LINENO $# 4 4 "LINENO, key, data, outfile"
    local -r _arg_encrypt_data_key=$2
    local -r _arg_encrypt_data_data=$3
    local -r _arg_encrypt_data_file_out=$4

    local _encrypt_data_file_in=
    fn_make_temp_file $LINENO _encrypt_data_file_in

    if ! echo "$_arg_encrypt_data_data" >$_encrypt_data_file_in
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Failed to write to file $_encrypt_data_file_in, returning 1"
        return 1
    fi #}

    if ! $cmd_GAPCYPERFILE "$_arg_encrypt_data_key" $_encrypt_data_file_in $_arg_encrypt_data_file_out 2 &>$g_NULL
    then #{
        ### just try it one more time, simply removing if secure delete
        ### fails for whatever reason
        if ! fn_delete_scrambled_shredded_file $LINENO $_encrypt_data_file_in
        then #{
            ### definitely need to let know in the logs that failed to
            ### delete, otherwise serious security hole, if still fails
            ### to delete, well, logs that go to EM indicated this
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "call 1 to fn_delete_scrambled_shredded_file $_encrypt_data_file_in failed"
            $cmd_RM -f $_encrypt_data_file_in &>$g_NULL
        fi #}
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Call to $cmd_GAPCYPERFILE $_arg_encrypt_data_key $_encrypt_data_file_in $_arg_encrypt_data_file_out 2 failed, function returning 1"
        return 1
    fi #}

    ### even if success encrypting, still need to securely delete this file,
    ### so do same as above
    if ! fn_delete_scrambled_shredded_file $LINENO $_encrypt_data_file_in
    then #{
        ### definitely need to let know in the logs that failed to delete,
        ### otherwise serious security hole, if still fails to delete,
        ### well, logs that go to EM indicated this although, in this case
        ### it is just deletion failed
        $cmd_RM -f $_encrypt_data_file_in &>$g_NULL
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "call 2 to fn_delete_scrambled_shredded_file $_encrypt_data_file_in failed"
        return 1
    fi #}

    return 0
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 is the key
###          $3 is the passback variable for data
###          $4 is the input file.
### Returns: 1 on error, 0 on success
fn_decrypt_data()
{
#    fn_chkargs $FUNCNAME $LINENO $# 4 4 "LINENO, key, passback_data, infile"
    local -r _arg_decrypt_data_key=$2
    local -r _arg_decrypt_data_passback_data_ref=$3
    eval "${_arg_decrypt_data_passback_data_ref}=\"\""
    local -r _arg_decrypt_data_file_in=$4

    local _decrypt_data_file_out=
    fn_make_temp_file $LINENO _decrypt_data_file_out

    if ! $cmd_GAPCYPERFILE "$_arg_decrypt_data_key" $_arg_decrypt_data_file_in $_decrypt_data_file_out 1 &>$g_NULL
    then #{

        ### just try it one more time, simply removing if secure delete fails
        ### for whatever reason
        if ! fn_delete_scrambled_shredded_file $LINENO $_decrypt_data_file_out
        then #{
            ### definitely need to let know in the logs that failed to delete,
            ### otherwise serious security hole, if still fails to delete,
            ### well, logs that go to EM indicated this
            $cmd_RM -f $_decrypt_data_file_out &>$g_NULL
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "call 1 to fn_delete_scrambled_shredded_file $_decrypt_data_file_out failed"
        fi #}
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "call to $cmd_GAPCYPERFILE $_arg_decrypt_data_key $_arg_decrypt_data_file_in $_decrypt_data_file_out 1 failed, function returning 1"
        return 1
    fi #}

    ### now, let's get the data out of file_out, basically everything in the
    ### file
    eval "${_arg_decrypt_data_passback_data_ref}=\"$($cmd_CAT $_decrypt_data_file_out)\""

    ### no return here, even if fails needs to del file_out later
    ### even if success encrypting, still need to securely delete this file,
    ### so do same as above
    if ! fn_delete_scrambled_shredded_file $LINENO $_decrypt_data_file_out
    then #{
        ### definitely need to let know in the logs that failed to delete,
        ### otherwise serious security hole, if still fails to delete, well,
        ### logs that go to EM indicated this although, in this case it is
        ### just deletion failed.
        $cmd_RM -f  $_decrypt_data_file_out &>$g_NULL
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "call 2 to fn_delete_scrambled_shredded_file $_decrypt_data_file_out failed"
        return 1
    fi #}

    ### here we want to return 1 if data_out is empty, otherwise assign it to
    ### pass back in data
    if [[ ! ${!_arg_decrypt_data_passback_data_ref} ]]
    then #{
        fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "output file is empty, function returning 1"
        return 1
    fi #}

    return 0
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 patch_name
###          $3 patch_ver
### Returns: 1 on error, 0 on success
fn_verify_signatures()
{
    fn_chkargs $FUNCNAME $LINENO $# 3 3 "LINENO, patch_name, patch_ver"

    ### Normally, we want to check the signature of the umd file.
    ### If $gscr_CHECKSIG is set to no, we don't check the umd file
    ### signature and we return 0 which looks to the caller as though
    ### the check was a success. This technique allows for more generic
    ### client code and allows us to test with unsigned patches.
    [[ $gscr_CHECKSIG && $gscr_CHECKSIG == no ]] && return 0

    local -r _arg_vs_patch_name=$2
    local -r _arg_vs_patch_ver=$3

    local -r _vs_rpms=$($cmd_CAT $g_INFODIR/$_arg_vs_patch_name-$_arg_vs_patch_ver.$g_arch.umd.rpms)
    local _vs_rpm=

    if [[ -e "$g_INFODIR/$_arg_vs_patch_name-$_arg_vs_patch_ver.$g_arch.usd" ]]
    then #{

        pushd / &>$g_NULL #{
        if [[ $? != 0 ]]
        then #{
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Failure to change to /"
            return 1
        fi #}

        $cmd_TAR -xf $g_INFODIR/$_arg_vs_patch_name-$_arg_vs_patch_ver.$g_arch.usd &>$g_NULL
        if [[ $? != 0 ]]
        then #{
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$cmd_TAR -xf $g_INFODIR/$_arg_vs_patch_name-$_arg_vs_patch_ver.$g_arch.usd failed"
            popd &>$g_NULL
            return 1
        fi #}
        popd &>$g_NULL #}

        fn_write_status $LINENO "Verifying"

        for _vs_rpm in $_vs_rpms
        do #{
            if ! $cmd_CFSSERVER -signverify \
                $g_INFODIR/$_vs_rpm $g_INFODIR/$_vs_rpm.sig &>$g_NULL
            then #{
                fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$cmd_CFSSERVER -signverify $g_INFODIR/$_vs_rpm $g_INFODIR/$_vs_rpm.sig failed, returning 1"
                return 1
            fi #}
        done #}

    else #}{

        ### TODO Was W 2200 "Software update invalid signature or corrupt file."
        ### but that's not in /nn/etc/DiaLoggerTaxonomy file.
        fn_write_event $LINENO W 2304 "Software update invalid signature or corrupt file. Retry file transfer."
        fn_write_status $LINENO "Failed_Sigs"
        return 1

    fi #}

    for _vs_rpm in $_vs_rpms
    do #{
        $cmd_RM -f $g_INFODIR/$_vs_rpm.sig &>$g_NULL
    done #}

    return 0
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 udx_path
###          $3 umd_path
### Returns: 1 on error, 0 on success
### Note:    if $gscr_CHECKSIG=no, this check defaults to a pass
###          but is still tested and the result is logged
fn_verify_uxd()
{
    fn_chkargs $FUNCNAME $LINENO $# 3 3 "LINENO, udx_path, umd_path"

    ### Normally, we want to check the signature of the uxd file.
    ### If $gscr_CHECKSIG is set to no, we don't check the uxd file
    ### signature and we return 0 which looks to the caller as though
    ### the check was a success. This technique allows for more generic
    ### client code and allows us to test with unsigned patches.
    [[ $gscr_CHECKSIG && $gscr_CHECKSIG == no ]] && return 0

    local -r _arg_vu_uxd_path=$2
    local -r _arg_vu_uxd_signature_path=$g_INFODIR/$(basename $_arg_vu_uxd_path).sig
    local -r _arg_vu_umd_path=$3

    if [[ ! -f $_arg_vu_uxd_path ]]
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Bad or non-existant uxd file \"$_arg_vu_uxd_path\""
        return 1
    fi #}

    if [[ ! -f $_arg_vu_umd_path ]]
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Bad or non-existant umd file \"$_arg_vu_umd_path\""
        return 1
    fi #}

    local _vu_uxd_sig=
    fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_RAW \
        $g_tmp_dir $(basename $_arg_vu_umd_path) "UXD_SIGNATURE" _vu_uxd_sig \
            || return 1

    echo -n $_vu_uxd_sig | $cmd_BASE64 -de >$_arg_vu_uxd_signature_path
    $cmd_CFSSERVER -signverify $_arg_vu_uxd_path \
        $_arg_vu_uxd_signature_path &>$g_NULL
    if [[ $? != 0 ]]
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$cmd_CFSSERVER -signverify $_arg_vu_uxd_path $_arg_vu_uxd_signature_path failed"
        return 1
    fi #}
    rm -f $_arg_vu_uxd_signature_path

    return 0
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 is the return value to test
###          $3 is the path to the log file
###          $4 passback variable for error string
### Returns: 0 if found, 1 otherwise.
fn_found_error()
{
    fn_chkargs $FUNCNAME $LINENO $# 4 4 "LINENO, exit_code, log_file_path, passback_error"

    local -r -i _arg_fe_calling_lineno=$1
    local -r -i _arg_fe_retval=$2
    local -r    _arg_fe_log_file=$3
    local -r    _arg_fe_passback_error=$4
    eval "${_arg_fe_passback_error}=\"\""

    ### wget and samba client does not necessarily exits with non-zero when
    ### there is some issues only obvious ones, therefore need to check a
    ### log file if there was a problem based on the content of the log file
    ### messages, a file should be overwritten every time wget or samba client
    ### is called, global logging should be employed outside here, the error
    ### message passed back is actually what will go into $g_ACTIVESTATUS
    ### NOTE: no need for a separate handler for errors separately for wget
    ### or samba client

    [[ $_arg_fe_retval != 0 ]] \
        && eval "${_arg_fe_passback_error}=\"Connection_Failed\""

    $cmd_GREP -q '^No such directory' \
        $_arg_fe_log_file && eval "${_arg_fe_passback_error}=\"Directory_Not_Found\""
    $cmd_GREP -q ' ERROR 404: Not Found. *$' \
        $_arg_fe_log_file && eval "${_arg_fe_passback_error}=\"File_Not_Found\""
    $cmd_GREP -q ' failed: Connection refused. *$' \
        $_arg_fe_log_file && eval "${_arg_fe_passback_error}=\"Connection_Refused\""
    $cmd_GREP -q ' 401 Authorization Required *$' \
        $_arg_fe_log_file && eval "${_arg_fe_passback_error}=\"Authorization_Failed\""
    $cmd_GREP -q '^Login incorrect.' \
        $_arg_fe_log_file && eval "${_arg_fe_passback_error}=\"Login_Incorrect\""
    $cmd_GREP -q ' failed: Host not found. *$' \
        $_arg_fe_log_file && eval "${_arg_fe_passback_error}=\"Host_Not_Found\""
    $cmd_GREP -q ' failed: No route' \
        $_arg_fe_log_file && eval "${_arg_fe_passback_error}=\"Host_Unreachable\""
    $cmd_GREP -q '^session setup failed: NT_STATUS_LOGON_FAILUR' \
        $_arg_fe_log_file && eval "${_arg_fe_passback_error}=\"Authorization_Failed\""
    $cmd_GREP -q '^tree connect failed: NT_STATUS_BAD_NETWORK_NAME'\
        $_arg_fe_log_file && eval "${_arg_fe_passback_error}=\"Host_Not_Found\""
    $cmd_GREP -q '^NT_STATUS_NO_SUCH_FILE ' \
        $_arg_fe_log_file && eval "${_arg_fe_passback_error}=\"File_Not_Found\""

    if [[ ${!_arg_fe_passback_error} ]]
    then #{
        fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "<$_arg_fe_calling_lineno error message parsed, error=\"${!_arg_fe_passback_error}\", returning 0"
        return 0
    else #}{
        return 1
    fi #}
}

################################################################################
### Args:    $1 is the calling $LINENO
###          $2 is severity must be E, W or I for Error, Warning or
###             Info respectively.
###          $3 is the unique event_id which is:
###             2000-2999 for patching
###             3000-3999 for upgrades
###             -1 for local logging only (no alarms are raised for -1).
###          $4 is the customer-facing event description
### Returns: 0
### Note:    Used to be called write_alarm in old script.
fn_write_event()
{
    fn_chkargs $FUNCNAME $LINENO $# 4 4 "LINENO, severity, event_id, message"

    ### For available events, see /nn/etc/DiaLoggerTaxonomy.

    ### TODO: The following events are in the /nn/etc/DiaLoggerTaxonomy file
    ### but are unused.
    ###   I 2104 "Software update scheduled"
    ###   I 2105 "Scheduled software update completed."

    local -r -i _arg_calling_lineno=$1

    ### _arg_severity must be E, W or I for Error, Warning or Info respectively.
    local -r _arg_severity=$2

    ### _arg_event_id is a unique ID for alarm
    ###       2000-2999 for patching,
    ###       3000-3999 for upgrades
    ###       -1 value for local logging only, no alarms are raised
    local -r -i _arg_event_id=$3

    ### _arg_message is customer-facing event description.
    ### Note if we simply say _arg_message="$4", newlines will be preserved,
    ### but by using the _arg_message="$(echo $4)", construct, newlines will
    ### be stripped.
    local -r _arg_message="$(echo $4)"

    fn_log $g_LOGINFO $FUNCNAME $LINENO "<$_arg_calling_lineno sev:$_arg_severity eid:$_arg_event_id msg=\"$_arg_message\""

    ### Note we don't check for existence of $cmd_ADDNNUDIAGLOG as it
    ### was done during script startup.

    ### $cmd_AddNnuDiagLog takes the following parameters:
    ###   -m<moduleName>
    ###   -l<logFileName>
    ###   -s<severity>
    ###   -v<eventID>
    ###   -w<where>
    ###   <message>
    ### Where in our case, the values are:
    ###   <moduleName>  Our module is called "SoftwareUpdates"
    ###   <logFileName> The basename of the log file.
    ###   <severity>    One of E, W, I or D for Error, Warning, Info, or
    ###                     Debug respectively.
    ###   <eventID>     -1 if no event id, or a positive event id which can be
    ###                     found in the file /nn/etc/DiaLoggerTaxonomy and
    ###                     which is used to map events to alarms that will
    ###                     then appear in Element Manager, and possibly on
    ###                     the alarm set or an SNMP client, and that may also
    ###                     possibly affect the LEDs.
    ###   <where>       Will be R meaning to log to registered file.
    ###   <message>     The message (as a text string) to be logged.

    if ! $cmd_ADDNNUDIAGLOG -mSoftwareUpdates \
            -l$g_LOGFILE_BASENAME -wR -s$_arg_severity \
            -v$_arg_event_id "$_arg_message"
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$cmd_ADDNNUDIAGLOG -mSoftwareUpdates -l$g_LOGFILE_BASENAME -wR -s$_arg_severity -v$_arg_event_id \"$_arg_message\" failed"
    fi #}

    return 0
}

################################################################################
### Purpose: Checks to see if package is installed, i.e., is present in the
###          RPM database. It does this using the passed in rpm package file
###          name, where it gets rpm name, version and release out of the
###          actual file name, since at this point the .rpm package has not
###          yet been downloaded (usually.) It is considered installed
###          (ignored) if the rpm version and release are less than or equal
###          to the version and release in the rpm db.
###          MAYBE A GOOD IDEA TO HAVE METADATA IN UMD FILE THAT REVERTS THIS
###          BEHAVOUR TO A TRADITIONAL ONE, though that would break signature
###          of UMD file.
### Args:    $1 calling $LINENO
###          $2 is the rpm package name.
### Returns: 0 if package is to be ignored, 1 if not.
fn_ignore_package()
{
    fn_chkargs $FUNCNAME $LINENO $# 2 2 "LINENO, pkgname"

    ### just in case if rpm package passed as location/file, sometimes
    ### good for doing testing.
    local -r _arg_ignorepackage_rpm_package=$(basename $2)

    local -r _ignorepackage_package_name=$(echo $_arg_ignorepackage_rpm_package | $cmd_SED -e "s/^\([^.][^.]*\)-[^-][^-]*-[^-][^-]*\.$g_arch\.rpm$/\1/")
    ### check if package_name is in rpm db, if it is, check version and
    ### release, if not, do not ignore it
    $cmd_RPM -q $_ignorepackage_package_name &>$g_NULL || return 1

    ### installed, check version, then release

    local -r _ignorepackage_rpm_ver=$($cmd_RPM -q \
        --queryformat %{VERSION}-%{RELEASE} $_ignorepackage_package_name)

    ### if rpm ver is greater than or equal to package ver then just ignore
    ### this package
    local -r _ignorepackage_package_rel=$(echo $_arg_ignorepackage_rpm_package | $cmd_SED -e "s/^[^.][^.]*-[^-][^-]*-\([^-][^-]*\)\.$g_arch\.rpm$/\1/")
    local -r _ignorepackage_package_ver=$(echo $_arg_ignorepackage_rpm_package | $cmd_SED -e "s/^[^.][^.]*-\([^-][^-]*\)-[^-][^-]*\.$g_arch\.rpm$/\1/")

    fn_lockfile $LINENO $g_RPMCOMP
    $cmd_RPMCOMPARE \
        $_ignorepackage_package_ver-$_ignorepackage_package_rel \
        $_ignorepackage_rpm_ver \
        >$g_RPMCOMP
    local -r _ignorepackage_compare_return=$?
    if [[ -e $g_RPMCOMP ]]
    then #{
        fn_cat $LINENO $g_LOGVERBOSE $g_RPMCOMP
        $cmd_RM -f $g_RPMCOMP &>$g_NULL
    fi #}
    fn_unlockfile $LINENO $g_RPMCOMP

    if [[ $_ignorepackage_compare_return == $g_RPMCOMPARE_RET_NEWER ]]
    then #{
        ### patch version greater than installed version, do not ignore
        fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "package \"$_ignorepackage_package_name\" newer than installed version, do not ignore, returning 1"
        return 1
    elif [[ $_ignorepackage_compare_return == $g_RPMCOMPARE_RET_ERR ]]; then #}{
        ### This should only be seen during testing, but may occur in the
        ### field, therefore it's a runtime error.
        fn_exit $FUNCNAME $LINENO RET_RUNTIME_RPMCOMPARE_FAILED "$cmd_RPMCOMPARE call failed"
    fi #}

    ### Should only get here if we want to ignore the package, i.e.,
    ### the indicated version or a newer one is installed.
    return 0
}

################################################################################
### Purpose: Iterates list of packages listed in umd file and compares them to
###          to packages listed in RPM db. In the case of UPGRADE, creates a
###          file named $_fmp_rpms_root which contains a full list of the
###          packages (rpms) passed in. In the case of PATCH, creates up to
###          three files with names $_fmp_rpms_root, $_fmp_rpms_root.ignored
###          and $_fmp_rpms_root.missing. The list of passed in packages (rpms)
###          is iterated and for each package it will be considered "ignored"
###          if it is already installed (i.e. it is in the RPM database) at an
###          equivalent or newer version and release, and will thus be listed
###          in the file $_fmp_rpms_root.ignored. If the package is not
###          "ignored", then it is listed in the file $_fmp_rpms_root.missing
###          if it's NOT listed in the index file ($arg_fmp_index_file), or
###          is listed in the $_fmp_rpms_root file otherwise (i.e., if it IS
###          listed in the index file.)
### Args:    $1 calling $LINENO
###          $2 index_file
###          $3 umd_file
###          $* packages
### Returns: 0 if package found, 1 or 99 if not.
fn_found_missing_packages()
{
    fn_chkargs $FUNCNAME $LINENO $# 4 $g_INTMAX "LINENO, index_file, umd_file, ...packages"
    ### $_arg_fmp_index_file represents an index file that lists packages that
    ### are available on the server. For some protocols, the ability to simply
    ### use 'ls' to generate the list would not work (as the files are not
    ### physically present in local file system) so this index file was
    ### pre-generated and passed as argument.
    local -r _arg_fmp_index_file=$2
    local -r _arg_fmp_umd_file=$3
    local -r _fmp_rpms_root=$g_INFODIR/$_arg_fmp_umd_file.rpms

    shift 3

    local _fmp_umd_type=
    ### TODO: should this be on $g_tmp_dir?
    if ! fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_UPCASE $g_tmp_dir \
            $_arg_fmp_umd_file "SOFTWARETYPE" _fmp_umd_type
    then #{
        ### TODO shouldn't this be a fatal error?
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "fn_get_umd_tag_value $g_tmp_dir $_arg_fmp_umd_file unable to get SOFTWARETYPE, returning 1"
        return 1
    fi #}

    ### For an upgrade, we unconditionally list all the packages and we're done.
    if [[ $_fmp_umd_type == UPGRADE ]]
    then #{
        echo $* >>$_fmp_rpms_root
        fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "SOFTWARETYPE is UPGRADE so returning 1"
        return 1
    fi #}

    ### $_fmp_status is originally set to 1. It gets set to 0 if at least one
    ### of the packages from the passed in package list is not installed or
    ### represents a newer version than the one that is installed, AND it is
    ### not found in the passed in index file.
    local -i    _fmp_status=1

    local -i    _fmp_ignored_count=0
    local -r -i _fmp_package_count=$#
    local       _fmp_package=
    for _fmp_package in $*
    do #{

        ### See if the indicated package is already installed, i.e., appears
        ### in the RPM database and therefore should be ignored.
        if fn_ignore_package $LINENO $_fmp_package
        then #{
            ### the package seems to be either already in rpm db and it
            ### ver/rel is either equal or less than one found in rpm db,
            ### so need to simply ignore it, my need to mark it in the warnings
            echo "$_fmp_package" >>$_fmp_rpms_root.ignored
            ((_fmp_ignored_count++))
            fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "Ignoring package $_fmp_package, already installed"
            continue
        fi #}
        ### If we got to here, we've determined either the package is not
        ### installed, or the one we're checking is newer than the one
        ### installed. If it's not listed in the passed in index file, it's
        ### missing and we list it in the file $_fmp_rpms_root.missing.
        ### If it IS listed in the passed in index file, we list it in
        ### $_fmp_rpms_root
        if ! $cmd_GREP -q -w "$_fmp_package" $_arg_fmp_index_file
        then #{
            ### Determined a package is missing, but we don't stop, as we
            ### want to collect a list of all missing packages.
            echo "$_fmp_package" >>$_fmp_rpms_root.missing
            _fmp_status=0
        else #}{
            echo "$_fmp_package" >>$_fmp_rpms_root
        fi #}

    done #}

    ### This should mark the patch as obsolete, all packages are outdated
    [[ $_fmp_ignored_count == $_fmp_package_count ]] && _fmp_status=99

    return $_fmp_status
}

################################################################################
### Purpose: Generate the index file which will be $g_tmp_dir/index.html. It's
###          actually only an HTML file for protocols that use $cmd_WGET to
###          generate the list, but will be named index.html globally to allow
###          the code to be more generic. Also, protocol usb could simply
###          generate the index file on the fly using ls, but we generate one
###          for all protocols for uniformity, so we don't have to have
###          different logic per protocol later on when we handle the file
###          lists, i.e., we can just go ahead and access the index.html file.
### Args:    $1 calling $LINENO
###          $2 is url
###          $3 is patch_proto
###          $4 is umd_file
###          $5 is passback for error message
###          $6 is samba shared sub folder
### Returns: 0 on success; sets passback error message and returns 1 on failure.
fn_generate_index()
{
    fn_chkargs $FUNCNAME $LINENO $# 5 6 "LINENO, url, patch_proto, umd_file, passback_errmsg"

    local -r _arg_gi_url=$2
    local -r _arg_gi_patch_proto=$3
    local -r _arg_gi_umd_file=$4
    local -r _arg_gi_passback_errmsg=$5
    eval "${_arg_gi_passback_errmsg}=\"\""
    local -r _smb_sub_dir=${6}
    local -i _gi_ret_code=0

    case "$_arg_gi_patch_proto" in #{

        "usb") #{
            if ! $cmd_MOUNTUSB &>$g_NULL
            then #{
                fn_write_event $LINENO I -1 "No usb device attached or it is already mounted"
            fi #}

            if $cmd_MOUNT | $cmd_GREP -q "$g_usbdev"
            then #{

                $cmd_LS -1 $_arg_gi_url/*.rpm >$g_tmp_dir/index.html 2>$g_NULL

            else #}{
                ### problem mounting usb

                eval "${_arg_gi_passback_errmsg}=\"Problem mounting USB\""
                fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Problem mounting USB, returning 1"
                return 1
            fi #}
            $cmd_UMOUNTUSB
            ;; #}

        "http" | "https" | "ftp") #{
            ### $cmd_WGET below will write HTML-ized index of the remote
            ### directory rooted at URL $_arg_gi_url to the file
            ### $g_tmp_dir/index.html.
            $cmd_WGET --no-parent --directory-prefix=$g_tmp_dir -N $_arg_gi_url/ &>$g_WGETLOG
            _gi_ret_code=$?
            if fn_found_error $LINENO $_gi_ret_code \
                    $g_WGETLOG $_arg_gi_passback_errmsg
            then #{
                fn_log $g_LOGALWAYS $FUNCNAME $LINENO "${!_arg_gi_passback_errmsg}, returning 1"
                return 1
            fi #}
            ;; #}

        "samba") #{
            local -r _gi_index_file=$g_tmp_dir/index.html
            if [ $_smb_sub_dir == "." ]; then
              $cmd_SMBCLIENT -E $_arg_gi_url -c "prompt; ls *.rpm" &>$_gi_index_file 
            else 
              ### The following works only in WIN SHARE/SAMBA DIR
              $cmd_SMBCLIENT -E $_arg_gi_url -c "prompt; cd $_smb_sub_dir; ls *.rpm" &>$_gi_index_file 
            fi 
            _gi_ret_code=$?
            if fn_found_error $LINENO $_gi_ret_code \
                    $_gi_index_file $_arg_gi_passback_errmsg
            then #{
                eval "${_arg_gi_passback_errmsg}=\"${!_arg_gi_passback_errmsg} ${cmd_WGET}\""
                fn_log $g_LOGALWAYS $FUNCNAME $LINENO "${!_arg_gi_passback_errmsg} $cmd_WGET\, returning 1"
                return 1
            fi #}
            ;; #}

        "em") #{
            local -r _gi_index_file=$g_tmp_dir/index.html
            echo "" >$_gi_index_file
            ### this is to bypass EM limitation, which does not allow us to
            ### see what RPMs are actually there on my computer, as opposed
            ### to with, let's say ftp method, where one can use wget to query
            ### what files are on the server. Here we simply assume the files
            ### are there by dumping list of RPMs from umd file itself into
            ### the file indicated by $_gi_index_file, so that, everything
            ### is treated uniformly, otherwise, need to make a special case
            ### of it, which would bring us to same thing anyway.
            if ! $cmd_XPATHPARSE $g_tmp_dir/$_arg_gi_umd_file \
                    "//PACKAGE/text()" >&$g_NULL
            then #{
                eval "${_arg_gi_passback_errmsg}=\"Error fetching tag PACKAGE in file $g_tmp_dir/$_arg_gi_umd_file\""
                fn_log $g_LOGALWAYS $FUNCNAME $LINENO "${!_arg_gi_passback_errmsg}, returning 1"
                return 1
            fi #}

            ### TODO: Do we really want PACKAGE1 stuff? Legacy didn't do this.
            local _gi_pkg=
            while read -r _gi_pkg
            do #{
                echo "$_gi_pkg" >>$_gi_index_file
            done < <($cmd_XPATHPARSE $g_tmp_dir/$_arg_gi_umd_file "//PACKAGE/text() | //PACKAGE1/text()" 2>$g_NULL) #}

            ;; #}

    esac #}

    return 0
}

################################################################################
### Purpose: Generate the $g_INFODIR/$_arg_gep_umd_file.<proto> file. This is
###          not the .proto file which contains the protocol used, but the file
###          NAMED by the protocol (e.g., <proto> is '.em' or '.ftp', etc.) and
###          which holds the encrypted connection information for the protocol,
###          e.g. for protocol 'em' the file would be named
###          $_arg_gep_umd_file.em.
### Args:    $1 calling $LINENO
###          $2 is url
###          $3 is patch_proto
###          $4 is umd_file
###          $5 is passback for error message
### Returns: 0 on success; sets passback error message and returns 1 on failure.
fn_generate_encrypted_proto()
{
    fn_chkargs $FUNCNAME $LINENO $# 5 5 "LINENO, url, patch_proto, umd_file, passback_errmsg"

    local -r _arg_gep_url=$2
    local -r _arg_gep_patch_proto=$3
    local -r _arg_gep_umd_file=$4
    local -r _arg_gep_passback_errmsg=$5
    eval "${_arg_gep_passback_errmsg}=\"\""

    local _gep_encryption_key=
    if ! fn_get_urandom_key $LINENO _gep_encryption_key
    then #{
        eval "${_arg_gep_passback_errmsg}=\"Could not get random key\""
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Could not get random key, returning 1"
        return 1
    fi #}

    local -r _gep_directory="/tmp/$_arg_gep_umd_file"
    $cmd_RM -rf $_gep_directory &>$g_NULL

    $cmd_MKDIR -p $_gep_directory &>$g_NULL
    if [[ $? != 0 ]]
    then #{
        eval "${_arg_gep_passback_errmsg}=\"Could not make directory $_gep_directory\""
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Could not make directory $_gep_directory, returning 1"
        return 1
    fi #}

    fn_hide_key $LINENO $_gep_directory $_gep_encryption_key
    if [[ $? -ne 0 ]]
    then #{
        eval "${_arg_gep_passback_errmsg}=\"fn_hide_key failed\""
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "fn_hide_key failed, returning 1"
        return 1
    fi #}

    ### Remove the $g_INFODIR/$_arg_gep_umd_file.<proto> file. It is
    ### re-generated below.
    $cmd_RM -f $g_INFODIR/$_arg_gep_umd_file.$_arg_gep_patch_proto &>$g_NULL

    ### Now generate the $g_INFODIR/$_arg_gep_umd_file.<proto> file.
    fn_encrypt_data $LINENO $_gep_encryption_key "$_arg_gep_url" \
        $g_INFODIR/$_arg_gep_umd_file.$_arg_gep_patch_proto
    if [[ $? -ne 0 ]]
    then #{
        eval "${_arg_gep_passback_errmsg}=\"fn_encrypt_data failed\""
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "fn_encrypt_data failed, returning 1"
        return 1
    fi #}

    return 0
}

################################################################################
### Purpose: This function, a helper function for fn_build_list(), checks rpm
###          packages on the server. Could be remote (http|https|ftp|samba) or
###          local file system (usb|em). The major purpose of this function is
###          to identify a list of rpms to be applied. It checks the content
###          of the patch, as opposed the patch itself, which is what
###          fn_build_list does. It calls fn_found_missing_packages() which
###          generates the .rpms files.
###          --- ??? --- need a bit of  more work in here
### Args:    $1  calling $LINENO
###          $2  is uxd_file
###          $3  is umd_name
###          $4  is umd_ver
###          $5  is umd_rel
###          $6  is url
###          $7  is patch_proto
###          $8  is umd_file
###          $9  is passback for status, set to Invalid or Obsolete
###          $10 is passback for error message
###          $11 is samba shared sub folder
### Returns: 0 on success, 1 on failure.
fn_check_for_packages()
{
    fn_chkargs $FUNCNAME $LINENO $# 10 13 "LINENO, uxd_file, umd_name, umd_ver, ume_rel, url, patch_proto, umd_file, passback_status, passback_errmsg"
    ### Note that positional parameters greater than 9 must be enclosed
    ### in braces.
    local -r _arg_cfp_uxd_file=$2
    local -r _arg_cfp_umd_name=$3
    local -r _arg_cfp_umd_ver=$4
    local -r _arg_cfp_umd_rel=$5
    local -r _arg_cfp_url=$6
    local -r _arg_cfp_patch_proto=$7
    local -r _arg_cfp_umd_file=$8
    local -r _arg_cfp_passback_status=$9
    local -r _arg_cfp_passback_errmsg=${10}
    eval "${_arg_cfp_passback_errmsg}=\"\""
    local -r _smb_sub_dir=${11}
    

    local _cfp_umd_packages=
    if ! fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_RAW $g_tmp_dir \
            $_arg_cfp_umd_file "PACKAGE" _cfp_umd_packages
    then #{
        eval "${_arg_cfp_passback_status}=\"Invalid\""
        eval "${_arg_cfp_passback_errmsg}=\"fn_get_umd_tag_value error\""
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "fn_get_umd_tag_value error fetching PACKAGE, status \"${!_arg_cfp_passback_status}\", returning 1"
        return 1
    fi #}

    ### do some cleaning before processing
    $cmd_RM -f $g_INFODIR/$_arg_cfp_umd_file.rpm* &>$g_NULL

    ### Generate the index file.
    ### Note we pass the value of $_arg_cfp_passback_errmsg
    if ! fn_generate_index $LINENO "$_arg_cfp_url" $_arg_cfp_patch_proto \
        $_arg_cfp_umd_file $_arg_cfp_passback_errmsg $_smb_sub_dir
    then #{
        eval "${_arg_cfp_passback_status}=\"Invalid\""
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "fn_generate_index failed, error \"${!_arg_cfp_passback_errmsg}\" status ${!_arg_cfp_passback_status}, returning 1"
        return 1
    fi #}

    ### If go to this spot, means there was some fn_scan_method used to get
    ### here, which produced the index file ($g_tmp_dir/index.html.) All is
    ### needed now is go through rpms found and compare them to index file
    ### and rpm db itself so that rpm packages to be ignored and missing can
    ### be identified.
    fn_found_missing_packages $LINENO $g_tmp_dir/index.html \
        $_arg_cfp_umd_file $_cfp_umd_packages
    local -r -i _cfp_found_return=$?
    if [[ $_cfp_found_return == 0 ]]
    then #{

        eval "${_arg_cfp_passback_status}=\"Invalid\""

        ### also log it and pass it to EM
        fn_write_event $LINENO W -1 "Missing packages in $_arg_cfp_umd_name $($cmd_CAT $g_INFODIR/$_arg_cfp_umd_file.rpms.missing)"
        echo "Missing packages in $_arg_cfp_umd_name" >>$g_READMEDIR/Warnings-$_arg_cfp_umd_name-$_arg_cfp_umd_ver-$_arg_cfp_umd_rel.txt
        $cmd_CAT $g_INFODIR/$_arg_cfp_umd_file.rpms.missing >>$g_READMEDIR/Warnings-$_arg_cfp_umd_name-$_arg_cfp_umd_ver-$_arg_cfp_umd_rel.txt

    elif [[ $_cfp_found_return == 99 ]]; then #}{

        eval "${_arg_cfp_passback_status}=\"Obsolete\""
        echo "Newer version of software already installed." >>$g_READMEDIR/Warnings-$_arg_cfp_umd_name-$_arg_cfp_umd_ver-$_arg_cfp_umd_rel.txt
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Newer version of software already installed."
    fi #}

    if [[ -e "$g_INFODIR/$_arg_cfp_umd_file.rpms.ignored" ]]
    then #{
        ### there were some packages ignored, maybe log it and just pass it on
        ### to EM
        fn_write_event $LINENO W -1 "Ignored packages in $_arg_cfp_umd_name $($cmd_CAT $g_INFODIR/$_arg_cfp_umd_file.rpms.ignored)"
        $cmd_CAT $g_INFODIR/$_arg_cfp_umd_file.rpms.ignored >>$g_READMEDIR/Warnings-$_arg_cfp_umd_name-$_arg_cfp_umd_ver-$_arg_cfp_umd_rel.txt
    fi #}

    ### Tag PACKAGE1 doesn't necessarily have to exist, so we ignore the
    ### return value and let fn_get_umd_tag_value do the logging.
    ### TODO: Should PACKAGE1 code be combined with PACKAGE code above?
    ### The logic is slightly different (doesn't consider the
    ### return value of fn_found_missing_packages)
    _cfp_umd_packages=
    fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_RAW $g_tmp_dir \
        $_arg_cfp_umd_file  "PACKAGE1" _cfp_umd_packages
    if [[ $_cfp_umd_packages ]]
    then #{
        if fn_found_missing_packages $LINENO $g_tmp_dir/index.html \
            $_arg_cfp_umd_file $_cfp_umd_packages
        then #{

            eval "${_arg_cfp_passback_status}=\"Invalid\""

            ### also log it and pass it to EM
            fn_write_event $LINENO W -1 "Missing packages in $_arg_cfp_umd_name $($cmd_CAT $g_INFODIR/$_arg_cfp_umd_file.rpms.missing)"
            echo "Missing packages in $_arg_cfp_umd_name" >>$g_READMEDIR/Warnings-$_arg_cfp_umd_name-$_arg_cfp_umd_ver-$_arg_cfp_umd_rel.txt
            $cmd_CAT $g_INFODIR/$_arg_cfp_umd_file.rpms.missing >>$g_READMEDIR/Warnings-$_arg_cfp_umd_name-$_arg_cfp_umd_ver-$_arg_cfp_umd_rel.txt
        fi #}

        if [[ -e "$g_INFODIR/$_arg_cfp_umd_file.rpms.ignored" ]]
        then #{
            ### there were some packages ignore, maybe log it and just pass
            ### it on to EM
            fn_write_event $LINENO W -1 "Ignored packages in $_arg_cfp_umd_name $($cmd_CAT $g_INFODIR/$_arg_cfp_umd_file.rpms.ignored) <- $LINENO of $g_PROGNAME"
            echo "Ignored packages in $_arg_cfp_umd_name" >>$g_READMEDIR/Warnings-$_arg_cfp_umd_name-$_arg_cfp_umd_ver-$_arg_cfp_umd_rel.txt
            $cmd_CAT $g_INFODIR/$_arg_cfp_umd_file.rpms.ignored >>$g_READMEDIR/Warnings-$_arg_cfp_umd_name-$_arg_cfp_umd_ver-$_arg_cfp_umd_rel.txt
        fi #}
    fi #}

    if ! fn_generate_encrypted_proto $LINENO "$_arg_cfp_url" \
            $_arg_cfp_patch_proto $_arg_cfp_umd_file $_arg_cfp_passback_errmsg
    then #{
        eval "${_arg_cfp_passback_status}=\"Invalid\""
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "fn_generate_encrypted_proto failed, error \"${!_arg_cfp_passback_errmsg}\" status ${!_arg_cfp_passback_status}, returning 1"
        return 1
    fi #}

    ### Copy the specified umd and uxd files from $g_tmp_dir to $g_INFODIR.
    $cmd_CP -f $g_tmp_dir/{$_arg_cfp_umd_file,$_arg_cfp_uxd_file} $g_INFODIR

    return 0
}

################################################################################
### Purpose: Given an rpm name, this function will return the raw name,
###          version and release. Also works with ranged rpm specifications
###          as contained within the <REQUIRES> XML tags in the umd file,
###          which appear like so:
###              <REQUIRES>something</REQUIRES>
###          The "something" can be a rpm name, or can be an rpm name followed
###          by a lexical comparator followed by a version, e.g., 2.0.2.05, or
###          the version and release, e.g., 2.0.2.05-2. Valid lexical
###          comparators are listed here:
###              Comparator  Meaning
###              ----------  --------------------------------------------------
###              >= or =>    greater than or equal to
###              >           greater than
###              <= or =<    less than or equal to, < must be expressed as &lt;
###              <           less than, < must be expressed as &lt;
###              =           equal to
###          Here are some sample REQUIRES specifications, numbered so we can
###          explain them in a moment:
###              (1) <REQUIRES>system-release</REQUIRES>
###              (2) <REQUIRES>system-release >= 2.0.2.05</REQUIRES>
###              (3) <REQUIRES>system-release => 2.0.2.05</REQUIRES>
###              (4) <REQUIRES>system-release >= 2.0.2.05-4</REQUIRES>
###              (5) <REQUIRES>system-release &lt;= 2.0.2.05-4</REQUIRES>
###          So looking at the sample REQUIRES specifications above:
###          - Specification (1) shows a REQUIRES specification with no version
###            requirements
###          - Specification (2) and (3) show REQUIRES specifications with
###            version requirements, but no release requirements.
###          - Specification (4) shows a REQUIRES specification with version
###            (the 2.0.2.05-4 part) and release (the 4 part) requirements.
###          - You will note that specification (2) and (3) are actually the
###            same, using two different forms of the "greater than or equal
###            to" lexical comparator.
###          - Note the use of text "&lt;" in (5), this is because the umd
###            file is actually an XML file, and you must use the text "&lt;"
###            (without the quotes) to express a literal less-than symbol in
###            an XML file.
### Args:    $1 calling $LINENO
###          $2 rpmname
###          $3 passback for name
###          $4 passback for version
###          $5 passback for release
### Returns: 0
fn_parse_rpm()
{
    fn_chkargs $FUNCNAME $LINENO $# 5 5 "LINENO, rpmname, passback_name, passback_ver, passback_rel"

    local    _arg_parse_rpm=$2
    local -r _arg_parse_rpm_passback_name=$3
    local -r _arg_passback_ver=$4
    local -r _arg_passback_rel=$5

    local _parse_rpm_name=
    local _parse_rpm_ver=
    local _parse_rpm_rel=

    ### $_arg_parse_rpm is the RPM as name-version-release, and may have
    ### trailing .$g_arch.rpm, .$g_arch.umd, .$g_arch.uxd, and/or spaces.
    ### We need to strip off the trailing .$g_arch.{rpm,umd,uxd} and/or
    ### spaces if they exist. It may also have a path but that's stripped
    ### off later.
    _arg_parse_rpm=${_arg_parse_rpm/\.$g_arch\.*/}
    _arg_parse_rpm=${_arg_parse_rpm// /}

    ### Check to see if the rpm has range (i.e., lexical comparators such as
    ### '>', '<', '=' or some combination of same) specified.
    if [[ $(echo $_arg_parse_rpm | $cmd_GREP "[>=<]" 2>$g_NULL) ]]
    then #{

        ### The rpm has range specified, so we're in luck as the only thing
        ### to the left of the range is guaranteed to be the name.
        _parse_rpm_name=${_arg_parse_rpm%%[>=<]*}

        ### Again, we know the part to the right of the range is the
        ### "version" or the "version-release", so let's store it
        ### temporarily in $_parse_rpm_ver.
        _parse_rpm_ver=${_arg_parse_rpm##*[>=<]}

        ### Now $_parse_rpm_ver either contains "version-release" or just the
        ### "version" with "release" being empty. We'll test for the dash
        ### character and if it exists, we do some further processing. If it
        ### does not exist, $_parse_rpm_ver already contains the "version",
        ### but we set the "release" to "0".
        if [[ $(echo $_parse_rpm_ver | $cmd_GREP "-" 2>$g_NULL) ]]
        then #{
            ### There is a dash character in $_parse_rpm_ver, so we can
            ### parse out the "release", and then adjust $_parse_rpm_ver
            ### to actually contain the "version".
            _parse_rpm_rel=${_parse_rpm_ver##*-}
            _parse_rpm_ver=${_parse_rpm_ver%%-*}
        else #}{
            _parse_rpm_rel=0
        fi #}

    else #}{

        ### The rpm naming conventions require that the version and
        ### release may not contain a dash character, but the name may,
        ### so we will use that fact to work our way backwards from the
        ### release. First, let's get the release:
        _parse_rpm_rel=${_arg_parse_rpm##*-}

        ### Now we can remove the "-release" from the end and have
        ### the "name-version" part. Let's store it temporarily in
        ### _parse_rpm_name.
        _parse_rpm_name=${_arg_parse_rpm/-$_parse_rpm_rel}

        ### Now we can use the "name-version" part in $_parse_rpm_name
        ### to determine the "version" part, and once we know that we can
        ### correct $_parse_rpm_name to hold the "name" part.
        _parse_rpm_ver=${_parse_rpm_name##*-}
        _parse_rpm_name=${_parse_rpm_name/-$_parse_rpm_ver}

    fi #}

    eval "${_arg_parse_rpm_passback_name}=\"$(basename $_parse_rpm_name)\""
    eval "${_arg_passback_ver}=\"$_parse_rpm_ver\""
    eval "${_arg_passback_rel}=\"$_parse_rpm_rel\""

    return 0
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 umd_name
###          $3 umd_ver
###          $4 umd_rel
###          $* requires_list
### Returns: 0 if not found, 1 if found
fn_patch_does_not_meet_requires()
{
    fn_chkargs $FUNCNAME $LINENO $# 5 $g_INTMAX "LINENO, umd_name, umd_ver, umd_rel, ...requires_list"

    ### Function name is fn_patch_does_not_meet_requires, so the prefix is
    ### shortened to _pdnmr
    local -r _arg_pdnmr_umd_name=$2
    local -r _arg_pdnmr_umd_ver=$3
    local -r _arg_pdnmr_umd_rel=$4

    shift 4
    local -r _arg_pdnmr_requires_list=$*
    fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "Requirement list is \"$_arg_pdnmr_requires_list\""

    local -i _pdnmr_foundstatus=1
    local    _pdnmr_rpm_v=
    local    _pdnmr_rpm_r=
    local    _pdnmr_name=
    local    _pdnmr_req_ver=
    local    _pdnmr_req_rel=

    local    _pdnmr_require=
    for _pdnmr_require in $_arg_pdnmr_requires_list
    do #{

        ### Requires can be absolute, e.g., X is required, or versioned,
        ### e.g., X must be greater than or equal to a specific version.
        ### See documentation under fn_parse_rpm.
        if [[ $(echo "$_pdnmr_require" | $cmd_GREP "[>=<]" 2>$g_NULL) ]]
        then #{

            fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "Requirement \"$_pdnmr_require\" has range"
            ### Get the patch name and release-version from $_pdnmr_require.
            fn_parse_rpm $LINENO "$_pdnmr_require" \
                _pdnmr_name _pdnmr_req_ver _pdnmr_req_rel

            ### we are not interested if it is not installed, later logic
            ### catches this, so we only need to check for NAME here.
            if fn_get_rpm_tag_value $FUNCNAME $LINENO \
                    $_pdnmr_name "NAME" g_dummy
            then #{

                ### it is in rpm db, it should have ver-rel, get it
                fn_get_rpm_tag_value $FUNCNAME $LINENO $_pdnmr_name \
                    "VERSION" _pdnmr_rpm_v || continue
                fn_get_rpm_tag_value $FUNCNAME $LINENO $_pdnmr_name \
                    "RELEASE" _pdnmr_rpm_r || _pdnmr_rpm_r=0

                if fn_requires_satisfied $LINENO \
                    "$_pdnmr_require" $_pdnmr_name \
                    $_pdnmr_rpm_v $_pdnmr_rpm_r \
                    $_pdnmr_req_ver $_pdnmr_req_rel
                then #{
                    ### This requirement is satisfied, go on to the next one.
                    fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "Requirement \"$_pdnmr_require\" satisfied"
                    continue
                fi #}

                ### The package $_pdnmr_name is installed but the requirement
                ### range is not satisfied, therefore this patch has at least
                ### one unsatisfied requirement.
                fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "Requirement \"$_pdnmr_require\" unsatisfied, returning 0"
                return 0
            fi #}
        else #}{
            ### check rpm db first, go to next upon success, otherwise
            ### check if has been scheduled to get there
            fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "Requirement \"$_pdnmr_require\" does not have range"
            if $cmd_RPM -q $_pdnmr_require &>$g_NULL
            then #{
                continue
            fi #}
        fi #}

        ### TODO fix this! Original comment follows:
        ### see if has been scheduled: this needs to be really thought
        ### through, since if has been scheduled may show patch as available,
        ### however it is really only for scheduling purposes, although the
        ### user see it as being available and might try to apply it, where it
        ### would fail by rpm since the dependency is nor really in rpm db
        [[ -e "$g_INFODIR/$_pdnmr_require.$g_arch.umd.scd" ]] && continue

        ### the above rules are not satisfied, the package becomes invalid,
        ### by default it is always available
        _pdnmr_foundstatus=0
        fn_write_event $LINENO I -1 "WARNING: Please apply the $_pdnmr_require update prior to installing the $_arg_pdnmr_umd_name update"
        echo "WARNING: Please apply the $_pdnmr_require update prior to installing the $_arg_pdnmr_umd_name update" >>$g_READMEDIR/Warnings-$_arg_pdnmr_umd_name-$_arg_pdnmr_umd_ver-$_arg_pdnmr_umd_rel.txt
    done #}

    [[ 0 == $_pdnmr_foundstatus ]] \
        && fn_log $g_LOGALWAYS $FUNCNAME $LINENO "requirements not met umd_name=\"$_arg_pdnmr_umd_name\" umd_ver=\"$_arg_pdnmr_umd_ver\" umd_rel=\"$_arg_pdnmr_umd_rel\" requires=\"$_arg_pdnmr_requires_list\", returning 0" \
        || fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "requirements met umd_name=\"$_arg_pdnmr_umd_name\" umd_ver=\"$_arg_pdnmr_umd_ver\" umd_rel=\"$_arg_pdnmr_umd_rel\" requires=\"$_arg_pdnmr_requires_list\", returning 1"
    return $_pdnmr_foundstatus ### 0 if not found, 1 if found
}

################################################################################
### Purpose: Helper function which checks the specified directory to ensure
###          the .umd and .uxd files exist.
### Args:    $1 calling $LINENO
###          $2 dir to search
### Returns: 0 on success, 1 on failure
fn_checkfor_umds_uxds()
{
    fn_chkargs $FUNCNAME $LINENO $# 2 2 "LINENO, dir"
    local -r _arg_find_patches_dir=$2

    ### Check for .umd files.
    if ! $cmd_LS $_arg_find_patches_dir/*.umd &>$g_NULL
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$_arg_find_patches_dir/*.umd not found, returning 1"
        return 1
    fi #}

    ### Check for .uxd files.
    if ! $cmd_LS $_arg_find_patches_dir/*.uxd &>$g_NULL
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$_arg_find_patches_dir/*.uxd not found, returning 1"
        return 1
    fi #}

    return 0
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 url
###          $3 patch_proto
###          $4 passback for error message
###          $5 samba SubFolder
### Note:    Calls fn_check_for_packages()
### Returns: 0 on success, 1 on failure
fn_build_list()
{
    fn_chkargs $FUNCNAME $LINENO $# 4 5 "LINENO, url, patch_proto, passback_errmsg"
    local -r _arg_bl_url=$2
    local -r _arg_bl_patch_proto=$3
    local -r _arg_bl_passback_err_msg=$4
    eval "${_arg_bl_passback_err_msg}=\"\""
    local -r _smb_sub_dir=$5

    ### NOW: this building status should be updated with % as each umd file
    ### is processed, could be count each umd out of total umds
    fn_write_status $LINENO "Building "
    fn_write_event $LINENO I -1 "Building ... "

    if [[ ! -d $g_tmp_dir ]]
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Directory \"$g_tmp_dir\" missing,returning 1"
        return 1
    fi #}

    ### No need to go ahead if there are no *.umd AND *.uxd files in temp dir.
    ### They are downloaded by the fn_scan_ functions.
    if ! fn_checkfor_umds_uxds $LINENO $g_tmp_dir
    then #{
        eval "${_arg_bl_passback_err_msg}=\"No_Files Could not find any patches in $g_tmp_dir\""
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "${!_arg_bl_passback_err_msg}, returning 1"
        return 1
    fi #}

    local    _bl_umd_reboot=
    local    _bl_umd_warnings=
    local    _bl_umd_desc=
    local    _bl_umd_name_ver_rel=

    local    _bl_uxd_file=
    local    _bl_umd_path=
    local    _bl_umd_file=
    local    _bl_umd_name=
    local    _bl_umd_ver=
    local    _bl_umd_rel=
    local    _bl_umd_size=
    local    _bl_check_for_packages_err_msg=
    local    _bl_requires=
    local    _bl_requires_list=
    local    _bl_rpm_name=
    local    _bl_rpm_ver=
    local    _bl_rpm_rel=
    local    _bl_keycode=
    local    _bl_keycode_id=
    local    _bl_keycode_value=
    local    _bl_code_value=
    local -i _bl_umd_sign_retval=
    local -i _bl_rpmcomp_ret=
    local -i _reboot_status=

    ### _bl_packages_status and _bl_internal_status may be one of the
    ### _bl_ps_ constants.
    local -r _bl_ps_AVAILABLE=Available
    local -r _bl_ps_APPLIED=Applied
    local -r _bl_ps_OBSOLETE=Obsolete
    local -r _bl_ps_SCHEDULE=Schedule
    local -r _bl_ps_INVALID=Invalid
    local    _bl_packages_status=$_bl_ps_INVALID
    local    _bl_internal_status=

    ### It is guaranteed $($cmd_LS -1 $g_tmp_dir/*.umd) exists due to
    ### fn_checkfor_umds_uxds check above.
    local -r _bl_umd_files=$($cmd_LS -1 $g_tmp_dir/*.umd 2>$g_NULL)
    fn_log $g_LOGWARN $FUNCNAME $LINENO "Processing umd files \"$_bl_umd_files\""
    for _bl_umd_path in $_bl_umd_files
    do #{
        _bl_umd_file=$(basename $_bl_umd_path)
        fn_log $g_LOGWARN $FUNCNAME $LINENO "processing umd_file=\"$_bl_umd_file\""
        ### TITLE is mandatory in the .umd files.
        if ! fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_RAW $g_tmp_dir \
                $_bl_umd_file "TITLE" _bl_umd_name
        then #{
            ### need to log this fact into warning/logs, etc. --- ????
            fn_write_event $LINENO I -1 "Ignoring $_bl_umd_file ... <- $LINENO of $g_PROGNAME"
            continue
        fi #}

        ### if you get this far you are guaranteed that ver and rel has
        ### some values
        if ! fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_RAW $g_tmp_dir \
                $_bl_umd_file "VERSION" _bl_umd_ver
        then #{
            ### this is more or less for completeness, since if can query the
            ### name of package from rpm db and fail to query its version is
            ### when something really goes wrong, e.g. db gets deleted right
            ### after it has been queried, no point of going on like that
            eval "${_arg_bl_passback_err_msg}=\"DB_Error Could not query get VERSION tag from  $_bl_umd_file in $g_tmp_dir directory\""
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "${!_arg_bl_passback_err_msg}, returning 1"
            return 1
        fi #}

        if [[ $gscr_CHECKSIG == yes ]]
        then #{
            $cmd_UMD_SIGN validate $_bl_umd_path
            _bl_umd_sign_retval=$?
            if [[ $_bl_umd_sign_retval -ne 0 ]]
            then #{
                eval "${_arg_bl_passback_err_msg}=\"DB_Error UMD file $_bl_umd_file was not properly signed\""
                fn_log $g_LOGALWAYS $FUNCNAME $LINENO "${!_arg_bl_passback_err_msg}, $cmd_UMD_SIGN returned $_bl_umd_sign_retval, continue"
                continue
            fi #}
        fi #}

        ### Failure to get RELEASE should not return, just log
        if ! fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_RAW $g_tmp_dir \
                $_bl_umd_file "RELEASE" _bl_umd_rel
        then #{
            eval "${_arg_bl_passback_err_msg}=\"DB_Error Could not query get RELEASE tag from $_bl_umd_file in $g_tmp_dir directory\""
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "${!_arg_bl_passback_err_msg}, continue"
        fi #}

        ### Verify UXD file signature
        _bl_umd_name_ver_rel=$_bl_umd_name-$_bl_umd_ver-$_bl_umd_rel
        _bl_uxd_file="$_bl_umd_name_ver_rel.$g_arch.uxd"
        fn_verify_uxd $LINENO $g_tmp_dir/$_bl_uxd_file $_bl_umd_path
        if [[ $? != 0 ]]
        then #{
            ### TODO does not cause update to abort, but does log the
            ### signature check failure. Improve this. Should probably
            ### use fn_write_event. This problem exists elsewhere too.
            eval "${_arg_bl_passback_err_msg}=\"DB_Error UXD file $_bl_uxd_file was not properly signed\""
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "${!_arg_bl_passback_err_msg}, continue"
            continue
        fi #}

        ### NEED TO DECIDE HOW TO TREAT READMEs and WARNINGs files - ???

        ### warnings file is updated requires check function to show what has
        ### been missing if anything
        $cmd_RM -f $g_READMEDIR/Warnings-$_bl_umd_name_ver_rel.txt &>$g_NULL
        $cmd_TOUCH $g_READMEDIR/Warnings-$_bl_umd_name_ver_rel.txt

        ### at least one uxd file guaranteed, however need to check whether
        ### the correct one exists
        ### in case if does not exist need to continue next umd, however
        ### need to note in warnings or logs etc ???
        if [[ ! -e $g_tmp_dir/$_bl_uxd_file ]]
        then #{
            fn_write_event $LINENO I -1 "Missing upgrade description file $_bl_uxd_file for $_bl_umd_file in $g_tmp_dir, continuing to build list"
            fn_write_event $LINENO I -1 "$($cmd_LS -al $g_tmp_dir 2>$g_NULL)"
            _bl_uxd_file=
            continue
        fi #}

        ### fn_patch_does_not_meet_requires() which may be called below
        ### takes the requirements list as a space separated string. Let's
        ### generate the requirements list string.
        _bl_requires_list=
        while read -r _bl_requires
        do #{
            ### Note the removal of spaces in _bl_requires.
            _bl_requires_list="$_bl_requires_list ${_bl_requires// /}"
        done < <($cmd_XPATHPARSE $_bl_umd_path "//REQUIRES/text()" 2>$g_NULL) #}

        ### The algorithm above will add a leading space to $_bl_requires_list,
        ### so we strip any leading spaces. This may result in making the
        ### string empty.
        _bl_requires_list=${_bl_requires_list## }

        ### So, if $_bl_requires_list is not empty, there are requirements
        ### present. Check if the patch matches it against the system, and
        ### if not then only make it invalid
        if [[ $_bl_requires_list ]]
        then #{

            ### need to handle this system-release specified in the patch
            ### relative to the one on the system, see more comments inside
            ### function
            ### note, requires does not have to contain only system-release
            ### package, could be more, also, we can handle all this in the
            ### Requires field of the wrapper, the idea is to have these
            ### requires relate to other patches, system-release, upgrades,
            ### the requires inside wrapper (uxd file)
            ### really just ties together itself with its content and maybe
            ### other patches but via its content (rpms) not the other
            ### wrappers, which what this requires in umd file is for, this
            ### feature is not utilized much, but it carried here from the
            ### original design and can be used but what for ???.
            fn_log $g_LOGWARN $FUNCNAME $LINENO "umd_file=\"$_bl_umd_file\" has requirements=\"$_bl_requires_list\", checking"

            ### If patch doesn't meet requires list, we log that and set
            ### _bl_internal_status=$_bl_ps_INVALID, but that's it, we don't
            ### 'return' or 'continue'.
            if fn_patch_does_not_meet_requires $LINENO \
                $_bl_umd_name $_bl_umd_ver \
                $_bl_umd_rel $_bl_requires_list
            then #{
                _bl_internal_status=$_bl_ps_INVALID
                fn_log $g_LOGALWAYS $FUNCNAME $LINENO "umd_file=\"$_bl_umd_file\" fails requirements check on requirements=\"$_bl_requires_list\""
            fi #}
        else #}{
            ### else there was no requirements for this umd file.
            fn_log $g_LOGWARN $FUNCNAME $LINENO "umd_file=\"$_bl_umd_file\" has no requirements to check"
        fi #}

        if ! fn_get_rpm_tag_value $FUNCNAME $LINENO $_bl_umd_name \
                "NAME" _bl_rpm_name
        then #{
            ### if non-zero returned means package is not installed
            ### otherwise rpm name/ver/rel are guaranteed to be non-empty
            ### means not installed, Available, all Available should be check
            ### for availability of corresponding RPMs, if not found status
            ### goes to Partial

            ### when returns for wrong parameters, do we really need this ???

            ### assume Available, gets overwritten in check for packages if not
            ### all packages are found
            _bl_packages_status=$_bl_ps_AVAILABLE
            if ! fn_check_for_packages $LINENO $_bl_uxd_file \
                $_bl_umd_name $_bl_umd_ver $_bl_umd_rel "$_arg_bl_url" \
                $_arg_bl_patch_proto $_bl_umd_file \
                _bl_packages_status _bl_check_for_packages_err_msg $_smb_sub_dir
            then #{
                fn_write_event $LINENO I -1 "$_bl_check_for_packages_err_msg"
                ### TODO consider adding 'continue' here.
            fi #}
        else #}{
            fn_get_rpm_tag_value $FUNCNAME $LINENO $_bl_rpm_name \
                "VERSION" _bl_rpm_ver || continue
             $cmd_RPMCOMPARE $_bl_umd_ver  $_bl_rpm_ver >&$g_NULL
             _bl_rpmcomp_ret=$?
            ### if umd ver/rel is greater than rpm ver/rel means Available
            if [[ 1 -eq $_bl_rpmcomp_ret ]]
            then #{

                _bl_packages_status=$_bl_ps_AVAILABLE
                if ! fn_check_for_packages $LINENO $_bl_uxd_file \
                    $_bl_umd_name $_bl_umd_ver $_bl_umd_rel "$_arg_bl_url" \
                    $_arg_bl_patch_proto $_bl_umd_file \
                    _bl_packages_status _bl_check_for_packages_err_msg $_smb_sub_dir
                then #{
                    fn_write_event $LINENO I -1 "$_bl_check_for_packages_err_msg <- $LINENO of $g_PROGNAME"
                fi #}

            elif [[ 0 -eq $_bl_rpmcomp_ret ]]; then #}{

                ### same, need to check for umd rel and rpm rel
                fn_get_rpm_tag_value $FUNCNAME $LINENO $_bl_rpm_name \
                    "RELEASE" _bl_rpm_rel || continue

                $cmd_RPMCOMPARE $_bl_umd_rel  $_bl_rpm_rel >&$g_NULL
                 _bl_rpmcomp_ret=$?
                if [[ 1 -eq $_bl_rpmcomp_ret ]]
                then #{
                    _bl_packages_status=$_bl_ps_AVAILABLE
                    if ! fn_check_for_packages $LINENO $_bl_uxd_file \
                        $_bl_umd_name $_bl_umd_ver $_bl_umd_rel "$_arg_bl_url" \
                        $_arg_bl_patch_proto $_bl_umd_file \
                        _bl_packages_status _bl_check_for_packages_err_msg $_smb_sub_dir
                    then #{
                        fn_write_event $LINENO I -1 "$_bl_check_for_packages_err_msg <- $LINENO of $g_PROGNAME"
                    fi #}
                elif [[ 0 -eq $_bl_rpmcomp_ret ]]; then  #}{
                    ### if umd rel is equal to rpm rel means Applied
                    _bl_packages_status=$_bl_ps_APPLIED
                else #}{
                    ### means Obsolete
                    _bl_packages_status=$_bl_ps_OBSOLETE
                fi #}

            else #}{

                ### otherwise Obsolete, umd ver/rel is less than rpm ver/rel
                _bl_packages_status=$_bl_ps_OBSOLETE

            fi #}
        fi #}

        ### fn_get_umd_tag_value logs when it can't read a tag, so in the next
        ### few calls to fn_get_umd_tag_value we only check the return value if
        ### we have a need for additional conditional behaviour.

        fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_RAW $g_tmp_dir \
            $_bl_umd_file "DESCRIPTION" _bl_umd_desc

        fn_read_reboot $FUNCNAME $LINENO $g_tmp_dir $_bl_umd_file _bl_umd_reboot
        _reboot_status=$?

        if [[ 1 == $_reboot_status ]]
        then #{
            _bl_umd_desc="PATCH ERROR"
        fi #}

        $cmd_RM -f "$g_INFODIR/reboot_list" &>$g_NULL

        fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_RAW $g_tmp_dir \
            $_bl_umd_file "SIZE" _bl_umd_size

        fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_RAW $g_tmp_dir \
            $_bl_umd_file "WARNINGS" _bl_umd_warnings
        if [[ $_bl_umd_warnings ]]
        then #{
            fn_log $g_LOGWARN $FUNCNAME $LINENO "Appending warnings \"$_bl_umd_warnings\" to file $g_READMEDIR/$_bl_umd_name_ver_rel.warning"
            echo $_bl_umd_warnings >>$g_READMEDIR/$_bl_umd_name_ver_rel.warning
        fi #}

        if fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_RAW $g_tmp_dir \
                $_bl_umd_file "KEYCODE" _bl_keycode
        then #{
            _bl_keycode_id=$(echo $_bl_keycode \
                | $cmd_TR '=' ' ' | $cmd_CUT -f1 -d ' ')
            _bl_keycode_value=$(echo $_bl_keycode \
                | $cmd_TR '=' ' ' | $cmd_CUT -f2 -d ' ')
            $cmd_CFSGETCODE $_bl_keycode_id
            _bl_code_value=$?
            if [[ "$($cmd_EXPR $_bl_code_value != $_bl_keycode_value)" == "1" ]]
            then #{
                fn_write_event $LINENO E -1 "No Proper keycode applied. Please retrieve and apply a feature keycode prior to patching the system."
                echo "No Proper keycode applied. Please retrieve and apply a feature keycode prior to patching the system." >>$g_READMEDIR/Warnings-$_bl_umd_name_ver_rel.txt
                _bl_internal_status=$_bl_ps_INVALID
            fi #}
        fi #}

        ### Presence of .scd file means indicated patch has been individually
        ### scheduled. The .scd file should be removed when patch is applied.
        if [[ -e "$g_INFODIR/$_bl_umd_file.scd" ]]
        then #{
            _bl_packages_status=$_bl_ps_SCHEDULE
            fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "File $g_INFODIR/$_bl_umd_file.scd found, patch scheduled"
        fi #}

        ### this is to mark that patch has once change its status to obsolete,
        ### meaning was upgraded, this stops from rolling this patch back more
        ### than once, otherwise rpm behaves unpredictably, rpm limitations
        if [[ $_bl_packages_status == $_bl_ps_OBSOLETE ]]
        then #{
            ### Mark the patch as $_bl_ps_OBSOLETE.
            $cmd_TOUCH $g_INFODIR/$_bl_umd_file.obs

            ### Rewrite $g_PATCHHISTORY to show all occurrences of the patch
            ### we're working as NotRemovable. We lock it against concurrent
            ### access.
            if [[ -e $g_PATCHHISTORY ]]
            then #{
                fn_lockfile $LINENO $g_PATCHHISTORY
                $cmd_SED -i "s/\(\<$_bl_umd_name\>.*\<$_bl_umd_ver\>-\<$_bl_umd_rel\>.*\)\<Removable\>\(.*\)/\1NotRemovable\2/" $g_PATCHHISTORY
                [[ $? != 0 ]] && fn_exit $FUNCNAME $LINENO RET_RUNTIME_SED_FAILED "$cmd_SED call failed"
                fn_unlockfile $LINENO $g_PATCHHISTORY
            fi #}
        fi #}

        if [[         $_bl_internal_status == $_bl_ps_INVALID \
                &&  ! $_bl_packages_status == $_bl_ps_APPLIED ]]
        then #{
            _bl_packages_status=$_bl_ps_INVALID
            _bl_internal_status=
        fi #}

        if [[ $_bl_packages_status == $_bl_ps_AVAILABLE ]]
        then #{
            ### Mark the patch as $_bl_ps_AVAILABLE.
            $cmd_TOUCH $g_INFODIR/$_bl_umd_file.ava
            if [[ -f "$g_READMEDIR/Warnings-$_bl_umd_name_ver_rel.txt" ]]
            then #{
                ### here do something with the Warnings, need to get where
                ### EM can see it
                ### TODO?
                echo "" >>$g_READMEDIR/Warnings-$_bl_umd_name_ver_rel.txt
            fi #}

            ### There is a pushd here so the call to
            ### $cmd_CPIO will run in the right directory.
            pushd $g_tmp_dir &>$g_NULL #{
            $cmd_RPM2CPIO $_bl_uxd_file | $cmd_CPIO -i -d &>$g_NULL
            popd &>$g_NULL #}

            $cmd_CP -f $g_tmp_dir/$g_PATCHDIR/sigs/*.usd $g_INFODIR &>$g_NULL
            $cmd_CP -f $g_tmp_dir/$g_READMEDIR/* $g_READMEDIR &>$g_NULL

            ### Run the pre_patch.sh if there is one.
            fn_run_pre_patch $LINENO $_bl_umd_name_ver_rel
        fi #}

        fn_write_event $LINENO I -1 "$_bl_umd_name $_bl_umd_ver $_bl_umd_rel $_bl_umd_desc $_bl_umd_size $_bl_umd_reboot $_bl_packages_status <- $LINENO of $g_PROGNAME"

        ### We need to send the output to file descriptor 6, which is where
        ### stdout was preserved to when I/O redirection was turned on as well
        ### as sending it to $g_PATCHCACHE.
        ### Output: Name, Version-Release, ShortDescription, Size,
        ### RebootReqired, Size, Status.
        printf "%s\t%s-%s\t%s\t%s\t%s\t%s\n" \
            "$_bl_umd_name" \
            "$_bl_umd_ver" \
            "$_bl_umd_rel" \
            "$_bl_umd_desc" \
            "$_bl_umd_size" \
            "$_bl_umd_reboot" \
            "$_bl_packages_status" | $cmd_TEE -a $g_PATCHCACHE >&6

        ### $g_PATCHCACHE file is created here, but was locked against
        ### concurrent access in fn_main in the handlers for the download
        ### protocol calls (--ftp,  --http, etc.) so we will unlock it now.
        fn_unlockfile $LINENO $g_PATCHCACHE

        ### We also send it to the debug log file
        fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "printing to stdout and appending to $g_PATCHCACHE: \"$_bl_umd_name $_bl_umd_ver-$_bl_umd_rel $_bl_umd_desc $_bl_umd_size $_bl_umd_reboot $_bl_packages_status\""

        ### The .proto file is used to mark what method which patch used to
        ### get here. Previously a global patchproto.log was used, however
        ### statelessness of softinv will override this when we're in context
        ### of scheduling patches.

        echo "$_arg_bl_patch_proto" >$g_INFODIR/$_bl_umd_file.proto

    done #}

    return 0
}

################################################################################
### Purpose: a generic function to query an xml file value of a tag.
###          multiple values are passed back as space separated, although
###          $cmd_XPATHPARSE utility outputs them one per line
### Args:    $1 calling $FUNCNAME
###          $2 calling $LINENO
###          $3 case modifier, affects value places in pass back tag value.
###             Set to $g_gutv_DOWNCASE to shift to lowercase, $g_gutv_UPCASE
###             to shift to uppercase or $g_gutv_RAW to leave read value
###             unchanged.
###          $4 location directory path
###          $5 xml file name
###          $6 tag name
###          $7 var name to pass back tag value
### Returns: 0 on success, 1 on failure.
### Note:    This function logs failure to read a tag, and also from where
###          the call was made, so if you don't need to perform conditional
###          behaviour based on whether or not the tag was read, you can
###          simply call the function and ignore the return value and the
###          logging will be done for you.
fn_get_umd_tag_value()
{
    fn_chkargs $FUNCNAME $LINENO $# 7 7 "FUNCNAME, LINENO, casemod, location_directory_path, xml_file_name, tag_name, passback_tagvalue"

    local -r    _arg_gutv_funcname=$1
    local -r -i _arg_gutv_lineno=$2
    local -r -i _arg_gutv_casemod=$3
    local -r    _arg_gutv_path=$4
    local -r    _arg_gutv_xml_file=$5
    local -r    _arg_gutv_tag=$(echo "$6" | $cmd_TR '[:lower:]' '[:upper:]')
    local -r    _arg_gutv_passback_tagvalue=$7

    eval "${_arg_gutv_passback_tagvalue}=\"\""
    if [[ ! -e "$_arg_gutv_path/$_arg_gutv_xml_file" ]]
    then #{
        fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "<$_arg_gutv_funcname:$_arg_gutv_lineno on path=\"$_arg_gutv_path\" file=\"$_arg_gutv_xml_file\" for tag=\"$_arg_gutv_tag\", $_arg_gutv_path/$_arg_gutv_xml_file does not exist, returning 1"
        ### $_arg_gutv_passback_tagvalue was set to blank above.
        return 1
    fi #}

    local _gutv_tagvalue=
    while read -r _gutv_tagvalue
    do #{
        eval "${_arg_gutv_passback_tagvalue}=\"${!_arg_gutv_passback_tagvalue} $_gutv_tagvalue\""
    done < <($cmd_XPATHPARSE $_arg_gutv_path/$_arg_gutv_xml_file "//$_arg_gutv_tag/text()" 2>$g_NULL) #}

    ### The algorithm above will add a leading space so we strip any leading
    ### spaces. This may result in making the string empty.
    eval "${_arg_gutv_passback_tagvalue}=\"${!_arg_gutv_passback_tagvalue## }\""

    if [[ ! ${!_arg_gutv_passback_tagvalue} ]]
    then #{
        fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "<$_arg_gutv_funcname:$_arg_gutv_lineno on path=\"$_arg_gutv_path\" file=\"$_arg_gutv_xml_file\" for tag=\"$_arg_gutv_tag\", tag not found"
        return 1
    fi #}

    if [[ $_arg_gutv_casemod == $g_gutv_DOWNCASE ]]
    then #{
        eval "${_arg_gutv_passback_tagvalue}=\"$(echo ${!_arg_gutv_passback_tagvalue} | $cmd_TR '[:upper:]' '[:lower:]')\""
    elif [[ $_arg_gutv_casemod == $g_gutv_UPCASE ]]; then #}{
        eval "${_arg_gutv_passback_tagvalue}=\"$(echo ${!_arg_gutv_passback_tagvalue} | $cmd_TR '[:lower:]' '[:upper:]')\""
    elif [[ $_arg_gutv_casemod != $g_gutv_RAW ]]; then #}{
        fn_exit $FUNCNAME $LINENO RET_SCRIPT_GETUMDTAGVAL_BADARGS "$_arg_gutv_casemod must be \"g_gutv_DOWNCASE\", \"g_gutv_UPCASE\" or \"g_gutv_RAW\" but is \"$_arg_gutv_casemod\""
    fi #}

    return 0
}

################################################################################
### Purpose: A generic function to query an rpm package for a value of a tag.
###          An rpm package is a physical file as opposed to querying the
###          rpm db,  the latter being performed by fn_get_rpm_tag_value().
### Args:    $1 calling $FUNCNAME
###          $2 calling $LINENO
###          $3 location path
###          $4 rpm package file name
###          $5 tag name
###          $6 passback for tag_value
### Returns: 0 on success, 1 on failure.
### Note:    This function logs failure to read a tag, and also from where
###          the call was made, so if you don't need to perform conditional
###          behaviour based on whether or not the tag was read, you can
###          simply call the function and ignore the return value and the
###          logging will be done for you.
fn_get_package_tag_value()
{
    fn_chkargs $FUNCNAME $LINENO $# 6 6 "FUNCNAME, LINENO, location_path, rpm_package_file_name, tag_name, passback_tagvalue"

    local -r    _arg_gptv_funcname=$1
    local -r -i _arg_gptv_lineno=$2
    local -r    _arg_gptv_path=$3
    local -r    _arg_gptv_package=$4
    local -r    _arg_gptv_tag=$5
    local -r    _arg_gptv_passback_tagvalue=$6

    eval "${_arg_gptv_passback_tagvalue}=\"\""

    if [[ ! -e "$_arg_gptv_path/$_arg_gptv_package" ]]
    then #{
        fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "<$_arg_gptv_funcname:$_arg_gptv_lineno on path=\"$_arg_gptv_path\" package=\"$_arg_gptv_package\" for tag=\"$_arg_gptv_tag\", $_arg_gptv_path/$_arg_gptv_package does not exist, returning 1"
        ### $_arg_gptv_passback_tagvalue was set to blank above.
        return 1
    fi #}

    ### Because we need to check the value of $?, we can't combine the local
    ### declaration with the call. We also prepend the name of the function
    ### to prevent problems with inherited local scope.
    local _get_package_tag_value=
    _get_package_tag_value=$($cmd_RPM -qp --qf "%{$_arg_gptv_tag}" $_arg_gptv_path/$_arg_gptv_package)
    if [[ $? != 0 ]]
    then #{
        fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "<$_arg_gptv_funcname:$_arg_gptv_lineno on path=\"$_arg_gptv_path\" file=\"$_arg_gptv_xml_file\" for tag=\"$_arg_gptv_tag\", $cmd_RPM -qp --qf %{$_arg_gptv_tag} failed, returning 1"
        return 1
    fi #}

    eval "${_arg_gptv_passback_tagvalue}=\"$_get_package_tag_value\""

    return 0
}

################################################################################
### Purpose: A generic function to query an rpm for a value of a tag.
###          This is against installed rpms as opposed to against an rpm
###          package, the latter being performed by fn_get_package_tag_value().
### Args:    $1 calling $FUNCNAME
###          $2 calling $LINENO
###          $3 rpm name
###          $4 tag name
###          $5 var name to pass back value
### Returns: 1 on error, 0 on success
### Note:    This function logs failure to read a tag, and also from where
###          the call was made, so if you don't need to perform conditional
###          behaviour based on whether or not the tag was read, you can
###          simply call the function and ignore the return value and the
###          logging will be done for you.
fn_get_rpm_tag_value()
{
    fn_chkargs $FUNCNAME $LINENO $# 5 5 "FUNCNAME, LINENO, rpm_name, tag_name, passback_tagvalue"

    local -r    _arg_grtv_funcname=$1
    local -r -i _arg_grtv_lineno=$2
    local -r    _arg_grtv_rpmname=$3
    local -r    _arg_grtv_tag=$4
    local -r    _arg_grtv_passback_tagvalue=$5

    ### in most cases value is going to be: 'package package-aa is
    ### not installed' if package-aa is not installed
    ### Because we need to check the value of $?, we can't combine the local
    ### declaration with the call. We also prepend the name of the function
    ### to prevent problems with inherited local scope.
    local _get_rpm_tag_value=
    _get_rpm_tag_value=$($cmd_RPM -q --qf "%{$_arg_grtv_tag}" $_arg_grtv_rpmname)
    if [[ $? != 0 ]]
    then #{
        fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "<$_arg_grtv_funcname:$_arg_grtv_lineno no tag=\"$_arg_grtv_tag\" found for package=\"$_arg_grtv_rpmname\" returning 1"
        eval "${_arg_grtv_passback_tagvalue}=\"\""
        return 1
    else #}{
        eval "${_arg_grtv_passback_tagvalue}=\"$_get_rpm_tag_value\""
        return 0
    fi #}
}

################################################################################
### Purpose: Restores stdout and stderr to normal, i.e., it turns off I/O
###          redirection. This function is called automatically on exit,
###          whether that exit was intentional or by way of a signal, due
###          to the signal trap command issued elsewhere in this script.
### Notes:   If $gscr_DEBUG is 0 only the I/O redirection part is done.
### Args:    $1 calling $LINENO
### Returns: 0
fn_trap()
{
    $cmd_SYNC ### flush all file system buffers... includes FS cache

    ### Restore stdout and stderr and close file descriptors
    exec 1>&6 6>&-
    exec 2>&7 7>&-

    ### delete temporary directory and files
    [[ $g_tmp_dir && -d $g_tmp_dir ]] && $cmd_RM -rf $g_tmp_dir &>$g_NULL
    g_tmp_dir=

    ### Unlock any locked files. Notice we didn't keep these files in
    ### $g_tmp_dir. That was on purpose, since $g_tmp_dir is unique per
    ### instance of the script.
    ### TODO: This technique removes ALL lock files, which ignores the fact
    ### that another instance of this script may have created them, and still
    ### be running. A better algorithm would be to iterate the lock files,
    ### checking the PID inside each one, and if matches the PID for this
    ### instance of the script (this scripts PID is in $$), then we remove
    ### the lock.
    $cmd_RM -f $g_PATCHTMPDIR/*$g_LOCK

    if [[ $g_exitval -gt 0 ]]
    then #{
        if [[ $g_exitval -ge $RETSTART_SCRIPT ]]
        then #{
            echo "$g_SCRIPTERR_PREFIX returned $g_exitval"
        elif [[ $g_exitval -ge $RETSTART_RUNTIME ]]; then #}{
            echo "$g_RUNTIMEERR_PREFIX returned $g_exitval"
        elif [[ $g_exitval -ne $RET_USAGE ]]; then #}{
            echo "ERROR: returned $g_exitval"
        fi #}
    fi #}

    ### TODO change trap to modify exit value for normal exit vs.
    ### trap on signals.
    exit $g_exitval
}

################################################################################
### Purpose: Given a path, strips leading slashes, converts // to / and \ to /.
### Args:    $1 calling $LINENO
###          $2 passin and passback for massaged path
### Returns: 0
fn_massage_path()
{
    fn_chkargs $FUNCNAME $LINENO $# 2 2 "LINENO, passback_path"

    local -r _arg_passback_path=$2
    local    _massage_path_tmppath=${!_arg_passback_path}

    ### strip leading slashes from path
    _massage_path_tmppath=${_massage_path_tmppath##/}
    _massage_path_tmppath=${_massage_path_tmppath##\\}
    ### replace any // with / and \ with /
    _massage_path_tmppath=${_massage_path_tmppath//\/\//\/}
    _massage_path_tmppath=${_massage_path_tmppath//\\\\//}

    eval "${_arg_passback_path}=\"$_massage_path_tmppath\""

    return 0
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 force - one of $g_NOFORCE or $g_FORCE. If set to $g_FORCE,
###             will force the download even if the .ava and .scd files
###             are absent. This is needed if this algorithm is to be used
###             for downloading multiple patches to be used with a multiple
###             patch selection algorithm.
###          $3 passback variable for error_message
###          $4 patch_name
###          $5 patch_ver
### Returns: 0 on success, 1 on failure
fn_download_patch()
{
    local -r _arg_dlp_force=$2
    local -r _arg_dlp_passback_errmsg=$3
    eval "${_arg_dlp_passback_errmsg}=\"\""
    local -r _arg_dlp_patch_name=$4
    local -r _arg_dlp_patch_ver=$5

    local -r _dlp_root=$g_INFODIR/$_arg_dlp_patch_name-$_arg_dlp_patch_ver.$g_arch

    ### For Optional Components
    local optional_selects=
    if [ $# -gt 5 ]; then
       shift 5 

       optional_selects=$*
       if [ ! "`echo $optional_selects | grep \.rpm`" = "" ]; then
          echo $optional_selects >> ${g_INFODIR}/${_arg_dlp_patch_name}-${_arg_dlp_patch_ver}.$g_arch.umd.rpms
       fi
    fi

    local _dlp_umd_size=
    if ! fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_RAW $g_INFODIR \
        $_arg_dlp_patch_name-$_arg_dlp_patch_ver.$g_arch.umd "SIZE" \
        _dlp_umd_size
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "fn_get_umd_tag_value $g_INFODIR $_arg_dlp_patch_name-$_arg_dlp_patch_ver.$g_arch.umd \"SIZE\" failed to set _dlp_umd_size, returning 1"
        return 1
    fi #}

    local _dlp_umd_type=
    if ! fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_UPCASE $g_INFODIR \
        $_arg_dlp_patch_name-$_arg_dlp_patch_ver.$g_arch.umd \
        "SOFTWARETYPE" _dlp_umd_type
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "fn_get_umd_tag_value $g_INFODIR $_arg_dlp_patch_name-$_arg_dlp_patch_ver.$g_arch.umd \"SOFTWARETYPE\" failed to set _dlp_umd_type, returning 1"
        ### TODO shouldn't this be fatal?
        return 1
    fi #}

    ### TODO: Check totalsize, startsize and upgrading to see if we can improve.
    $cmd_RM -f $g_INFODIR/{totalsize,startsize,upgrading} &>$g_NULL

    if [[ $_dlp_umd_type == UPGRADE ]]
    then #{
        $cmd_TOUCH $g_INFODIR/upgrading
        if echo $_dlp_umd_size | $cmd_GREP MB 2>$g_NULL
        then #{
            $cmd_EXPR match "$_dlp_umd_size" '\([0-9]*\)' >$g_INFODIR/totalsize
        fi #}
        $cmd_DU -mSs $g_INFODIR | $cmd_CUT -f1 >$g_INFODIR/startsize
    fi #}

    ### test -d true if file exists and is a directory, test -h file true if
    ### file exists and is a symbolic link.
    [[      ! -h /var/spool/repackage \
        ||  ! -d /var/spool/repackage ]] \
            && $cmd_MKDIR -p /var/spool/repackage

    fn_write_status $LINENO "Downloading"
    fn_write_event $LINENO I -1 "Downloading "

    ### What protocol is to be used to download this patch?
    ### TODO: OUTSTANDING: make sure to exit with appropriate ERROR when
    ### this file is not found
    local _dlp_proto=
    if [[ -e "$_dlp_root.umd.proto" ]]
    then #{
        read _dlp_proto g_dummy <$_dlp_root.umd.proto
    else #}{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "file $_dlp_root.umd.proto missing so could not read patch protocol from it, returning 1"
        return 1
    fi #}

    ### Test -e true if file exists.
    if [[       $_arg_dlp_force == $g_FORCE \
            ||  -e $_dlp_root.umd.ava       \
            ||  -e $_dlp_root.umd.scd       ]]
    then #{
        echo -n " $_dlp_root.uxd" >$_dlp_root.umd.trn

        local -r _dlp_str_tmn=$($cmd_DATE '+%a %b %d %H:%M:%S %Y')
        printf "%s\t%s\t%s\t%s\t%s\n" \
            "$_arg_dlp_patch_name" \
            "$_arg_dlp_patch_ver" \
            "$_dlp_str_tmn" \
            "$_dlp_proto" \
            "Downloading" \
            >$_dlp_root.umd.str
        local -r _dlp_directory="/tmp/$_arg_dlp_patch_name-$_arg_dlp_patch_ver.$g_arch.umd"

        local _dlp_tmp_key=
        if ! fn_unhide_key $LINENO $_dlp_directory _dlp_tmp_key
        then #{
            eval "${_arg_dlp_passback_errmsg}=\"Failed_Key \""
            fn_clean_temp $LINENO $_arg_dlp_patch_name-$_arg_dlp_patch_ver
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "${!_arg_dlp_passback_errmsg}, fn_unhide_key failed, returning 1"
            return 1
        fi #}

        ### decrypt url
        local _dlp_url=
        if ! fn_decrypt_data $LINENO $_dlp_tmp_key _dlp_url \
                $_dlp_root.umd.$_dlp_proto
        then #{
            eval "${_arg_dlp_passback_errmsg}=\"Failed_Decrypt \""
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "${!_arg_dlp_passback_errmsg}, fn_decrypt_data failed, returning 1"
            return 1
        fi #}

        ### Notice that we pass the value of $_arg_dlp_passback_errmsg
        if ! fn_download_patch_proto \
                $LINENO \
                $_arg_dlp_patch_name-$_arg_dlp_patch_ver \
                "$_dlp_url" \
                $_dlp_proto \
                $_arg_dlp_passback_errmsg
        then #{
            [[ ! ${!_arg_dlp_passback_errmsg} ]] && \
                eval "${_arg_dlp_passback_errmsg}=\"Download_Failed \""
            fn_clean_temp $LINENO $_arg_dlp_patch_name-$_arg_dlp_patch_ver
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "${!_arg_dlp_passback_errmsg}, fn_download_patch_proto failed, returning 1"
            return 1
        fi #}

        fn_write_status $LINENO "Verifying_Signatures"
        fn_write_event $LINENO I -1 "Verifying_Signatures "
        if ! fn_verify_signatures $LINENO $_arg_dlp_patch_name $_arg_dlp_patch_ver
        then #{
            eval "${_arg_dlp_passback_errmsg}=\"Failed_Sigs \""
            fn_clean_temp $LINENO $_arg_dlp_patch_name-$_arg_dlp_patch_ver
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "${!_arg_dlp_passback_errmsg}, fn_verify_signatures failed, returning 1"
            return 1
        fi #}

        echo "" >>$_dlp_root.umd.trn

        printf "%s\t%s\t%s\t%s\t%s\n"   \
            "$_arg_dlp_patch_name"      \
            "$_arg_dlp_patch_ver"       \
            "$_dlp_str_tmn"             \
            "$_dlp_proto"               \
            "Downloaded"                \
            >$_dlp_root.umd.str

        $cmd_RM -rf $_dlp_directory &>$g_NULL

    else #}{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Files $_dlp_root.umd.{ava,scd} absent AND force download not set. Files will not be downloaded, returning 1"
        return 1
    fi #}
    return 0
}

################################################################################
### Purpose: Helper function for fn_download_patch()
### Args:    $1 calling $LINENO
###          $2 patch_id
###          $3 url
###          $4 patch_proto
###          $5 passback errmsg
### Returns: 0 on success, 1 on failure.
fn_download_patch_proto()
{
    fn_chkargs $FUNCNAME $LINENO $# 5 5 "LINENO, patch_id, url, patch_proto, passback_errmsg"
    local -r _arg_dpp_patch_id=$2
    local -r _arg_dpp_url=$3
    local -r _arg_dpp_patch_proto=$4
    local -r _arg_dpp_passback_errmsg=$5
    eval "${_arg_dpp_passback_errmsg}=\"\""
    local -r _dpp_rpms=$($cmd_CAT $g_INFODIR/$_arg_dpp_patch_id.$g_arch.umd.rpms 2>$g_NULL)

    if [[ ! $_dpp_rpms ]]
    then #{
        eval "${_arg_dpp_passback_errmsg}=\"Download_Failed\""
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "error message ${!_arg_dpp_passback_errmsg}, couldn't get RPMS from file $g_INFODIR/$_arg_dpp_patch_id.$g_arch.umd.rpms, returning 1"
        return 1
    fi #}

    local -i _dpp_ret_code=
    local    _dpp_rpm=
    for _dpp_rpm in $_dpp_rpms
    do #{

        case "$_arg_dpp_patch_proto" in #{

            "http" | "https" | "ftp") #{

                ### $cmd_WGET below will write HTML-ized file listing of
                ### the remote directory $_dpp_rpm at URL $_arg_dpp_url
                ### to file $g_INFODIR/index.html
                $cmd_WGET --no-parent --directory-prefix=$g_INFODIR -N $_arg_dpp_url/$_dpp_rpm &>$g_WGETLOG
                _dpp_ret_code=$?

                ### Note we pass the value of $_arg_dpp_passback_errmsg
                if fn_found_error $LINENO $_dpp_ret_code \
                        $g_WGETLOG $_arg_dpp_passback_errmsg
                then #{
                    ### TODO: 2301 is written as 'E' but is listed in
                    ### /nn/etc/DiaLoggerTaxonomy as major, which
                    ### should be 'W'.
                    fn_write_event $LINENO E 2301 "Software update failed to transfer files"
                    return 1
                fi #}

                echo -n " $g_INFODIR/$_dpp_rpm" \
                    >>$g_INFODIR/$_arg_dpp_patch_id.$g_arch.umd.trn

                ;; #}

            "samba") #{

                ### There is a pushd here so the call to
                ### $cmd_SMBCLIENT will run in the right directory.
                pushd $g_INFODIR &>$g_NULL #{
                if [[ $? != 0 ]]
                then #{
                    fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Failure to change to $g_INFODIR"
                    return 1
                fi #}

                local _smb_sub_dir=.
                if [[ -e "$g_INFODIR/smb_subfolder" ]]
                then #{
                  read _smb_sub_dir <$g_INFODIR/smb_subfolder
                fi #}

                ### TODO may only work for Windows samba
                $cmd_SMBCLIENT -E $_arg_dpp_url -c "prompt; cd $_smb_sub_dir; mget $_dpp_rpm" \
                    &>$g_SMBCLIENTLOG
                _dpp_ret_code=$?

                popd &>$g_NULL #}

                ### Note we pass the value of $_arg_dpp_passback_errmsg
                if fn_found_error $LINENO $_dpp_ret_code \
                        $g_SMBCLIENTLOG $_arg_dpp_passback_errmsg
                then #{
                    ### TODO: 2301 is written as 'E' but is listed in
                    ### /nn/etc/DiaLoggerTaxonomy as major, which
                    ### should be 'W'.
                    fn_write_event $LINENO E 2301 "Software update failed to transfer files"
                    return 1
                fi #}

                echo -n " $g_INFODIR/$_dpp_rpm" \
                    >>$g_INFODIR/$_arg_dpp_patch_id.$g_arch.umd.trn

                ;; #}

            "usb") #{

                if ! $cmd_MOUNTUSB &>$g_NULL
                then #{
                    fn_write_event $LINENO I -1 "No usb device attached or it is already mounted --- Continue ..."
                fi #}

                if $cmd_MOUNT | $cmd_GREP -q "$g_usbdev"
                then #{
                    if ! $cmd_NICE --adjustment=5 $cmd_CP -a \
                            -f $_arg_dpp_url/$_dpp_rpm $g_INFODIR &>$g_NULL
                    then #{
                        ### maybe some info needs to be put into
                        ### Warnings in $g_READMEDIR/
                        ### 2>>$g_READMEDIR/Warnings-$_arg_dpp_patch_id.txt
                        eval "${_arg_dpp_passback_errmsg}=\"Download_Failed $cmd_CP $_dpp_rpm \""
                        ### TODO: 2301 is written as 'E' but is listed in
                        ### /nn/etc/DiaLoggerTaxonomy as major, which
                        ### should be 'W'.
                        fn_write_event $LINENO E 2301 "Software update failed to transfer files"
                        return 1
                    fi #}
                    echo -n " $g_INFODIR/$_dpp_rpm" \
                        >>$g_INFODIR/$_arg_dpp_patch_id.$g_arch.umd.trn
                else #}{
                    eval "${_arg_dpp_passback_errmsg}=\"Download_Failed $cmd_CP $_dpp_rpm \""
                    ### TODO: 2301 is written as 'E' but is listed in
                    ### /nn/etc/DiaLoggerTaxonomy as major, which
                    ### should be 'W'.
                    fn_write_event $LINENO E 2301 "Software update failed to transfer files"
                    return 1
                fi #}
                ;; #}

            "em") #{

                if ! $cmd_MV -f $_arg_dpp_url/$_dpp_rpm $g_INFODIR &>$g_NULL
                then #{
                    eval "${_arg_dpp_passback_errmsg}=\"Download_Failed mv $_dpp_rpm \""
                    ### TODO: 2301 is written as 'E' but is listed in
                    ### /nn/etc/DiaLoggerTaxonomy as major, which
                    ### should be 'W'.
                    fn_write_event $LINENO E 2301 "Software update failed to transfer files"
                    return 1
                fi #}
                echo -n " $g_INFODIR/$_dpp_rpm" \
                    >>$g_INFODIR/$_arg_dpp_patch_id.$g_arch.umd.trn
                ;; #}

        esac #}

    done #} for _dpp_rpm in $_dpp_rpms

    ### TODO: What is $g_INFODIR/wget_$_arg_dpp_patch_id.log file used for?
    [[ -e "$g_INFODIR/wget_$_arg_dpp_patch_id.log" ]] && \
        $cmd_RM -f $g_INFODIR/wget_$_arg_dpp_patch_id.log &>$g_NULL
    [[ $_arg_dpp_patch_proto == usb ]] && $cmd_UMOUNTUSB

    return 0
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 patch
### Returns: 0
fn_clean_temp()
{
    fn_chkargs $FUNCNAME $LINENO $# 2 2 "LINENO, patch"
    $cmd_RM -f  $g_BLOCKINGFLAG                     \
                $g_INFODIR/$2.$g_arch.umd.{trn,str} \
                &>$g_NULL

    return 0
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 force - passed on to fn_download_patch
###          $3 patch name
###          $4 patch version
### Returns: 0 on success, 1 on failure.
fn_do_donly()
{

    local -r _arg_do_donly_force=$2
    local -r _arg_do_donly_patch_name=$3
    local -r _arg_do_donly_patch_ver=$4

    fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Downloading $_arg_do_donly_patch_name $_arg_do_donly_patch_ver"
    fn_write_status $LINENO "Download_Start"
    fn_write_event $LINENO I -1 "Download_Start"
    shift; shift
    local _do_donly_errmsg=
    if ! fn_download_patch $LINENO $_arg_do_donly_force \
            _do_donly_errmsg $*
    then #{
        [[ ! $_do_donly_errmsg ]] \
            && _do_donly_errmsg="Download_Failed "
        fn_write_status $LINENO "$_do_donly_errmsg"
        fn_write_event $LINENO E -1 "$_do_donly_errmsg <- $LINENO of $g_PROGNAME"
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "fn_download_patch $_arg_do_donly_patch_name $_arg_do_donly_patch_ver failed, error message \"$_do_donly_errmsg\""
        return 1
    fi #}

    fn_write_status $LINENO "Download_End"
    fn_write_event $LINENO I -1 "Download_End <- $LINENO of $g_PROGNAME"
    fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Downloaded $_arg_do_donly_patch_name $_arg_do_donly_patch_ver"

    return 0
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 patch_name
###          $3 patch_ver
### Returns: 0 on success, 1 on failure.
### TODO:    If this method returns prematurely, it breaks "--select apply"
###          and "--select aonly" such that you can't simply resume. Needs
###          to be addressed.
fn_apply_patch()
{
    local -r _arg_ap_patch_name=$2
    local -r _arg_ap_patch_ver=$3
    local -r _ap_umd_file_name=$_arg_ap_patch_name-$_arg_ap_patch_ver.$g_arch.umd

    fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Applying $_arg_ap_patch_name $_arg_ap_patch_ver"
    ### TODO: Having the status (and the event for that matter) updated to
    ### Apply_Start here assumes that we will only be applying one patch,
    ### and that once it's applied, we're done. This is not true however
    ### if we use this function fn_apply_patch() in a loop to apply many
    ### patches, such as might be the case if we are using a multiple
    ### patch selection algorithm.
    fn_write_status $LINENO "Apply_Start"
    fn_write_event $LINENO I -1 "Apply_Start"

    local _ap_umd_type=
    if ! fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_UPCASE $g_INFODIR \
            $_ap_umd_file_name "SOFTWARETYPE" _ap_umd_type
    then #{
        fn_write_status $LINENO "Apply_Failed"
        fn_write_event $LINENO I -1 "Apply_Failed <- $LINENO of $g_PROGNAME"
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "fn_get_umd_tag_value $g_INFODIR $_ap_umd_file_name could not read SOFTWARETYPE, returning 1"
        return 1
    fi #}

    ### validate the signature if someone just tries to apply a patch without
    ### a valid signature
    if [[ $gscr_CHECKSIG == yes ]]
    then #{
        $cmd_UMD_SIGN validate $g_INFODIR/$_ap_umd_file_name
        local -r -i _ap_umd_sign_retval=$?
        if [[ $_ap_umd_sign_retval -ne 0 ]]
        then #{
            fn_write_status $LINENO "Apply_Failed"
            if [[ $_ap_umd_type != UPGRADE ]]
            then #{
                fn_write_event $LINENO E 2302 "Software upgrade failed to apply"
            else #}{
                fn_write_event $LINENO E 2300 "Software update failed to apply"
            fi #}
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Apply_Failed $_arg_ap_patch_name $_arg_ap_patch_ver, $cmd_UMD_SIGN returned $_ap_umd_sign_retval"
            return 1
        fi #}
    fi #}

    ### before doing anything we need to check whether we're not applying
    ### something that has one or more items in its requires list scheduled.
    ### if at least one item in the list found to be scheduled then apply can
    ### not go on.
    local _ap_requires=
    while read -r _ap_requires
    do #{
        ### Note the truncation of _ap_requires on space or lexical
        ### comparators. This is because _cr_requires can be expressed
        ### absolutely or relatively. For example package 'some-pkg'
        ### version '1.2' release '3.4' would be expressed absolutely as
        ### 'some-pkg-1.2-3.4'. If we wanted to specify the same package
        ### requirement as greater than the indicated version, it would
        ### be 'some-pkg > 1.2-3.4' or 'some-pkg>1.2-3.4' (the latter
        ### being without any spaces.)
        if [[ -e "$g_INFODIR/${_ap_requires%%[>=< ]*}.$g_arch.umd.scd" ]]
        then #{
            fn_write_status $LINENO "Apply_Failed"
            fn_write_event $LINENO I -1 "Apply_Failed <- $LINENO of $g_PROGNAME"
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "scheduled item found, status Apply_Failed, returning 1"
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Apply_Failed $_arg_ap_patch_name $_arg_ap_patch_ver"
            return 1
        fi #}
    done < <($cmd_XPATHPARSE $g_INFODIR/$_ap_umd_file_name "//REQUIRES/text()" 2>$g_NULL) #}

    if [[ -e $g_BLOCKINGFLAG ]]
    then #{
        fn_write_status $LINENO "Apply_Failed"
        fn_write_event $LINENO I -1 "Apply_Failed <- $LINENO of $g_PROGNAME"
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Found $g_BLOCKINGFLAG, status Apply_Failed, returning 1"
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Apply_Failed $_arg_ap_patch_name $_arg_ap_patch_ver"
        return 1
    else #}{
        $cmd_TOUCH $g_BLOCKINGFLAG
    fi #}

    ### fn_get_umd_tag_value logs when it can't read a tag, so in the next
    ### few calls to fn_get_umd_tag_value we only check the return value if
    ### we have a need for additional conditional behaviour.

    local _ap_umd_desc=
    fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_RAW $g_INFODIR\
        $_ap_umd_file_name "DESCRIPTION" _ap_umd_desc

    local _ap_umd_reboot=
    fn_read_reboot $FUNCNAME $LINENO $g_INFODIR \
        $_ap_umd_file_name _ap_umd_reboot

    local _ap_umd_rollback=
    fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_DOWNCASE $g_INFODIR \
        $_ap_umd_file_name "ALLOWROLLBACK" _ap_umd_rollback

    local _ap_force=""
    fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_DOWNCASE $g_INFODIR \
        $_ap_umd_file_name "DEPENDENCYCHECK" _ap_force
    [[ $_ap_force == no ]] && _ap_force="--force" || _ap_force=""

    local _ap_proto=
    if [[ -e "$g_INFODIR/$_ap_umd_file_name.proto" ]]
    then #{
        read _ap_proto g_dummy <$g_INFODIR/$_ap_umd_file_name.proto
    else #}{
        fn_write_status $LINENO "Apply_Failed"
        fn_write_event $LINENO I -1 "Apply_Failed <- $LINENO of $g_PROGNAME"
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "file $g_INFODIR/$_ap_umd_file_name.proto missing so could not read patch prototype, returning 1"
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Apply_Failed $_arg_ap_patch_name $_arg_ap_patch_ver"
        return 1
    fi #}

    local -r _ap_td=$($cmd_DATE '+%a %b %d %H:%M:%S %Y')
    ### note that this should return value of $cmd_WC and not return code
    local -r -i _ap_istopped=$($cmd_PROCESSCONTROL detaillist \
        | $cmd_GREP Stopped | $cmd_WC -l)
    printf "%s\t%s\t%s\t%s\t%s\n" \
        "$_arg_ap_patch_name" \
        "$_arg_ap_patch_ver" \
        "$_ap_td" \
        "$_ap_proto" \
        "Applying" \
        >$g_INFODIR/$_ap_umd_file_name.str
    fn_write_status $LINENO "Applying"
    echo $_arg_ap_patch_name-$_arg_ap_patch_ver >$g_ACTIVEPATCH

    if [[ $_ap_umd_type == UPGRADE ]]
    then #{
        fn_write_event $LINENO I 2103 "Software upgrade started"
    else #}{
        fn_write_event $LINENO I 2102 "Software update started"
    fi #}

    if [[ -e "$g_INFODIR/$_arg_ap_patch_name-$_arg_ap_patch_ver.$g_arch.pre" ]]
    then #{
        $cmd_CFSSERVER -signverify \
            $g_INFODIR/$_arg_ap_patch_name-$_arg_ap_patch_ver.$g_arch.pre \
            $g_INFODIR/$_arg_ap_patch_name-$_arg_ap_patch_ver.$g_arch.sig
        if [[ $? != 0 ]]
        then #{
            fn_write_status $LINENO "Apply_Failed"
            fn_write_event $LINENO E 2300 "Software update failed to apply"
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Apply_Failed $_arg_ap_patch_name $_arg_ap_patch_ver"
            return 1
        fi #}

        $cmd_BASH -x \
            $g_INFODIR/$_arg_ap_patch_name-$_arg_ap_patch_ver.$g_arch.pre \
            $_ap_umd_type >>$g_LOGFILE 2>&1
        if [[ $? != 0 ]]
        then #{
            fn_write_status $LINENO "Apply_Failed"
            fn_write_event $LINENO E 2300 "Software update failed to apply"
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Apply_Failed $_arg_ap_patch_name $_arg_ap_patch_ver"
            return 1
        fi #}
    fi #}

    ### $_ap_trns contains all the .rpms listed in the patch, but due to
    ### scheduled patch application (or other methods of patch application,
    ### such as using another tool to do patch application, or the introduction
    ### of multi-selection patch application, i.e., the ability to select more
    ### than one patch for application) some of the listed .rpms may already be
    ### applied. A convenient side effect of this fact is that once an rpm has
    ### been applied, it is removed from the $g_INFODIR folder, so all we have
    ### to do is massage $_ap_trns to discard any rpms that are not listed in
    ### the $g_INFODIR folder. Once we've done that, we then only install the
    ### RPM if it's newer, or not already installed.
    ### TODO: Ideally, we should check prerequisites here too.
    local    _ap_trns=
    local    _ap_trn=
    local    _ap_rpm_name=
    local    _ap_rpm_ver=
    local    _ap_rpm_rel=
    local -i _ap_rpmcomp_ret=

    for _ap_trn in $($cmd_LS $($cmd_CAT $g_INFODIR/$_ap_umd_file_name.trn) 2>$g_NULL)
    do #{
      ### Get the patch name and release-version from $_ap_trn
      fn_parse_rpm $LINENO "$_ap_trn" _ap_rpm_name _ap_rpm_ver _ap_rpm_rel

      ### If this is an upgrade just take the full list without doing the compare
      if [[ $_ap_umd_type == UPGRADE ]]
      then
          _ap_trns="$_ap_trns $_ap_trn"
      else
          if ! $cmd_RPM -q $_ap_rpm_name &>$g_NULL
          then #{
              ### The package $_ap_rpm_name is not installed (regardless
              ### of version and release) so we will install it.
              _ap_trns="$_ap_trns $_ap_trn"
          else #}{
              ### The package $_ap_rpm_name IS installed, but we need to see if
              ### $_ap_trn is newer, in which case we will install it.
              $cmd_RPMCOMPARE \
                  $_ap_rpm_name-$_ap_rpm_ver-$_ap_rpm_rel \
                  $($cmd_RPM -q $_ap_rpm_name) \
                  >&$g_NULL
              _ap_rpmcomp_ret=$?
              if [[ $_ap_rpmcomp_ret == $g_RPMCOMPARE_RET_NEWER ]]
              then #{
                  ### The RPM we are providing is newer.
                  _ap_trns="$_ap_trns $_ap_trn"
              elif [[ $_ap_rpmcomp_ret == $g_RPMCOMPARE_RET_ERR ]]; then #}{
                  ### There was an error in the $cmd_RPMCOMPARE call.
                  ### Best we can do is log it.
                  fn_log $g_LOGALWAYS $FUNCNAME $LINENO "There was an error in the $cmd_RPMCOMPARE call comparing \"$_ap_rpm_name-$_ap_rpm_ver-$_ap_rpm_rel\" to \"$($cmd_RPM -q $_ap_rpm_name)\""
              fi #}
          fi #}
      fi
    done #}

    local -i _ap_rpm_ret=0
    if [[ $_ap_umd_rollback == no ]]
    then #{
        fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "Calling $cmd_RPM --define '_binary_payload w1.gzdio' $_ap_force -Uvvh $_ap_trns"
        $cmd_RPM --define '_binary_payload w1.gzdio' \
            $_ap_force -Uvvh $_ap_trns >>$g_LOGFILE 2>&1
        _ap_rpm_ret=$?
    else #}{
        fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "Calling $cmd_RPM --define '_binary_payload w1.gzdio' --define '_rollback_transaction_on_failure 1' --define '_unsafe_rollbacks 1059710400' --define '_repackage_all_erasures 1' $_ap_force -Uvvh $_ap_trns"
        $cmd_RPM \
            --define '_binary_payload w1.gzdio' \
            --define '_rollback_transaction_on_failure 1' \
            --define '_unsafe_rollbacks 1059710400' \
            --define '_repackage_all_erasures 1' \
            $_ap_force -Uvvh $_ap_trns >>$g_LOGFILE 2>&1
        _ap_rpm_ret=$?
    fi #}
    if [[ ! $_ap_rpm_ret -eq 0 ]]
    then #{
        fn_clean_temp $LINENO $_arg_ap_patch_name-$_arg_ap_patch_ver
        fn_write_status $LINENO "Apply_Failed"
        if [[ $_ap_umd_type != UPGRADE ]]
        then #{
            fn_write_event $LINENO E 2302 "Software upgrade failed to apply"
        else #}{
            fn_write_event $LINENO E 2300 "Software update failed to apply"
        fi #}
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Apply_Failed $_arg_ap_patch_name $_arg_ap_patch_ver"
        return 1
    fi #}

    if [[ -s $g_INFODIR/$_ap_umd_file_name.trn1 ]]
    then #{
        ### See the comment above for an explanation of why we remove some of
        ### the .rpms from $_ap_trns.
        ### TODO: This code is cut-paste from above... see if we can streamline
        ### it better.
        for _ap_trn in $($cmd_LS $($cmd_CAT $g_INFODIR/$_ap_umd_file_name.trn1) 2>$g_NULL)
        do #{
            ### Get the patch name and release-version from $_ap_trn
            fn_parse_rpm $LINENO "$_ap_trn" _ap_rpm_name _ap_rpm_ver _ap_rpm_rel

            if ! $cmd_RPM -q $_ap_rpm_name &>$g_NULL
            then #{
                ### The package $_ap_rpm_name is not installed (regardless
                ### of version and release) so we will install it.
                _ap_trns="$_ap_trns $_ap_trn"
            else #}{
                ### The package $_ap_rpm_name IS installed, but we need to see
                ### if $_ap_trn is newer, in which case we will install it.
                $cmd_RPMCOMPARE \
                    $_ap_rpm_name-$_ap_rpm_ver-$_ap_rpm_rel \
                    $($cmd_RPM -q $_ap_rpm_name) \
                    >&$g_NULL
                _ap_rpmcomp_ret=$?
                if [[ $_ap_rpmcomp_ret == $g_RPMCOMPARE_RET_NEWER ]]
                then #{
                    ### The RPM we are providing is newer.
                    _ap_trns="$_ap_trns $_ap_trn"
                elif [[ $_ap_rpmcomp_ret == $g_RPMCOMPARE_RET_ERR ]]; then #}{
                    ### There was an error in the $cmd_RPMCOMPARE call.
                    ### Best we can do is log it.
                    fn_log $g_LOGALWAYS $FUNCNAME $LINENO "There was an error in the $cmd_RPMCOMPARE call comparing \"$_ap_rpm_name-$_ap_rpm_ver-$_ap_rpm_rel\" to \"$($cmd_RPM -q $_ap_rpm_name)\""
                fi #}
            fi #}
        done #}
        $cmd_RPM \
            --define \
            '_binary_payload w1.gzdio' \
            $_ap_force \
            -Uvvh \
            $_ap_trns \
                >>$g_INFODIR/$_arg_ap_patch_name-$_arg_ap_patch_ver.log 2>&1
        if [[ $? != 0 ]]
        then #{
            fn_clean_temp $LINENO $_arg_ap_patch_name-$_arg_ap_patch_ver
            fn_write_status $LINENO "Apply_Failed"
            if [[ $_ap_umd_type != UPGRADE ]]
            then #{
                fn_write_event $LINENO E 2302 "Software upgrade failed to apply"
            else #}{
                fn_write_event $LINENO E 2300 "Software update failed to apply"
            fi #}
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Apply_Failed $_arg_ap_patch_name $_arg_ap_patch_ver"
            return 1
        fi #}
    fi #}

    ### If $_ap_umd_rollback == no, the patch is not removable.
    ### If the patch is listed as obsolete, it is not removable.
    local _ap_removable="Removable"
    [[      $_ap_umd_rollback == no \
        ||  -e $g_INFODIR/$_ap_umd_file_name.obs ]] \
            && _ap_removable="NotRemovable"

    ### Append to the $g_PATCHHISTORY file, locking it against concurrent
    ### access.
    fn_lockfile $LINENO $g_PATCHHISTORY
    printf "%s\t%s\t%s\t%s\t%s\t%s\n" \
            "$_arg_ap_patch_name" \
            "$_arg_ap_patch_ver" \
            "$_ap_umd_desc" \
            "Patch Applied" \
            "$_ap_td" \
            "$_ap_removable" \
            >>$g_PATCHHISTORY
    fn_unlockfile $LINENO $g_PATCHHISTORY

    if [[ $_ap_umd_type != UPGRADE ]]
    then #{
        fn_write_event $LINENO I 2100 "Software update applied successfully"
    else #}{
        fn_write_event $LINENO I 2101 "Software upgrade applied successfully"
    fi #}

    printf "%s\t%s\t%s\t%s\t%s\n" \
        "$_arg_ap_patch_name" \
        "$_arg_ap_patch_ver" \
        "$_ap_td" \
        "$_ap_proto" \
        "Applied" \
        >$g_INFODIR/$_ap_umd_file_name.str
    printf "%s\n%s\n%s\n" \
        "$_arg_ap_patch_name" \
        " $_arg_ap_patch_ver" \
        " $_ap_td" \
        >$g_INFODIR/$_ap_umd_file_name.end

    ### Can't use -e test here due to globbing of asterisk.
    if $($cmd_LS $g_INFODIR/$_arg_ap_patch_name-$_arg_ap_patch_ver.umd.* &>$g_NULL)
    then #{
        ### Need to leave the .umd files around for patch removal
        $cmd_RM -f \
            $g_INFODIR/$_arg_ap_patch_name-$_arg_ap_patch_ver.{umd.*,uxd} \
            &>$g_NULL
    fi #}

    local _ap_trn=
    for _ap_trn in $($cmd_CAT $g_INFODIR/$_ap_umd_file_name.{trn,trn1} 2>/$g_NULL)
    do #{
        [[ -e $_ap_trn ]]     && $cmd_RM -f $_ap_trn     &>$g_NULL
        [[ -e $_ap_trn.sig ]] && $cmd_RM -f $_ap_trn.sig &>$g_NULL
    done #}

    ### If this represents a scheduled patch, we remove the scheduled item.
    ### We remove its .scd file in a moment when we do cleanup.
    ### Note we don't have to worry about the status as that's taken care
    ### of by the caller of this function if it's applicable.
    [[ -e "$g_INFODIR/$_ap_umd_file_name.scd" ]] && \
        fn_modify_schedule $LINENO $_arg_ap_patch_name $_arg_ap_patch_ver TRUE

    ### This patch is applied (installed) so we can clean up the files used
    ### for managing the patch before it's applied.
    $cmd_RM -f                                                  \
        $g_BLOCKINGFLAG                                         \
        $g_ACTIVEPATCH                                          \
        $g_INFODIR/$_ap_umd_file_name.{ava,scd,str,trn*,rpm*}   \
        &>$g_NULL

    $cmd_TOUCH $g_INFODIR/$_ap_umd_file_name.app

    if [[ -e "$g_INFODIR/$_arg_ap_patch_name-$_arg_ap_patch_ver/post_patch.sh" ]]
    then #{
        $cmd_BASH -x \
            $g_INFODIR/$_arg_ap_patch_name-$_arg_ap_patch_ver/post_patch.sh \
                $_ap_umd_type >>$g_LOGFILE 2>&1
    fi #}

    $cmd_RM -f $g_BLOCKINGFLAG &>$g_NULL
    $cmd_RM -f "$g_INFODIR/smb_subfolder" &>$g_NULL 

    ### TODO this is where we will defer reboot.
    if [[ $_ap_umd_reboot == reboot ]]
    then #{

        ### Make sure that the Apply_Sucess is seen by the SoftwareUpdateAgentProvider
        ### thread before rebooting the system
        $cmd_TOUCH $g_APPLY_SUCCESS_FLAG
        local _time_to_wait=0
        fn_write_status $LINENO "Apply_Success"
        fn_write_event $LINENO I -1 "Apply_Success <- $LINENO of $g_PROGNAME"
        while [[ -f $g_APPLY_SUCCESS_FLAG && $_time_to_wait -lt 180 ]]
        do
          ((_time_to_wait++))
          sleep 1
        done
        $cmd_RM -f $g_APPLY_SUCCESS_FLAG
        fn_write_status $LINENO "Apply_Reboot"
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "rebooting system"
        $cmd_SHUTDOWN -r now

    else #}{

        fn_write_status $LINENO "Restarting"
        ### If $cmd_STRTREE exists and is executable, call it.
        [[ -x $cmd_STRTREE ]] && $cmd_STRTREE
        local -i _ap_isleeps=0
        local -i _ap_istarted=$($cmd_PROCESSCONTROL detaillist \
            | $cmd_GREP Stopped 2>$g_NULL | $cmd_WC -l)

        fn_call_monit $LINENO

        while [[ $_ap_isleeps -lt 100 && $_ap_istarted -gt $_ap_istopped ]]
        do #{
            sleep 3
            ((_ap_isleeps++))
            _ap_istarted=$($cmd_PROCESSCONTROL detaillist \
                | $cmd_GREP Stopped 2>$g_NULL | $cmd_WC -l)
        done #}

        fn_write_status $LINENO "Apply_Success"
        fn_write_event $LINENO I -1 "Apply_Success <- $LINENO of $g_PROGNAME"

    fi #}

    fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Apply_Success $_arg_ap_patch_name $_arg_ap_patch_ver"

    return 0
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 patch_name
###          $3 patch_ver
### Returns: 0 on success, 1 on failure.
fn_remove_transaction()
{
    fn_chkargs $FUNCNAME $LINENO $# 3 3 "LINENO, patch_name, patch_ver"
    local -r _arg_rt_patch_name=$2
    local -r _arg_rt_patch_ver=$3

    if [[ ! -e "$g_INFODIR/$_arg_rt_patch_name-$_arg_rt_patch_ver.$g_arch.umd.app" ]]
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "file $g_INFODIR/$_arg_rt_patch_name-$_arg_rt_patch_ver.$g_arch.umd.app missing, returning 1"
        return 1
    fi #}

    if [[ -e "$g_INFODIR/$_arg_rt_patch_name-$_arg_rt_patch_ver.$g_arch.umd.obs" ]]
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "file $g_INFODIR/$_arg_rt_patch_name-$_arg_rt_patch_ver.$g_arch.umd.obs present but should not be, returning 1"
        return 1
    fi #}

    local -r -i _rt_istopped=$($cmd_PROCESSCONTROL detaillist | \
        $cmd_GREP Stopped 2>$g_NULL | $cmd_WC -l)
    local -r _rt_tid=$($cmd_RPM -q --qf  "%{INSTALLTID}\n" \
        $_arg_rt_patch_name-$_arg_rt_patch_ver)
    echo "INSTALL TID($_arg_rt_patch_name-$_arg_rt_patch_ver): $_rt_tid" \
        >>$g_RBACKLOG

    ### this will build an exclude list simply looking at all TIDs and
    ### ignoring those that less than or equal to _rt_tid, thus the resulting
    ### list will contain only those we want to exclude
    local _rt_ltid=""
    local _rt_etid=""
    for _rt_etid in $($cmd_RPM -qa --qf  "%{INSTALLTID}\n")
    do #{
        [[ $_rt_etid -le $_rt_tid ]] && continue
        if [[ $_rt_ltid ]]
        then #{
            _rt_ltid="$_rt_ltid $_rt_etid"
        else #}{
            _rt_ltid=$_rt_etid
        fi #}
    done #}

    ### fn_get_umd_tag_value logs when it can't read a tag, so in the next
    ### few calls to fn_get_umd_tag_value we only check the return value if
    ### we have a need for conditional behaviour.
    local _rt_rpm_desc=
    fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_RAW $g_INFODIR \
        $_arg_rt_patch_name-$_arg_rt_patch_ver.$g_arch.umd \
        "DESCRIPTION" _rt_rpm_desc

    local _rt_rpm_rollback=
    if fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_DOWNCASE $g_INFODIR \
        $_arg_rt_patch_name-$_arg_rt_patch_ver.$g_arch.umd \
        "ALLOWROLLBACK" _rt_rpm_rollback
    then #{
        if [[ $_rt_rpm_rollback != yes ]]
        then #{
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Value of ROLLBACK read by fn_get_umd_tag_value $g_INFODIR $_arg_rt_patch_name-$_arg_rt_patch_ver.$g_arch.umd, is not the expected value of yes, returning 1"
            return 1
        fi #}
    else #}{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "fn_get_umd_tag_value $g_INFODIR $_arg_rt_patch_name-$_arg_rt_patch_ver.$g_arch.umd could not read ROLLBACK, assuming no"
    fi #}

    ### Note that %s is number of seconds since 00:00:00 1970-01-01 UTC.
    local -r -i _rt_date_now=$($cmd_DATE --date=now +%s)
    local -r -i _rt_date_then=$((_rt_date_now - _rt_tid + 10))
    echo "DATE NOW: $_rt_date_now --- DATE THEN: $_rt_date_then" >>$g_RBACKLOG
    fn_write_status $LINENO "Removing"
    local _rt_ret_code=
    if [[ $_rt_ltid ]]
    then #{
        echo "$cmd_RPM -Uvh --rollback \"$_rt_date_then seconds ago\" --rbexclude=\"$_rt_ltid\"" >>$g_RBACKLOG
        ### TODO what happens to $g_RPMLOG. As written, it appears
        ### it will grow indefinitely!
        echo "$cmd_RPM  --define '_rollback_transaction_on_failure 1' --define '_unsafe_rollbacks 1059710400' --define '_repackage_all_erasures 1' -Uvvh --rollback \"$_rt_date_then seconds ago\" --rbexclude=\"$_rt_ltid\"" >>$g_RPMLOG
        $($cmd_RPM \
            --define \
            '_rollback_transaction_on_failure 1' \
            --define '_unsafe_rollbacks 1059710400' \
            --define '_repackage_all_erasures 1' \
            -Uvvh \
            --rollback \
            "$_rt_date_then seconds ago" \
            --rbexclude="$_rt_ltid" \
                >>$g_RPMLOG 2>&1)
        _rt_ret_code=$?
    else #}{
        echo "$cmd_RPM -Uvh --rollback \"$_rt_date_then seconds ago\"" >>$g_RBACKLOG
        echo "$cmd_RPM  --define '_rollback_transaction_on_failure 1' --define '_unsafe_rollbacks 1059710400' --define '_repackage_all_erasures 1' -Uvvh --rollback \"$_rt_date_then seconds ago\"" >>$g_RPMLOG
        $($cmd_RPM \
            --define '_rollback_transaction_on_failure 1' \
            --define '_unsafe_rollbacks 1059710400' \
            --define '_repackage_all_erasures 1' \
            -Uvvh \
            --rollback "$_rt_date_then seconds ago" \
                >>$g_RPMLOG 2>&1)
        _rt_ret_code=$?
    fi #}

    if [[ $_rt_ret_code != 0 ]]
    then #{
        ### TODO this was 'E' 2305, but that's not in /nn/etc/DiaLoggerTaxonomy
        ### file. The closest match is 2303 which is listed in the taxonomy file
        ### as major, which should be 'W'.
        fn_write_event $LINENO W 2303 "Failed to remove software update."
        return 1
    else #}{
        echo "SUCCESS: ($_arg_rt_patch_name -$_rt_ret_code- $_arg_rt_patch_ver)" >>$g_RBACKLOG
    fi #}

    ### Append to the $g_PATCHHISTORY file, then rewrite it to show all
    ### occurrences of the patch we're working as NotRemovable. We also
    ### lock it against concurrent access while doing this.
    fn_lockfile $LINENO $g_PATCHHISTORY
    printf "%s\t%s\t%s\t%s\t%s\t%s\n" \
        "$_arg_rt_patch_name" \
        "$_arg_rt_patch_ver" \
        "$_rt_rpm_desc" \
        "Patch Removed" \
        "$($cmd_DATE '+%a %b %d %H:%M:%S %Y')" \
        "NotRemovable" \
        >>$g_PATCHHISTORY
    $cmd_SED -i "s/\(\<$_arg_rt_patch_name\>.*\<$_arg_rt_patch_ver\>.*\)\<Removable\>\(.*\)/\1NotRemovable\2/" $g_PATCHHISTORY
    [[ $? != 0 ]] && fn_exit $FUNCNAME $LINENO RET_RUNTIME_SED_FAILED "$cmd_SED call failed"
    fn_unlockfile $LINENO $g_PATCHHISTORY

    $cmd_RM -f $g_INFODIR/$_arg_rt_patch_name-$_arg_rt_patch_ver.$g_arch.umd.{app,str,trn,end,opts} &>$g_NULL

    $cmd_TOUCH $g_INFODIR/$_arg_rt_patch_name-$_arg_rt_patch_ver.$g_arch.umd.ava

    fn_write_status $LINENO "Restarting"

    ### If $cmd_STRTREE exists and is executable, call it.
    [[ -x $cmd_STRTREE ]] && $cmd_STRTREE

    local -i _rt_istarted=$($cmd_PROCESSCONTROL detaillist \
        | $cmd_GREP Stopped 2>$g_NULL | $cmd_WC -l)

    fn_call_monit $LINENO

    local -i _rt_isleeps=0
    while [[ $_rt_isleeps -lt 100 && $_rt_istarted -gt $_rt_istopped ]]
    do #{
        sleep 3
        ((_rt_isleeps++))
        _rt_istarted=$($cmd_PROCESSCONTROL detaillist \
            | $cmd_GREP Stopped 2>$g_NULL | $cmd_WC -l)
    done #}

    fn_write_status $LINENO "Remove_Success"
    fn_write_event $LINENO I 2106 "Software update removed."

    fn_call_monit $LINENO

    return 0
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 passback for download
###          $3 passback for apply
###          $4-$8 for download time
###          $9-$13 for apply time
###          See SECTION: "Conventions, Notes" for an explanation of the
###          five fields that make up a download/apply time.
### Returns: 0
fn_get_times()
{
    fn_chkargs $FUNCNAME $LINENO $# 13 13 "LINENO, passback_download, passback_apply, dl_DOW, dl_Mon, dl_Day, dl_time, dl_year, ap_DOW, ap_Mon, ap_Day, ap_time, ap_year"

    local -r _arg_passback_download=$2
    local -r _arg_passback_apply=$3

    eval "${_arg_passback_download}=\"$4 $5 $6 $7 $8\""
    ### Note that positional parameters greater than 9 must be enclosed
    ### in braces.
    eval "${_arg_passback_apply}=\"$9 ${10} ${11} ${12} ${13}\""

    return 0
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 patch_name
###          $3 patch_version
###          $4-$8 for download time
###          $9-$13 for apply time
###          See SECTION: "Conventions, Notes" for an explanation of the
###          five fields that make up a download/apply time.
### Returns: 0 on success, non-zero on failure
fn_schedule_transaction()
{
    fn_chkargs $FUNCNAME $LINENO $# 13 13 "LINENO, patch_name, patch_ver, dl_DOW, dl_Mon, dl_Day, dl_time, dl_year, ap_DOW, ap_Mon, ap_Day, ap_time, ap_year"

    local -r _arg_st_patch_name=$2
    local -r _arg_st_patch_ver=$3

    shift 3
    local _st_schedule_download=
    local _st_schedule_apply=
    fn_get_times $LINENO _st_schedule_download _st_schedule_apply $*

    ### This is to handle scheduling done via EM method (protocol 'em', i.e.
    ### a folder on "my computer"). EM allows user to change and set apply
    ### time only, however softinv gets both download time and apply time
    ### anyway, where apply time is the one set/changed by the user via EM
    ### however download time stays same as at the time schedule was set,
    ### so in case of EM mode we simply need to download time same as apply
    ### time then transaction gets scheduled as single apply. Note another
    ### issue is simply when user does not increase apply time at all which
    ### by the time it arrives here is considered in past and the error is
    ### there.
    ### TODO: due to removal of file $_arg_cfp_umd_file.$_arg_cfp_patch_proto
    ### in fn_generate_encrypted_proto (called by fn_check_for_packages), this
    ### will always fail. Need to find another way to determine if em was the
    ### protocol used.
    [[ -e "$g_INFODIR/$_arg_st_patch_name-$_arg_st_patch_ver.$g_arch.umd.em" ]] && _st_schedule_download=$_st_schedule_apply

    ### _d_ for download, _a_ for apply.
    ### Note that %s is number of seconds since 00:00:00 1970-01-01 UTC.
    local -r -i _st_d_sec=$($cmd_DATE --date="$_st_schedule_download" '+%s')
    local -r -i _st_a_sec=$($cmd_DATE --date="$_st_schedule_apply" '+%s')

    ### checking if download time is at not greater then apply time, as
    ### mentioned somewhere else, here we can check how different can
    ### download and apply time be, meaning, is there enough time for
    ### download to complete before apply kicks in, maybe apply can be
    ### postponed, but it should be handled  in apply or apply only
    if [[ $_st_d_sec -gt $_st_a_sec ]]
    then #{
        ### download time is later than apply time
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "download time is later than apply time, returning RET_SCHED_DLAFTERAPPLY=$RET_SCHED_DLAFTERAPPLY"
        return $RET_SCHED_DLAFTERAPPLY
    fi #}

    ### obviously, no need trying scheduling in past, check only
    ### download time since apply should be later
    ### Note that %s is number of seconds since 00:00:00 1970-01-01 UTC.
    if [[ $($cmd_DATE --date=now +%s) -ge $_st_d_sec ]]
    then #{
        ### attempt to schedule in past, why ???
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "attempt to schedule in past, why???, returning RET_SCHED_INPAST=$RET_SCHED_INPAST"
        return $RET_SCHED_INPAST
    fi #}

    if [[        -e "$g_INFODIR/$_arg_st_patch_name-$_arg_st_patch_ver.$g_arch.umd.ava" \
            && ! -e "$g_INFODIR/$_arg_st_patch_name-$_arg_st_patch_ver.$g_arch.umd.scd" ]]
    then #{

        ### This item is available (.ava exists) but is not yet
        ### scheduled (.scd is absent) so we'll create the schedule.

        if ! fn_check_requires $LINENO $_arg_st_patch_name \
                $_arg_st_patch_ver $_st_a_sec
        then #{
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "fn_check_requires $_arg_st_patch_name $_arg_st_patch_ver $_st_a_sec failed, must increase transaction apply time to satisfy requires, returning RET_SCHED_TRANS2SHORT=$RET_SCHED_TRANS2SHORT"
            return $RET_SCHED_TRANS2SHORT
        fi #}

        fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "Writing $_arg_st_patch_name $_arg_st_patch_ver $_st_schedule_download $_st_schedule_apply to $g_INFODIR/$_arg_st_patch_name-$_arg_st_patch_ver.$g_arch.umd.scd"
        printf "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" \
            "$_arg_st_patch_name" \
            "$_arg_st_patch_ver" \
            "$_st_schedule_download" \
            "$_st_schedule_apply" \
            >$g_INFODIR/$_arg_st_patch_name-$_arg_st_patch_ver.$g_arch.umd.scd

        ### fn_get_umd_tag_value logs when it can't read a tag, so in the next
        ### few calls to fn_get_umd_tag_value we only check the return value if
        ### we have a need for additional conditional behaviour.

        local _st_umd_desc=
        fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_RAW $g_INFODIR \
            $_arg_st_patch_name-$_arg_st_patch_ver.$g_arch.umd \
            "DESCRIPTION" _st_umd_desc

        local _st_umd_reboot=
        fn_read_reboot $FUNCNAME $LINENO $g_INFODIR \
            $_arg_st_patch_name-$_arg_st_patch_ver.$g_arch.umd _st_umd_reboot

        local _st_umd_size=
        fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_RAW $g_INFODIR \
            $_arg_st_patch_name-$_arg_st_patch_ver.$g_arch.umd \
            "SIZE" _st_umd_size

        local _st_display_path=
        read _st_display_path <$g_LOCATIONLOG

        fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "Appending $_arg_st_patch_name $_arg_st_patch_ver $_st_umd_desc $_st_display_path $_st_schedule_download $_st_schedule_apply $_st_umd_reboot $_st_umd_size Scheduled to $g_INFODIR/schedule.scd"

        fn_lockfile $LINENO $g_INFODIR/schedule.scd
        printf "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" \
            "$_arg_st_patch_name" \
            "$_arg_st_patch_ver" \
            "$_st_umd_desc" \
            "$_st_display_path" \
            "$_st_schedule_download" \
            "$_st_schedule_apply" \
            "$_st_umd_reboot" \
            "$_st_umd_size" \
            "Scheduled" \
            >>$g_INFODIR/schedule.scd
        fn_unlockfile $LINENO $g_INFODIR/schedule.scd

        local _st_tmp_sched_file_1=
        fn_make_temp_file $LINENO _st_tmp_sched_file_1

        ### _st_d_time for download, %M %H %d %m are minute, hour, day
        ### and month.
        local -r _st_d_time="$($cmd_DATE --date="$_st_schedule_download" '+%M %H %d %m')"
        if [[ $_st_d_sec -eq $_st_a_sec ]]
        then #{
            ### Download time same as apply time, so schedule using --apply.
            ### Also see the comments under the definition of g_CRONTAB_LOG.
            echo "$_st_d_time * $cmd_SOFTINV --apply $_arg_st_patch_name $_arg_st_patch_ver &>$g_CRONTAB_LOG" >$_st_tmp_sched_file_1
        else #}{
            ### Download time different than apply time, so schedule download
            ### using --donly, then schedule apply using --aonly.
            ### Also see the comments under the definition of g_CRONTAB_LOG.
            echo "$_st_d_time * $cmd_SOFTINV --donly $_arg_st_patch_name $_arg_st_patch_ver &>$g_CRONTAB_LOG" >$_st_tmp_sched_file_1
            ### _st_a_time for download, %M %H %d %m are minute, hour, day
            ### and month.
            local -r _st_a_time="$($cmd_DATE --date="$_st_schedule_apply" '+%M %H %d %m')"
            ### Also see the comments under the definition of g_CRONTAB_LOG.
            echo "$_st_a_time * $cmd_SOFTINV --aonly $_arg_st_patch_name $_arg_st_patch_ver &>$g_CRONTAB_LOG" >>$_st_tmp_sched_file_1
        fi #}

        ### get current crontab spool into temporary file to add schedule
        ### this item, otherwise then entire crontab spool is overwritten,
        ### also double check if this item is already scheduled
        local _st_tmp_sched_file_2=
        fn_make_temp_file $LINENO _st_tmp_sched_file_2
        $cmd_CRONTAB -l 2>$g_NULL \
            | $cmd_EGREP -v '^ *#|^ *$' >$_st_tmp_sched_file_2 2>$g_NULL

        ### we also should check if there is any scheduling entry already
        ### about this item, although *.scd should have indicated this
        ### already, let's assume the schedule simply was not cleared upon
        ### completion, meaning, when scheduled item has completed it
        ### should cleared itself out of crontab spooling system

        $cmd_CAT $_st_tmp_sched_file_1 >>$_st_tmp_sched_file_2

        $cmd_CRONTAB $_st_tmp_sched_file_2

        $cmd_RM -f  $_st_tmp_sched_file_1 \
                    $_st_tmp_sched_file_2 \
                    &>$g_NULL

        local -r _st_td=$($cmd_DATE '+%a %b %d %H:%M:%S %Y')

        ### Append to the $g_PATCHHISTORY file, locking it against concurrent
        ### access.
        fn_lockfile $LINENO $g_PATCHHISTORY
        printf "%s\t%s\t%s\t%s\t%s\t%s\n" \
            "$_arg_st_patch_name" \
            "$_arg_st_patch_ver" \
            "$_st_umd_desc" \
            "Scheduled" \
            "$_st_td" \
            "NotRemovable" \
            >>$g_PATCHHISTORY
        fn_unlockfile $LINENO $g_PATCHHISTORY

    elif [[ -e "$g_INFODIR/$_arg_st_patch_name-$_arg_st_patch_ver.$g_arch.umd.scd" ]]; then #}{

        ### this item has been already scheduled, modify or remove first,
        ### this also handled if the schedule is actually in crontab
        ### spooling system
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "attempt to schedule already scheduled transaction, delete first, returning RET_SCHED_ALREADYSCHED=$RET_SCHED_ALREADYSCHED"
        return $RET_SCHED_ALREADYSCHED

    else #}{

        ### There is neither *.ava nor *.scd for this item. This item can not
        ### be scheduled as it is not available (no .ava file). The logic
        ### should not actually get here unless used through CLI. Internal
        ### error to scheduler (i.e., application error) so should really be
        ### reported to support.
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "internal error to scheduler, returning RET_SCHED_INTRNLERROR=$RET_SCHED_INTRNLERROR"
        return $RET_SCHED_INTRNLERROR

    fi #}

    return $RET_OK
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 patch_name
###          $3 patch_version
###          $4 apply_time
### Returns: 0 on success, 1 on failure
fn_check_requires()
{
    fn_chkargs $FUNCNAME $LINENO $# 4 4 "LINENO, patch_name, patch_version, apply_time"
    local -r    _arg_cr_patch_name=$2
    local -r    _arg_cr_patch_ver=$3
    local -r -i _arg_cr_apply_time_sec=$4

    ### we can not schedule an item that has an item in its requires list
    ### that has not been applied or scheduled to be applied prior to schedule
    ### time of this item now, if the item is available it means the requires
    ### list has been satisfied, meaning every item is either already in rpm
    ### db or has been scheduled to get there we need to add one more rule
    ### here, this item's dwn/app times  must be greater than dwn/app times
    ### for every item in its requires scheduled list
    if ! $cmd_XPATHPARSE $g_INFODIR/$_arg_cr_patch_name-$_arg_cr_patch_ver.$g_arch.umd "//REQUIRES/text()" >&$g_NULL
    then #{
        fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "$g_INFODIR/$_arg_cr_patch_name-$_arg_cr_patch_ver.$g_arch.umd no REQUIRES, nothing to check, returning 0"
        return 0
    fi #}

    ### so, here we really do not need to check whether requires list of this
    ### item has been satisfied, it is already known, otherwise the item would
    ### not be available
    local _cr_unused_name=
    local _cr_unused_ver=
    local _cr_tmn=
    local _cr_apply=
    local _cr_scd_file=
    local _cr_requires=
    while read -r _cr_requires
    do #{
        ### Note the truncation of _cr_requires on space or lexical
        ### comparators. This is because _cr_requires can be expressed
        ### absolutely or relatively. For example package 'some-pkg'
        ### version '1.2' release '3.4' would be expressed absolutely as
        ### 'some-pkg-1.2-3.4'. If we wanted to specify the same package
        ### requirement as greater than the indicated version, it would
        ### be 'some-pkg > 1.2-3.4' or 'some-pkg>1.2-3.4' (the latter
        ### being without any spaces.)
        _cr_scd_file=$g_INFODIR/${_cr_requires%%[>=< ]*}.$g_arch.umd.scd

        ### if at least one item in the list found to be scheduled then check
        ### whether the app time for this item is later, otherwise schedule
        ### can not go on
        ### we do not care about download time, since it is guaranteed to be
        ### less then or equal to apply time, otherwise the item would not be
        ### scheduled
        if [[ -e $_cr_scd_file ]]
        then #{

            read _cr_unused_name _cr_unused_ver _cr_tmn <$_cr_scd_file

            fn_get_times $LINENO g_dummy _cr_apply $_cr_tmn

            ### only need to find one scheduled item that is scheduled later
            ### than this item intended to be
            ### Note that %s is number of seconds since 00:00:00 1970-01-01 UTC.
            if [[ $($cmd_DATE --date="$_cr_apply" '+%s') \
                    -ge $_arg_cr_apply_time_sec ]]
            then #{
                fn_log $g_LOGALWAYS $FUNCNAME $LINENO "found item scheduled later than expected, returning 1"
                return 1
            fi #}
        fi #}
    done < <($cmd_XPATHPARSE $g_INFODIR/$_arg_cr_patch_name-$_arg_cr_patch_ver.$g_arch.umd "//REQUIRES/text()" 2>$g_NULL) #}

    return 0
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 patch_name
###          $3 patch_ver
###          $4 applied (TRUE if called because patch was applied)
###          Remaining args optional:
###          $5-$9 for download time
###          $10-$14 for apply time
###          See SECTION: "Conventions, Notes" for an explanation of the
###          five fields that make up a download/apply time.
### Returns: $RET_OK on success, non-zero on failure.
fn_modify_schedule()
{
    fn_chkargs $FUNCNAME $LINENO $# 4 14 "LINENO, patch_name, patch_ver, applied, dl_DOW, dl_Mon, dl_Day, dl_time, dl_year, ap_DOW, ap_Mon, ap_Day, ap_time, ap_year"

    local -r _arg_ms_patch_name=$2
    local -r _arg_ms_patch_ver=$3
    local -r _arg_ms_applied=$4

    local -r _ms_msched_incl_time=$([[ $# -gt 4 ]] && echo true || echo false)

    ### Is this a scheduled item?
    if [[ ! -e "$g_INFODIR/$_arg_ms_patch_name-$_arg_ms_patch_ver.$g_arch.umd.scd" ]]
    then #{
        ### this item was not scheduled, schedule first to modify, should
        ### not get here unless via CLI
        ### internal error to scheduler, should really be reported
        ### to support.
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "internal error to scheduler, returning RET_MSCHED_INTRNLERROR=$RET_MSCHED_INTRNLERROR"
        return $RET_MSCHED_INTRNLERROR
    fi #}

    ### If we get to here, this item was scheduled and still active
    local _ms_patch_name_read=
    local _ms_patch_ver_read=
    local _ms_dl_and_ap_time_old_read=
    read _ms_patch_name_read _ms_patch_ver_read _ms_dl_and_ap_time_old_read \
      <$g_INFODIR/$_arg_ms_patch_name-$_arg_ms_patch_ver.$g_arch.umd.scd

    ### Note that this comparison is case insensitive
    if [[ $(echo $_arg_ms_patch_name | tr '[:upper:]' '[:lower:]') \
            != $(echo $_ms_patch_name_read | tr '[:upper:]' '[:lower:]') ]]
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "passed patch name=\"$_arg_ms_patch_name\" does not agree with read patch name=\"$_ms_patch_name_read\", returning RET_MSCHED_PATCHMISMATCH=$RET_MSCHED_PATCHMISMATCH"
        return $RET_MSCHED_PATCHMISMATCH
    fi #}

    if [[ $_arg_ms_patch_ver != $_ms_patch_ver_read ]]
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "passed patch version=\"$_arg_ms_patch_ver\" does not agree with read patch version=\"$_ms_patch_ver_read\", returning RET_MSCHED_PATCHMISMATCH=$RET_MSCHED_PATCHMISMATCH"
        return $RET_MSCHED_PATCHMISMATCH
    fi #}

    ### OK, _ms_dl_and_ap_time_old_read contains the download and apply time as
    ### a string (read from the .scd file.) Let's decompose it into download
    ### and apply time.
    local _ms_dl_time_old_read=
    local _ms_ap_time_old_read=
    fn_get_times $LINENO _ms_dl_time_old_read _ms_ap_time_old_read $_ms_dl_and_ap_time_old_read

    ### %M %H %d %m are minute, hour, day and month.
    local -r _ms_dl_time_old="$($cmd_DATE --date="$_ms_dl_time_old_read" '+%M %H %d %m')"
    local -r _ms_ap_time_old="$($cmd_DATE --date="$_ms_ap_time_old_read" '+%M %H %d %m')"

    local _ms_tag_value=
    if [[ $_ms_msched_incl_time = true ]]
    then #{
        shift 4
        local _arg_ms_msched_dltime_new=
        local _arg_ms_msched_aptime_new=

        fn_get_times $LINENO  _arg_ms_msched_dltime_new _arg_ms_msched_aptime_new $_ms_dl_and_ap_time_old_read

        ### In case of EM method (i.e., protocol 'em'), the download time
        ### may not be scheduled, only the apply time, so we just force the
        ### download time to be equivalent to apply time.
        ### TODO: due to removal of file
        ### $_arg_cfp_umd_file.$_arg_cfp_patch_proto file in
        ### fn_generate_encrypted_proto (called by fn_check_for_packages),
        ### this will always fail. Need to find another way to determine
        ### if em was the protocol used.
        [[ -e "$g_INFODIR/$_arg_ms_patch_name-$_arg_ms_patch_ver.$g_arch.umd.em" ]] && _arg_ms_msched_dltime_new=$_arg_ms_msched_aptime_new

        ### Note that %s is number of seconds since 00:00:00 1970-01-01 UTC.
        local -r -i _ms_dl_sec_new=$($cmd_DATE --date="$_arg_ms_msched_dltime_new" '+%s')
        local -r -i _ms_ap_sec_new=$($cmd_DATE --date="$_arg_ms_msched_aptime_new" '+%s')

        ### before doing anything else, let's check whether download time
        ### is less than or equal to apply time, only proceed if not
        ### can be enhanced to handle situation where delta between those
        ### two should take into account the time it takes for download
        ### however, apply may be allowed to schedule within short period
        ### of time, however when during apply to wait until download is
        ### done
        ### If this is invalid schedule, return with error
        if [[ $_ms_dl_sec_new -gt $_ms_ap_sec_new ]]
        then #{
            ### download time is later than apply time
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "download time is later than apply time, returning RET_MSCHED_DLAFTERAPPLY=$RET_MSCHED_DLAFTERAPPLY"
            return $RET_MSCHED_DLAFTERAPPLY
        fi #}
    fi #}

    ### this is going to hold current crontab system wide spooled items,
    ### we only edit patch relevant items
    local _ms_tmp_msched_file_1=
    fn_make_temp_file $LINENO _ms_tmp_msched_file_1
    $cmd_CRONTAB -l 2>$g_NULL \
        | $cmd_EGREP -v '^ *#|^ *$' >$_ms_tmp_msched_file_1 2>$g_NULL

    local _ms_tmp_msched_file_2=
    fn_make_temp_file $LINENO _ms_tmp_msched_file_2

    ### Note that %s is number of seconds since 00:00:00 1970-01-01 UTC.
    local -r -i _ms_dl_sec_old=$($cmd_DATE --date="$_ms_dl_time_old_read" '+%s')
    local -r -i _ms_ap_sec_old=$($cmd_DATE --date="$_ms_ap_time_old_read" '+%s')
    if [[ $_ms_msched_incl_time = true ]]
    then #{
        ### it is all or nothing situation, the scheduling can be change
        ### for both times only, not separately

        ### obviously, no need trying re-scheduling in past
        ### Note that %s is number of seconds since 00:00:00 1970-01-01 UTC.
        if [[ $($cmd_DATE --date=now +%s) -lt $_ms_dl_sec_new   &&  $(($_ms_dl_sec_new + 120)) -ge  $($cmd_DATE --date=now +%s) ]]
        then #{
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "attempt to schedule in past, why???, returning RET_MSCHED_INPAST=$RET_MSCHED_INPAST"
            return $RET_MSCHED_INPAST
        fi #}

        ### check if there is any scheduled items in requires list and
        ### they've been scheduled before this scheduling time means the
        ### time you trying to schedule is less or equal to the time of
        ### at least one item in your requires list
        if ! fn_check_requires $LINENO \
                $_arg_ms_patch_name $_arg_ms_patch_ver $_ms_ap_sec_new
        then #{
            ### must increase transaction apply time to satisfy requires
            fn_log $g_LOGALWAYS $FUNCNAME $LINENO "fn_check_requires $_arg_ms_patch_name $_arg_ms_patch_ver $_ms_ap_sec_new failed, must increase transaction apply time to satisfy requires, returning RET_MSCHED_TRANS2SHORT=$RET_MSCHED_TRANS2SHORT"
            return $RET_MSCHED_TRANS2SHORT
        fi #}

        ### %M %H %d %m are minute, hour, day and month.
        local -r _ms_dl_time_new=$($cmd_DATE --date="$_arg_ms_msched_dltime_new" '+%M %H %d %m')
        local -r _ms_ap_time_new=$($cmd_DATE --date="$_arg_ms_msched_aptime_new" '+%M %H %d %m')

        ### if previously scheduled item was --apply only (means download and
        ### apply time are same)
        if [[ $_ms_dl_sec_old -eq $_ms_ap_sec_old ]]
        then #{

            ### then if new download and apply time are same then simply replace
            ### old --apply item with a new --apply item
            if [[ $_ms_dl_sec_new -eq $_ms_ap_sec_new ]]
            then #{
                ### here we need to look at system spool and delete
                ### previous entry, it should not be hard, we have
                ### all the ingredients to describe previous scheduled
                ### same item. Also see the comments under the definition
                ### of g_CRONTAB_LOG. See the discussion of sed under
                ### SECTION: "Conventions, Notes" for an explanation of
                ### the '~' in the sed command.
                $cmd_SED -e "s~^ *$_ms_dl_time_old \* $cmd_SOFTINV --apply $_arg_ms_patch_name $_arg_ms_patch_ver \&>$g_CRONTAB_LOG.*$~$_ms_dl_time_new \* $cmd_SOFTINV --apply $_arg_ms_patch_name $_arg_ms_patch_ver \&>$g_CRONTAB_LOG~" $_ms_tmp_msched_file_1 >$_ms_tmp_msched_file_2
                [[ $? != 0 ]] && fn_exit $FUNCNAME $LINENO RET_RUNTIME_SED_FAILED "$cmd_SED call failed"
            else #}{
                ### else the old item was schedule as --apply and the new
                ### one should be split into download and apply items, so
                ### delete old -apply item and create a new one, split into
                ### download and apply items. Also see the comments under
                ### the definition of g_CRONTAB_LOG. See the discussion of
                ### sed under SECTION: "Conventions, Notes" for an explanation
                ### of the '~' in the sed command.
                $cmd_SED -e "s~^ *$_ms_dl_time_old \* $cmd_SOFTINV --apply $_arg_ms_patch_name $_arg_ms_patch_ver \&>$g_CRONTAB_LOG.*$~~" $_ms_tmp_msched_file_1 >>$_ms_tmp_msched_file_2
                [[ $? != 0 ]] && fn_exit $FUNCNAME $LINENO RET_RUNTIME_SED_FAILED "$cmd_SED call failed"
                echo "$_ms_dl_time_new * $cmd_SOFTINV --donly $_arg_ms_patch_name $_arg_ms_patch_ver &>$g_CRONTAB_LOG" >>$_ms_tmp_msched_file_2
                echo "$_ms_ap_time_new * $cmd_SOFTINV --aonly $_arg_ms_patch_name $_arg_ms_patch_ver &>$g_CRONTAB_LOG" >>$_ms_tmp_msched_file_2
            fi #}
        else #}{
            ### The previous old (previously scheduled item we're modifying)
            ### had separate download and apply times.

            if [[ $_ms_dl_sec_new -eq $_ms_ap_sec_new ]]
            then #{
                ### so new item should be schedule simply as --apply,
                ### thus delete download and apply items and sched --apply

                ### _ms_tmp_msched_file_1 holds system wide spooling
                ### information, first delete download scheduled entry
                ### and save result in _ms_tmp_msched_file_2. Also see
                ### the comments under the definition of g_CRONTAB_LOG.
                ### See the discussion of sed under SECTION:
                ### "Conventions, Notes" for an explanation of the '~'
                ### in the sed command.
                $cmd_SED -e "s~^ *$_ms_dl_time_old \* $cmd_SOFTINV --donly $_arg_ms_patch_name $_arg_ms_patch_ver \&>$g_CRONTAB_LOG.*$~~" $_ms_tmp_msched_file_1 >$_ms_tmp_msched_file_2
                [[ $? != 0 ]] && fn_exit $FUNCNAME $LINENO RET_RUNTIME_SED_FAILED "$cmd_SED call failed"

                ### take _ms_tmp_msched_file_2 and delete apply scheduled
                ### entry from it, save in _ms_tmp_msched_file_1, overwrite
                ### it. Also see the comments under the definition of
                ### g_CRONTAB_LOG. See the discussion of sed under
                ### SECTION: "Conventions, Notes" for an explanation of
                ### the '~' in the sed command.
                $cmd_SED -e "s~^ *$_ms_ap_time_old \* $cmd_SOFTINV --aonly $_arg_ms_patch_name $_arg_ms_patch_ver \&>$g_CRONTAB_LOG.*$~~" $_ms_tmp_msched_file_2 >$_ms_tmp_msched_file_1
                [[ $? != 0 ]] && fn_exit $FUNCNAME $LINENO RET_RUNTIME_SED_FAILED "$cmd_SED call failed"

                ### Now add single apply entry
                ### Also see the comments under the definition of g_CRONTAB_LOG.
                echo "$_ms_dl_time_new * $cmd_SOFTINV --apply $_arg_ms_patch_name $_arg_ms_patch_ver &>$g_CRONTAB_LOG" >>$_ms_tmp_msched_file_1

                ### now move it all to _ms_tmp_msched_file_2, so that we
                ### eventually end up in a single file to feed to crontab
                $cmd_CAT $_ms_tmp_msched_file_1 >$_ms_tmp_msched_file_2
            else #}{
                ### old and new items were and will be done separately per
                ### dwn and app times. Also see the comments under the
                ### definition of g_CRONTAB_LOG. See the discussion of sed
                ### under SECTION: "Conventions, Notes" for an explanation
                ### of the '~' in the sed command.
                $cmd_SED -e "s~^ *$_ms_dl_time_old \* $cmd_SOFTINV --donly $_arg_ms_patch_name $_arg_ms_patch_ver \&>$g_CRONTAB_LOG.*$~$_ms_dl_time_new \* $cmd_SOFTINV --donly $_arg_ms_patch_name $_arg_ms_patch_ver \&>$g_CRONTAB_LOG~" $_ms_tmp_msched_file_1 >$_ms_tmp_msched_file_2
                [[ $? != 0 ]] && fn_exit $FUNCNAME $LINENO RET_RUNTIME_SED_FAILED "$cmd_SED call failed"

                $cmd_SED -e "s~^ *$_ms_ap_time_old \* $cmd_SOFTINV --aonly $_arg_ms_patch_name $_arg_ms_patch_ver \&>$g_CRONTAB_LOG.*$~$_ms_ap_time_new \* $cmd_SOFTINV --aonly $_arg_ms_patch_name $_arg_ms_patch_ver \&>$g_CRONTAB_LOG~" $_ms_tmp_msched_file_2 >$_ms_tmp_msched_file_1
                [[ $? != 0 ]] && fn_exit $FUNCNAME $LINENO RET_RUNTIME_SED_FAILED "$cmd_SED call failed"

                ### now move it all to _ms_tmp_msched_file_2, so that we
                ### eventually end up in a single file to feed to crontab
                $cmd_CAT $_ms_tmp_msched_file_1 >$_ms_tmp_msched_file_2

            fi #}
        fi #}
         echo "$_arg_ms_patch_name $_arg_ms_patch_ver $($cmd_DATE --date="$_arg_ms_msched_dltime_new" '+%a %b %d %H:%M:%S %Y') $($cmd_DATE --date="$_arg_ms_msched_aptime_new" '+%a %b %d %H:%M:%S %Y')" >$g_INFODIR/$_arg_ms_patch_name-$_arg_ms_patch_ver.$g_arch.umd.scd

        ### Modify schedule cache to remove the patch we're working on.
        fn_lockfile $LINENO $g_INFODIR/schedule.scd
        $cmd_SED -i "/\<$_arg_ms_patch_name\>.*\<$_arg_ms_patch_ver\>.*/d" $g_INFODIR/schedule.scd
        [[ $? != 0 ]] && fn_exit $FUNCNAME $LINENO RET_RUNTIME_SED_FAILED "$cmd_SED call failed"
        fn_unlockfile $LINENO $g_INFODIR/schedule.scd

        if ! fn_get_package_tag_value $FUNCNAME $LINENO $g_INFODIR \
            $_arg_ms_patch_name-$_arg_ms_patch_ver.$g_arch.uxd \
            "DESCRIPTION" _ms_tag_value
        then #{
            fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "fn_get_package_tag_value unable to read DESCRIPTION, returning RET_MSCHED_GEN=$RET_MSCHED_GEN"
            return $RET_MSCHED_GEN
        fi #}

        local _ms_umd_reboot=
        fn_read_reboot $FUNCNAME $LINENO $g_INFODIR \
            $_arg_ms_patch_name-$_arg_ms_patch_ver.$g_arch.umd _ms_umd_reboot

        ### fn_get_umd_tag_value logs when it can't read a tag, so since
        ### it's no big deal if we can't read SIZE, we don't need to check
        ### the return value here.
        local _ms_umd_size=
        fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_RAW $g_INFODIR \
            $_arg_ms_patch_name-$_arg_ms_patch_ver.$g_arch.umd \
            "SIZE" _ms_umd_size

        local _ms_display_path=
        read _ms_display_path <$g_LOCATIONLOG
        fn_lockfile $LINENO $g_INFODIR/schedule.scd
        printf "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" \
            "$_arg_ms_patch_name" \
            "$_arg_ms_patch_ver" \
            "$_ms_tag_value" \
            "$_ms_display_path" \
            "$_arg_ms_msched_dltime_new" \
            "$_arg_ms_msched_aptime_new" \
            "$_ms_umd_reboot" \
            "$_ms_umd_size" \
            "Scheduled" \
            >>$g_INFODIR/schedule.scd
        fn_unlockfile $LINENO $g_INFODIR/schedule.scd

    else #}{

        ### this is a simple remove item from the schedule, so just
        ### remove it
        fn_log $g_LOGINFO $FUNCNAME $LINENO "Removing the scheduled patch from cron for $_arg_ms_patch_name $_arg_ms_patch_ver"
        if [[ $_ms_dl_sec_old -eq $_ms_ap_sec_old ]]
        then #{
            ### See the discussion of sed under SECTION: "Conventions, Notes"
            ### for an explanation of the '~' in the sed command.
            ### Also see the comments under the definition of g_CRONTAB_LOG.
            $cmd_SED -e "s~^ *$_ms_dl_time_old \* $cmd_SOFTINV --apply $_arg_ms_patch_name $_arg_ms_patch_ver \&>$g_CRONTAB_LOG.*$~~" $_ms_tmp_msched_file_1 >$_ms_tmp_msched_file_2
            [[ $? != 0 ]] && fn_exit $FUNCNAME $LINENO RET_RUNTIME_SED_FAILED "$cmd_SED call failed"
        else #}{
            ### See the discussion of sed under SECTION: "Conventions, Notes"
            ### for an explanation of the '~' in the sed command.
            ### Also see the comments under the definition of g_CRONTAB_LOG.
            $cmd_SED -e "s~^ *$_ms_dl_time_old \* $cmd_SOFTINV --donly $_arg_ms_patch_name $_arg_ms_patch_ver \&>$g_CRONTAB_LOG.*$~~" $_ms_tmp_msched_file_1 >$_ms_tmp_msched_file_2
            [[ $? != 0 ]] && fn_exit $FUNCNAME $LINENO RET_RUNTIME_SED_FAILED "$cmd_SED call failed"

            $cmd_SED -e "s~^ *$_ms_ap_time_old \* $cmd_SOFTINV --aonly $_arg_ms_patch_name $_arg_ms_patch_ver \&>$g_CRONTAB_LOG.*$~~" $_ms_tmp_msched_file_2 >$_ms_tmp_msched_file_1
            [[ $? != 0 ]] && fn_exit $FUNCNAME $LINENO RET_RUNTIME_SED_FAILED "$cmd_SED call failed"

            ### now move it all to _ms_tmp_msched_file_2, so that we eventually
            ### end up in a single file to feed to crontab
            $cmd_CAT $_ms_tmp_msched_file_1 >$_ms_tmp_msched_file_2
        fi #}

        fn_log $g_LOGINFO $FUNCNAME $LINENO "Removing the .scd file for $_arg_ms_patch_name $_arg_ms_patch_ver"
        $cmd_RM -f \
            $g_INFODIR/$_arg_ms_patch_name-$_arg_ms_patch_ver.$g_arch.umd.scd \
            &>$g_NULL

        ### Modify schedule cache to remove the patch we're working on.
        fn_lockfile $LINENO $g_INFODIR/schedule.scd
        $cmd_SED -i "/\<$_arg_ms_patch_name\>.*\<$_arg_ms_patch_ver\>.*/d" $g_INFODIR/schedule.scd
        [[ $? != 0 ]] && fn_exit $FUNCNAME $LINENO RET_RUNTIME_SED_FAILED "$cmd_SED call failed"
        fn_unlockfile $LINENO $g_INFODIR/schedule.scd

        $cmd_CRONTAB $_ms_tmp_msched_file_2
        $cmd_RM -f  $_ms_tmp_msched_file_1 \
                    $_ms_tmp_msched_file_2 \
                    &>$g_NULL
    fi #}

    ### $_arg_ms_applied indicates that scheduled item is being removed
    ### because it has been applied, so we just want to remove scheduling
    ### info. There is no need to reflect it in history since apply history
    ### takes care of it.
    if [[ $_arg_ms_applied != TRUE ]]
    then #{
        local _ms_act=
        [[ $_ms_msched_incl_time = true ]] \
            && _ms_act="Patch Schedule Modified" \
            || _ms_act="Patch Schedule Removed"

        if ! fn_get_package_tag_value $FUNCNAME $LINENO $g_INFODIR \
            $_arg_ms_patch_name-$_arg_ms_patch_ver.$g_arch.uxd \
            "DESCRIPTION" _ms_tag_value
        then #{
            fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "fn_get_package_tag_value unable to read DESCRIPTION, returning RET_MSCHED_GEN=$RET_MSCHED_GEN"
            return $RET_MSCHED_GEN
        fi #}

        ### Append to the $g_PATCHHISTORY file, locking it against concurrent
        ### access.
        fn_lockfile $LINENO $g_PATCHHISTORY
        printf "%s\t%s\t%s\t%s\t%s\t%s\n" \
                "$_arg_ms_patch_name" \
                "$_arg_ms_patch_ver" \
                "$_ms_tag_value" \
                "$_ms_act" \
                "$($cmd_DATE '+%a %b %d %H:%M:%S %Y')" \
                "NotRemovable" \
                >>$g_PATCHHISTORY

        ### If the $_ms_msched_incl_time = false, we're removing the scheduled
        ### patch, so the previously scheduled patch needs to be marked as
        ### NotRemovable in the history file.
        $cmd_SED -i "s/\(\<$_arg_ms_patch_name\>.*\<$_arg_ms_patch_ver\>.*\)\<Removable\>\(.*\)/\1NotRemovable\2/" $g_PATCHHISTORY
        [[ $? != 0 ]] && fn_exit $FUNCNAME $LINENO RET_RUNTIME_SED_FAILED "$cmd_SED call failed"

        fn_unlockfile $LINENO $g_PATCHHISTORY
    fi #}

    ### scheduled OK
    fn_log $g_LOGWARN $FUNCNAME $LINENO "returning RET_OK=$RET_OK"
    return $RET_OK
}

################################################################################
### Args:    $1 calling $LINENO
### Returns: 0
fn_remove_schedule()
{

    local _remove_schedule_patch_name=
    local _remove_schedule_patch_ver=

    ### We are going to utilize fn_modify_schedule here since if it gets only
    ### name and version of patch and not the time, it deletes it instead of
    ### modifying it.
    local _remove_schedule_scd_file=
    for _remove_schedule_scd_file in $($cmd_LS -1 $g_INFODIR/*.scd 2>$g_NULL)
    do #{
        ### Skip the schedule.scd file.
        [[ $_remove_schedule_scd_file == $g_INFODIR/schedule.scd ]] && continue
        read _remove_schedule_patch_name _remove_schedule_patch_ver \
            g_dummy <$_remove_schedule_scd_file
        fn_modify_schedule $LINENO \
            $_remove_schedule_patch_name $_remove_schedule_patch_ver FALSE
    done #}

    return 0
}

################################################################################
### Args:    $1 calling $LINENO
### Returns: 0
fn_query_apply()
{
    fn_chkargs $FUNCNAME $LINENO $# 1 1 "LINENO"
    ### this is just to query for what has been schedule so far
    ### Can't use -e test here due to globbing of asterisk.
    if $($cmd_LS -1 $g_INFODIR/*.str &>$g_NULL)
    then #{
        local _qa_str_tmn=
        local _qa_patch_name=
        local _qa_patch_ver=
        local _qa_umd_desc=
        local _qa_umd_reboot=
        local _qa_umd_size=
        local _qa_location=
        local _qa_location_massaged=

        local _qa_str_file=
        for _qa_str_file in $($cmd_LS -1 $g_INFODIR/*.str 2>$g_NULL)
        do #{
            fn_log $g_LOGWARN $FUNCNAME $LINENO "processing $_qa_str_file"

            read _qa_patch_name _qa_patch_ver _qa_str_tmn <$_qa_str_file
            if [[ -e "$g_INFODIR/$_qa_patch_name-$_qa_patch_ver.$g_arch.umd.end" ]]
            then #{
                fn_log $g_LOGWARN $FUNCNAME $LINENO "file $g_INFODIR/$_qa_patch_name-$_qa_patch_ver.$g_arch.umd.end exists, continue"
                continue
            fi #}

            read _qa_location <$g_LOCATIONLOG
            _qa_location_massaged="$_qa_location"
            fn_massage_path $LINENO _qa_location_massaged

            ### fn_get_umd_tag_value logs when it can't read a tag, so in
            ### the next few calls to fn_get_umd_tag_value we only check
            ### the return value if we have a need for conditional behaviour.

            fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_RAW $g_INFODIR \
                $_qa_patch_name-$_qa_patch_ver.$g_arch.umd \
                "DESCRIPTION" _qa_umd_desc

            fn_read_reboot $FUNCNAME $LINENO $g_INFODIR \
                $_qa_patch_name-$_qa_patch_ver.$g_arch.umd _qa_umd_reboot

            fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_RAW $g_INFODIR \
                $_qa_patch_name-$_qa_patch_ver.$g_arch.umd \
                "SIZE" _qa_umd_size

            fn_log $g_LOGWARN $FUNCNAME $LINENO "printing to stdout: \"$_qa_patch_name $_qa_patch_ver $_qa_umd_desc $_qa_location_massaged $_qa_str_tmn $_qa_umd_size Active $_qa_umd_reboot\""
            ### Also send the output to file descriptor 6 which is where stdout
            ### was preserved to when I/O redirection was turned on.
            printf "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" \
                "$_qa_patch_name" \
                "$_qa_patch_ver" \
                "$_qa_umd_desc" \
                "$_qa_location_massaged" \
                "$_qa_str_tmn" \
                "$_qa_umd_size" \
                "Active" \
                "$_qa_umd_reboot" >&6
        done #}
    fi #}

    return 0
}

################################################################################
### Args:    $1 patch_name
###          $2 patch_version
### Returns: 0
fn_optional_selections () {
    local _patch=$1-$2
    ### if no optional component available, no need to do anything
    if ! $cmd_XPATHPARSE $g_INFODIR/$1-$2.$g_arch.umd \
                   "//COMPONENT/text()" >&$g_NULL
    then #{
        return $RET_NOCOMPONENTS
    fi #}
    shift;shift
    local _optional_select="$*"

    local _rpm=
    $cmd_RM -f $g_INFODIR/${_patch}.$g_arch.umd.opts.tmp > /dev/null 2>&1
    $cmd_TOUCH $g_INFODIR/${_patch}.$g_arch.umd.opts.tmp > /dev/null 2>&1
    for _rpm in $_optional_select; do
        echo "$_rpm" >> $g_INFODIR/${_patch}.$g_arch.umd.opts.tmp
    done

    $cmd_RM -f $g_INFODIR/${_patch}.$g_arch.umd.opts.tmp.tmp
    $cmd_TOUCH $g_INFODIR/${_patch}.$g_arch.umd.opts.tmp.tmp

    local _savIFS=$IFS
    IFS=$'\n'
    for _rpm in `cat $g_INFODIR/${_patch}.$g_arch.umd.opts`; do
        if ! $cmd_GREP -q "$_rpm" $g_INFODIR/${_patch}.$g_arch.umd.opts.tmp; then
            echo "$_rpm" >> $g_INFODIR/${_patch}.$g_arch.umd.opts.tmp.tmp
        fi
    done

    IFS="$_savIFS"
    $cmd_CP -f $g_INFODIR/${_patch}.$g_arch.umd.opts.tmp.tmp $g_INFODIR/${_patch}.$g_arch.umd.opts > /dev/null 2>&1
    $cmd_RM -f $g_INFODIR/${_patch}.$g_arch.umd.opts.tmp.tmp > /dev/null 2>&1

    $cmd_RM -f $g_INFODIR/${_patch}.$g_arch.umd.rpms.tmp > /dev/null 2>&1
    $cmd_TOUCH $g_INFODIR/${_patch}.$g_arch.umd.rpms.tmp > /dev/null 2>&1
    local _savIFS=$IFS
    IFS=$'\n'
    for _rpm in `cat $g_INFODIR/${_patch}.$g_arch.umd.rpms`; do
        _rpm=`echo "$_rpm" | $cmd_SED -e "s/\.$g_arch\.rpm$//"`
        if ! $cmd_GREP -q "$_rpm" $g_INFODIR/${_patch}.$g_arch.umd.opts; then
            echo "$_rpm.$g_arch.rpm" >> $g_INFODIR/${_patch}.$g_arch.umd.rpms.tmp
        fi
    done

    IFS="$_savIFS"
    cp -f $g_INFODIR/${_patch}.$g_arch.umd.rpms.tmp $g_INFODIR/${_patch}.$g_arch.umd.rpms > /dev/null 2>&1
    $cmd_RM -f $g_INFODIR/${_patch}.$g_arch.umd.rpms.tmp > /dev/null 2>&1
    return 0

}

################################################################################
### Purpose: Log status message to file $g_ACTIVESTATUS
### Args:    $1 calling $LINENO
###          $2 status message
### Returns: 0
fn_write_status()
{
    fn_chkargs $FUNCNAME $LINENO $# 2 2 "LINENO, message"

    fn_lockfile $LINENO $g_ACTIVESTATUS
    fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "<$1 writing status \"$2\""
    echo $2 >$g_ACTIVESTATUS
    fn_unlockfile $LINENO $g_ACTIVESTATUS

    return 0
}

################################################################################
### Args:    $1 calling $LINENO
### Returns: 0
fn_read_status()
{
    fn_chkargs $FUNCNAME $LINENO $# 1 1 "LINENO"

    local _rs_msg=
    local _rs_current_status=
    local _rs_current_msg=

    if [[ -s "$g_ACTIVESTATUS" ]]
    then #{
        fn_lockfile $LINENO $g_ACTIVESTATUS
        _rs_msg=$($cmd_CAT $g_ACTIVESTATUS)
        fn_unlockfile $LINENO $g_ACTIVESTATUS
        _rs_current_status=$(echo $_rs_msg \
            | $cmd_SED -e 's/^ *\([^ ][^ ]*\)  *.*$/\1/')
        _rs_current_msg=$(echo $_rs_msg | $cmd_SED -e 's/^ *[^ ][^ ]*  *//')
        [[ ! $_rs_current_msg ]] && _rs_current_msg="Unknown Failure"
    else #}{
        _rs_current_status="Failed"
        _rs_current_msg="Unknown Failure"
    fi #}

    ### Embedded function. $1 is 0, 1 or -1 where 0 indicates a busy state,
    ### -1 indicates a failure state, and 1 indicates a success end state.
    subfn_read_status()
    {
        ### TODO: add arg checking
        fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "Status read: \"$1 $2\""
        echo -e "$1\t$2" >&6
    }

    ### Embedded function.
    subfn_read_status_clean()
    {
        ### TODO: add arg checking
        subfn_read_status "$1" "$2"
        $cmd_RM -f  $g_ACTIVEPATCH \
                    $g_RUNNINGPKG \
                    $g_INFODIR/*.status \
                    &>$g_NULL
    }

    ### The most common matches are kept near the top for performance reasons.
    ### TODO more testing needs to be done to streamline the list of most
    ### common values.
    case $_rs_current_status in #{

        "Working")
            subfn_read_status 0 "Checking for Software Updates" ;;

        "Building")
            subfn_read_status 0 "Validating Software Updates" ;;

        "Building_End")
            subfn_read_status 1 "Done Comparing $_rs_current_msg" ;;

          "Connection_Failed"           \
        | "Host_Unreachable"            \
        | "File_Not_Found"              \
        | "Directory_Not_Found"         \
        | "Connection_Refused"          \
        | "Authorization_Failed"        \
        | "Login_Incorrect"             \
        | "No_Files"                    \
	| "Invalid_Parameters"          \
        | "DB_Error"                    \
        | "Failed_Key")
            subfn_read_status -1 "$_rs_current_msg" ;;

        "Host_Not_Found")
            subfn_read_status -1 \
                "Cannot contact remote host. Please verify address." ;;
        "Failed_Decrypt")
            subfn_read_status -1 "Decryption Mechanism Failure" ;;
        "Download_Start")
            subfn_read_status 0 "Downloading update content" ;;
        "Download_End")
            subfn_read_status 0 "Finished downloading" ;;
        "Apply_Start")
            subfn_read_status 0 "Preparing to update" ;;
        "Verifying_Signatures")
            subfn_read_status 0 "Doing Checksums on updates content" ;;
        "Restarting")
            subfn_read_status 0 "Initializing" ;;
        "Verifying")
            subfn_read_status 0 "Verifying files" ;;
        "Apply_Reboot")
            subfn_read_status_clean 2 "Success...Rebooting" ;;
        "Apply_Success")
            $cmd_RM -f $g_APPLY_SUCCESS_FLAG
            subfn_read_status_clean 1 "Applied" ;;
        "Download_Failed")
            subfn_read_status_clean -1 "Download failed" ;;
        "Apply_Failed")
            subfn_read_status_clean -1 "Apply failed" ;;
        "Failed")
            subfn_read_status_clean -1 "Failed activity" ;;
        "Failed_Sigs")
            subfn_read_status_clean -1 "Invalid or corrupt patch. Please try retrieving the patch again." ;;

        "Failed_TZ") #{
            subfn_read_status -1 "$_rs_current_msg"
            ;; #}

        "Removing")
            subfn_read_status 0 "Removing" ;;
        "Remove_Success")
            subfn_read_status_clean 1 "Finished removing update" ;;
        "Downloading") #{
            local -i _rs_percent_complete=
            if [[ -e $g_INFODIR/startsize && -e $g_INFODIR/totalsize ]]
            then #{
                local _rs_start_size=
                local _rs_total_size=
                read _rs_start_size <$g_INFODIR/startsize
                read _rs_total_size <$g_INFODIR/totalsize
                local -r _rs_info_size=$($cmd_DU -mSs $g_INFODIR | $cmd_CUT -f1)
                ### TODO need to find out what downloading.log is used for. We
                ### may be able to eliminate this echo call and the one just
                ### following this conditional block. And yes, the unmatched
                ### close bracket is how it's written in the original script
                ### from which this one was derived.
                echo $($cmd_DATE) "$_rs_info_size-$_rs_start_size)*100/$_rs_total_size" >$g_INFODIR/downloading.log
                _rs_percent_complete=$(((_rs_info_size - _rs_start_size) * 100 / _rs_total_size))
            fi #}
            fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "printing to stdout: \"0   Downloading...$_rs_percent_complete%\""
            echo "0    Downloading...$_rs_percent_complete%" \
                >$g_INFODIR/downloading.log
            echo -e "0\tDownloading...$_rs_percent_complete%" >&6
            ;; #}

        "Applying") #{
            ### TODO figure out who writes $g_RUNNINGPKG
            local _rs_package=
            [[ -e "$g_RUNNINGPKG" ]] \
                && _rs_package=$($cmd_CAT $g_RUNNINGPKG)

            [[ $_rs_package && -e "$g_INFODIR/$_rs_package.log" ]] \
                && fn_cat $LINENO $g_LOGVERBOSE $g_INFODIR/$_rs_package.log

            local _rs_active_patch=
            if [[ -e $g_ACTIVEPATCH ]]
            then
                read _rs_active_patch <$g_ACTIVEPATCH
            fi

            local _rs_progress=
            local -r _rs_upgrade_log=$g_INFODIR/$_rs_active_patch.log
            if [[ -e $g_INFODIR/upgrading && -e $_rs_upgrade_log ]]
            then #{

                local -r -i _rs_num_complete=$($cmd_CAT $_rs_upgrade_log | $cmd_GREP adding 2>$g_NULL | $cmd_GREP Name 2>$g_NULL | $cmd_WC -l)

                if [[ $_rs_num_complete == 0 ]]
                then #{
                    fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "printing to stdout: \"0 Preparing...\""
                    subfn_read_status 0 "Preparing..."

                    fn_log $g_LOGWARN $FUNCNAME $LINENO "Current status is $_rs_current_status, exiting with RET_OK=$RET_OK"
                    return $RET_OK
                fi #}

                local -i _rs_num_total=$($cmd_CAT $g_INFODIR/$_rs_active_patch.$g_arch.umd.rpms | $cmd_WC -l)
                ((_rs_num_total++))

                _rs_progress="$_rs_num_complete\\$_rs_num_total"
            fi #}
            subfn_read_status 0 "Applying...$_rs_progress"
            ;; #}

        *) #{
            subfn_read_status_clean -1 "Failed activity"
            ;; #}

    esac #}

    return 0
}

################################################################################
### Args:    $1 calling $LINENO
###          $2 errnum to parse
### Returns: 0
fn_errors()
{
    fn_chkargs $FUNCNAME $LINENO $# 2 2 "LINENO, errnum"
    local -r -i _arg_errors_errnum=$2
    local       _errors_errmsg=
    case $_arg_errors_errnum in #{

        $RET_NOCOMPONENTS)
            _errors_errmsg="No optional components in indicated patch." ;;

        $RET_CMD_MKTEMP)
            _errors_errmsg="Failed to make temporary file." ;;

        $RET_FILES_NOLIST)
            _errors_errmsg="--files, no files found." ;;

        $RET_MAKE_TEMP_DIR)
            _errors_errmsg="Failed to make temporary directory." ;;

        $RET_USAGE)
            _errors_errmsg="No action performed, usage message displayed." ;;

        $RET_FTP)
            _errors_errmsg="Failed to connect to ftp server." ;;

        $RET_APPLY)
            _errors_errmsg="--apply Failed to apply downloaded patch" ;;

        $RET_DOWNLOAD)
            _errors_errmsg="--apply Failed to download patch" ;;

        $RET_DONLY)
            _errors_errmsg="--donly Failed to download patch" ;;

        $RET_AONLY)
            _errors_errmsg="--aonly Failed to apply patch" ;;

        $RET_RBACK)
            _errors_errmsg="--rback Failed to remove patch" ;;

        $RET_SCHED_GEN)
            _errors_errmsg="--sched Failed to schedule patch" ;;

        $RET_SCHED_DLAFTERAPPLY)
            _errors_errmsg="--sched Download time is later then apply - correct this" ;;

        $RET_SCHED_INPAST)
            _errors_errmsg="--sched Attempt to schedule in past, why? - correct this" ;;

        $RET_SCHED_TRANS2SHORT)
            _errors_errmsg="--sched Increase transaction apply time to satisfy requires" ;;

        $RET_SCHED_ALREADYSCHED)
            _errors_errmsg="--sched Attempt to schedule already scheduled item" ;;

        $RET_SCHED_INTRNLERROR)
            _errors_errmsg="--sched Internal scheduler error - report to support" ;;

        $RET_MSCHED_GEN)
            _errors_errmsg="--msched Failed to modify scheduled patch" ;;

        $RET_MSCHED_DLAFTERAPPLY)
            _errors_errmsg="--msched Download time is later then apply - correct this" ;;

        $RET_MSCHED_INPAST)
            _errors_errmsg="--msched Attempt to schedule in past, why? - correct this" ;;

        $RET_MSCHED_TRANS2SHORT)
            _errors_errmsg="--msched Increase transaction apply time to satisfy requires" ;;

        $RET_MSCHED_INTRNLERROR)
            _errors_errmsg="--msched Internal scheduler error - report to support" ;;

        $RET_MSCHED_PATCHMISMATCH)
            _errors_errmsg="--msched Passed patch name or version does not agree with read patch name or version - report to support" ;;

        $RET_HTTP)
            _errors_errmsg="--http/--https Failed to connect to http server or incorrect credentials." ;;

        $RET_SAMBA)
            _errors_errmsg="--samba Failed to connect to samba server or incorrect credentials." ;;

        $RET_USB)
            _errors_errmsg="--usb Failed to connect to usb device or incorrect path." ;;

        $RET_UNKNOWN_ARCH)
            _errors_errmsg="System architecture unknown - contact support." ;;

        $RET_NOTROOT)
            _errors_errmsg="This script must be run as root" ;;

        $RET_NOTSOURCEABLE)
            _errors_errmsg="You must not source this script, but run it directly instead" ;;

        $RET_BUILD_LIST)
            _errors_errmsg="No patches found." ;;

        $RET_EM)
            _errors_errmsg="--em No patches found in local directory.." ;;

        $RET_DATE_TZ)
            _errors_errmsg="Time zone on system must be set before performing software maintenance." ;;

        $RET_RSCHED_GEN)
            _errors_errmsg="--rsched Error removing all scheduled items." ;;

        $RET_FILES_NO_TAGVALUE)
            _errors_errmsg="--files fn_get_umd_tag_value failed." ;;

        ### If we're having problems with echo command--see comments on
        ### cmd_ECHO elsewhere--we technically wouldn't be able to
        ### report this error message. That said, it's included here
        ### for thoroughness and to satisfy the requirement that each
        ### declaration have a handler.
        $RET_RUNTIME_NOECHO)
            _errors_errmsg="$g_RUNTIMEERR_PREFIX Problems with 'echo' command" ;;

        $RET_RUNTIME_NOINDEX)
            _errors_errmsg="$g_RUNTIMEERR_PREFIX Could not generate index." ;;

        $RET_RUNTIME_FAILENCRYPT)
            _errors_errmsg="$g_RUNTIMEERR_PREFIX Error encrypting connection details." ;;

        $RET_RUNTIME_CMDNOEX)
            _errors_errmsg="$g_RUNTIMEERR_PREFIX Missing expected command or it's not executable" ;;

        $RET_RUNTIME_MAIN_PROTO_BADMETHOD)
            _errors_errmsg="$g_RUNTIMEERR_PREFIX Unhandled method" ;;

        $RET_RUNTIME_MAIN_SELECT_BADMETHOD)
            _errors_errmsg="$g_RUNTIMEERR_PREFIX --select unknown command" ;;

        $RET_RUNTIME_SED_FAILED)
            _errors_errmsg="$g_RUNTIMEERR_PREFIX $cmd_SED call failed" ;;

        $RET_RUNTIME_RPMCOMPARE_FAILED)
            _errors_errmsg="$g_RUNTIMEERR_PREFIX $cmd_RPMCOMPARE call failed" ;;

        $RET_RUNTIME_NOPACKAGES)
            _errors_errmsg="$g_RUNTIMEERR_PREFIX Patch has no packages" ;;

        $RET_SCRIPT_BADARGS)
            _errors_errmsg="$g_SCRIPTERR_PREFIX bad number of arguments" ;;

        $RET_SCRIPT_MAKE_TEMP_DIR_NON_REENTRANT)
            _errors_errmsg="$g_SCRIPTERR_PREFIX fn_make_temp_dir g_tmp_dir already set" ;;

        $RET_SCRIPT_PARSE_PROTOCOL)
            _errors_errmsg="$g_SCRIPTERR_PREFIX could not parse method used" ;;

        $RET_SCRIPT_FNLOG_BADARGS)
            _errors_errmsg="$g_SCRIPTERR_PREFIX fn_log() called with incorrect number of arguments" ;;

        $RET_SCRIPT_FNEXIT_BADARGS)
            _errors_errmsg="$g_SCRIPTERR_PREFIX fn_exit() called with incorrect number of arguments" ;;

        $RET_SCRIPT_DEBUGINVALID)
            _errors_errmsg="$g_SCRIPTERR_PREFIX gscr_DEBUG variable invalid, it must be set to an integer value between 0 and 9" ;;

        $RET_SCRIPT_CHECKUMDSIGINVALID)
            _errors_errmsg="$g_SCRIPTERR_PREFIX gscr_CHECKSIG variable invalid, it must be set to \"yes\" or \"no\"" ;;

        $RET_SCRIPT_GETUMDTAGVAL_BADARGS)
            _errors_errmsg="$g_SCRIPTERR_PREFIX fn_get_umd_tag_value, _arg_casemod must be -1, 0 or 1" ;;

        ### For each RET_* declaration except RET_OK there has to be a
        ### corresponding case in fn_errors().
        $RET_SCRIPT_DECLMISMATCH)
            _errors_errmsg="$g_SCRIPTERR_PREFIX RET declaration vs. handler mismatch" ;;

        $RET_SCRIPT_RECURSIVELOCK)
            _errors_errmsg="$g_SCRIPTERR_PREFIX nesting of calls to file lock function on the same file not permitted" ;;

    esac #}

    if [[ $_errors_errmsg ]]
    then #{
        fn_say $FUNCNAME $LINENO "$_arg_errors_errnum: $_errors_errmsg"
        return 0
    fi #}

    ### This relies on the definition of the RET_* values being in a
    ### certain format.
    echo "Supported Errors" >&6
    $cmd_SED '/^\<declare -r -i RET_.*=/!d;s/declare -r -i //' $g_PROGPATH >&6
    [[ $? != 0 ]] && fn_exit $FUNCNAME $LINENO RET_RUNTIME_SED_FAILED "$cmd_SED call failed"

    return 0
}

################################################################################
### Purpose: Generates $g_INFODIR/warnings.list
### Args:    $1 calling $LINENO
###          $2 patch_name
###          $3 patch_ver
### Returns: 0
fn_list_warnings()
{
    fn_chkargs $FUNCNAME $LINENO $# 3 3 "LINENO, patch_name, patch_ver"
    ### TODO it's unclear who uses the warnings.list file or how the .warning
    ### files get created. There is code to create .warning files, but that is
    ### in the $g_READMEDIR/ directory.
    local -r _arg_warnings_file=$g_INFODIR/$2-$3.warning
    local -r _tmp_warnings_file=$g_INFODIR/warnings.list

    if [[ ! -e $_arg_warnings_file ]]
    then #{
        echo "Minimal impact to system performance for the duration of the software update." >>$_tmp_warnings_file
    else #}{

        ### TODO: The only time the $_tmp_warnings_file gets erased is when
        ### there is a'1' in the parsed warning file. This is the behaviour
        ### in the original script.
        $cmd_GREP -q '1' $_arg_warnings_file && echo "Automatic reboot upon completion of the update." >$_tmp_warnings_file

        $cmd_GREP -q '2' $_arg_warnings_file && echo "Service interruption for the duration of the update." >>$_tmp_warnings_file

        $cmd_GREP -q '3' $_arg_warnings_file && echo "Loss of network connectivity for the duration of the update." >>$_tmp_warnings_file

        $cmd_GREP -q '4' $_arg_warnings_file && echo "Loss of modem connectivity for the duration of the update." >>$_tmp_warnings_file
    fi #}

    [[ -e $_tmp_warnings_file ]] \
        && fn_cat $LINENO $g_LOGVERBOSE $_tmp_warnings_file

    return 0
}

################################################################################
### Args:    $1 calling $LINENO
### Returns: 0 on success
###          May also exit script with value of RET_DATE_TZ
fn_validate_tz()
{
    fn_chkargs $FUNCNAME $LINENO $# 1 1 "LINENO"

    if $cmd_DATE | $cmd_GREP -i 'Local time zone must be set'
    then #{
        fn_write_status $LINENO \
            "Failed_TZ $cmd_DATE: Local time zone must be set prior to applying software updates. Please set the time zone and try again."
        fn_write_event $LINENO E -1 "Failed_TZ $cmd_DATE: Local time zone must be set prior to applying software updates. Please set the time zone and try again. <- $1 of $g_PROGNAME"
        fn_exit $FUNCNAME $LINENO RET_DATE_TZ "Failed_TZ $cmd_DATE: Local time zone must be set prior to applying software updates. Please set the time zone and try again. <- $1 of $g_PROGNAME"
    fi #}
    return 0
}

################################################################################
### Args:    None
### Returns: Does not return, forcibly exits with $RET_USAGE. Note that the
### only reason the exit value is $RET_USAGE rather than $RET_OK, even though
### there is technically no error condition is so that EM will respond in
### error if calling the script with an unhandled set of parameters.
fn_usage()
{
    ### If called with extra args, process them.
    if [[ 1 = $# ]]
    then #{

        local -r _arg_usage_parm=$1
        case "$_arg_usage_parm" in #{

            "-v") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm
    returns rpm VERSION of system-release
EOF
                ;; #}

            "--inventory") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm
    returns the "Software Inventory" and writes it to $g_INVENTORYLOG.
    The "Software Inventory" is the rpm query of all installed rpms,
    expressed as:
    - NAME
    - a tab character
    - VERSION
    - a dash ('-') character
    - RELEASE
    - a tab character
    - Operating System
    - a tab character
    - INSTALLTIME
EOF
                ;; #}

            "--status") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm
    returns the status from $g_ACTIVESTATUS
EOF
                ;; #}

            "--ftp") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm <address> <user_name>
  <user_password> <remote_path>
    Fetchs information about available patchs. Specifically, it gets the .umd
    and .uxd files from the remote system using the ftp protocol and indicated
    parameters, then builds the list of rpms, checking requirements. The list
    is sent to file $g_PATCHCACHE and stdout.
EOF
                ;; #}

            "--http" | "--https") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm <address> <user_name>
  <user_password> <remote_path> <ssl:YES/NO>
    Fetchs information about available patchs. Specifically, it gets the .umd
    and .uxd files from the remote system using the indicated parameters, using
    the https protocol if <ssl> is "YES" or the http protocol if <ssl> is "NO".
    It then builds the list of rpms, checking requirements. The list is sent
    to file $g_PATCHCACHE and stdout.
EOF
                ;; #}

            "--samba") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm <address> <user_name>
  <user_password> <remote_path>
    Fetchs information about available patchs. Specifically, it gets the .umd
    and .uxd files from the remote system using the samba protocol and indicated
    parameters, then builds the list of rpms, checking requirements. The list
    is sent to file $g_PATCHCACHE and stdout.
EOF
                ;; #}

            "--usb") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm <path>
    Fetchs information about available patchs. Specifically, it gets the .umd
    and .uxd files from the usb mounted drive, then builds the list of rpms,
    checking requirements. The list is sent to file $g_PATCHCACHE
    and stdout.
EOF
                ;; #}

            "--em") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm
    Fetchs information about available patchs. Specifically, it gets the .umd
    and .uxd files from the Local Computer, then builds the list of rpms,
    checking requirements. The list is sent to file $g_PATCHCACHE
    and stdout.
EOF
                ;; #}

            "--cache") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm
    Copies the $g_PATCHCACHE file to stdout.
EOF
                ;; #}

            "--apply") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm <patch_name> <patch_version>
    Downloads and applies the indicated patch.
$g_PROGNAME $_arg_usage_parm
    Downloads and applies the active patch.
EOF
                ;; #}

            "--donly") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm <patch_name> <patch_version>
    Downloads but does not apply the indicated patch.
EOF
                ;; #}

            "--aonly") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm <patch_name> <patch_version>
    Applies the indicated patch which would have had to have previously
    been downloaded with --donly.
EOF
                ;; #}

            "--rback") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm <patch_name> <patch_version>
    Rolls back a patch application for the given patch.
EOF
                ;; #}

            "--sched") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm
    Read the scheduled patches.
$g_PROGNAME $_arg_usage_parm <patch_name> <patch_version>
  <download_time> <apply_time>
    Schedules a patch, allowing independant setting of the download and apply
    time, or allowing scheduling of download followed by immediate apply.
    Where download_time and apply_time are expressed as follows:
    "Thu Jul 24 16:50:35 1969", specifically:
    - Three character day of week (Mon, Tue, etc.)
    - Three character month (Nov, Dec, etc.)
    - One or two characters representing the day of the month
    - The time in 24 hour format in the form HH:MM:SS
    - Four characters representing the year.
EOF
                ;; #}

            "--msched") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm <patch_name> <patch_version>
    Deletes the indicated scheduled patch.
$g_PROGNAME $_arg_usage_parm <patch_name> <patch_version>
  <download_time> <apply_time>
    Allows modification of the schedule of the indicated patch.
    Where download_time and apply_time are expressed as follows:
    "Thu Jul 24 16:50:35 1969", specifically:
    - Three character day of week (Mon, Tue, etc.)
    - Three character month (Nov, Dec, etc.)
    - One or two characters representing the day of the month
    - The time in 24 hour format in the form HH:MM:SS
    - Four characters representing the year.
EOF
                ;; #}

            "--rsched") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm
    Non selective removal of all scheduled patches.
EOF
                ;; #}

            "--warnings") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm <patch_name> <patch_version>
    Copies the warnings logs to stdout for the indicated patch.
EOF
                ;; #}

            "--hist") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm
    Copies the patch history ($g_PATCHHISTORY) to stdout.
EOF
                ;; #}

            "--errors") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm
    Dumps a list of all known warnings (exit values).
$g_PROGNAME $_arg_usage_parm <error_number>
    Looks up the indicated warning by number (exit value) and reports it as
    human readable english text.
EOF
                ;; #}

            "--setinprogress") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm
    Writes "Working" to the status file, causing the EM to reflect a busy
    state. GUI only.
EOF
                ;; #}

            "--files") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm <patch_name>
    Lists the files (XML tag <PACKAGE>) in the indicated patch.
EOF
                ;; #}

            "--hascomponents") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm <patch_name> <patch_version>
    Indicates if the patch has optional packages (XML tag <COMPONENT>) by
    returning $RET_OK if the patch has optional packages and $RET_NOCOMPONENTS
    if not.
EOF
                ;; #}

            "--components") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm <patch_name> <patch_version>
    Lists the optional packages (XML tag <COMPONENT>) in the indicated patch.
EOF
                ;; #}

            "-l") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm <patch_id>
    Outputs the Warning and Readme files for the queried patch. This is
    how the EM gets the file details.
EOF
                ;; #}

            "-d") #{
                $cmd_CAT >&7 <<EOF
$g_PROGNAME $_arg_usage_parm
    Outputs the rpm INSTALLTIME for package system-release. It's
    the complement to -v.
EOF
                ;; #}

            "--"*) #{
                $cmd_CAT >&7 <<EOF
Unable to give help for the indicated command: "$_arg_usage_parm".
EOF
                ;; #}

            *) #{
                $cmd_CAT >&7 <<EOF
Unable to give help for the indicated command: "$_arg_usage_parm".
Be sure to include the '-' or '--' in front of the command.
EOF
                ;; #}
        esac #}

        g_exitval=$RET_USAGE
        exit $g_exitval

    fi #}

    ### We send the output to file descriptor 7, which is where
    ### stderr was preserved to when I/O redirection was turned on.
    $cmd_CAT >&7 <<EOF
$g_PROGNAME
Usage: $g_PROGNAME [options] (all paths relative)
--help
--help <topic> (e.g., type $g_PROGNAME --ftp to get help on --ftp selection)
--test <patch_name> <patch_version>
--inventory
--http  <address> <user_name> <user_password> <remote_path> <ssl:YES/NO>
--https <address> <user_name> <user_password> <remote_path> <ssl:YES/NO>
--ftp   <address> <user_name> <user_password> <remote_path>
--samba <address> <user_name> <user_password> <remote_path>
--usb   <path>
--em
--cache
--apply
--apply  <patch_name> <patch_version>
--rback  <patch_name> <patch_version>
--sched
--sched  <patch_name> <patch_version> <download_time> <apply_time>
--msched <patch_name> <patch_version>
--msched <patch_name> <patch_version> <download_time> <apply_time>
--rsched
--hist
--files <patch_name>
--hascomponents <patch_name> <patch_version>
--components <patch_name> <patch_version>
--status
--setinprogress
--donly <patch_name> <patch_version>
--aonly <patch_name> <patch_version>
--warnings <patch_name> <patch_version>
--errors <error_number>
--errors
-v
-l <patch_id>
-d
EOF

    fn_log $g_LOGWARN $FUNCNAME $LINENO "Usage message displayed, script exiting with RET_USAGE=$RET_USAGE"
    g_exitval=$RET_USAGE
    exit $g_exitval
}

################################################################################
### Purpose: Checks that the script was called with the correct number of
###          arguments for the given command. For instance, let's say the
###          command --msched can be called with two arguments: <patch_name>
###          <patch_version> or four arguments: <patch_name> <patch_version>
###          <download_time> <apply_time>. To validate the command line, you
###          would call this function like so: fn_check_usage $LINENO $1 $# 2 4
### Args:    $1 calling $LINENO
###          $2 command from command line
###          $3 number of arguments on command line, including command
###          $* set of valid number of commands, offset by 1
### Returns: 0 if valid number of arguments
###          Calls fn_usage() if invalid number of arguments.
fn_check_usage()
{
    fn_chkargs $FUNCNAME $LINENO $# 4 $g_INTMAX "$LINENO, command, numargs, ...valid_num_args"
    local -r -i _arg_check_usage_calling_lineno=$1
    local -r    _arg_check_usage_command="$2"
    local    -i _arg_check_usage_numargs_passed=$3
    ((_arg_check_usage_numargs_passed--))

    shift 3
    local -i _check_usage_arg=
    for _check_usage_arg in $*
    do #{
        [[ $_arg_check_usage_numargs_passed == $_check_usage_arg ]] && return 0
    done #}

    fn_log $g_LOGALWAYS $FUNCNAME $LINENO "<$_arg_check_usage_calling_lineno Invalid number of parameters for $_arg_check_usage_command"
    fn_write_status $LINENO "Invalid_Parameters"
    fn_usage
}

################################################################################
### Purpose: Runs the pre_patch.sh if there is one.
### Args:    $1 calling $LINENO
###          $2 the name-ver-rel portion of the umd.
### Returns: 0
fn_run_pre_patch()
{
    fn_chkargs $FUNCNAME $LINENO $# 2 2 "LINENO, patch_name-ver-rel"

    local -r _arg_rpp_umd=$2

    [[ ! -e "$g_tmp_dir/$g_INFODIR/$_arg_rpp_umd/pre_patch.sh" ]] && return 0

    if [[ ! -e "$g_INFODIR/$_arg_rpp_umd.pre_patch.done" ]]
    then #{
        fn_write_event $LINENO I -1 "Found PRE script for $_arg_rpp_umd "
        if ! bash -x $g_tmp_dir/$g_INFODIR/$_arg_rpp_umd/pre_patch.sh &>$g_INFODIR/$_arg_rpp_umd.pre_patch.log
        then #{
            fn_write_event $LINENO I -1 "Found PRE script FAILED TO EXECUTE for $_arg_rpp_umd <- $LINENO of $g_PROGNAME"
        else #}{
            $cmd_TOUCH $g_INFODIR/$_arg_rpp_umd.pre_patch.done
        fi #}
    else #}{
        local _rpp_clean=$($cmd_XPATHPARSE $g_tmp_dir/$_arg_rpp_umd.$g_arch.umd "//CLEAN/text()" 2>$g_NULL | $cmd_TR '[:upper:]' '[:lower:]')
        ### TODO consider [[ $? = 0 ]] error handling, or default evaluation.
        if [[ $_rpp_clean == yes ]]
        then #{
            fn_write_event $LINENO I -1 "PRE script for $_arg_rpp_umd has already been executed <- $LINENO of $g_PROGNAME"
            if ! bash -x $g_tmp_dir/$g_INFODIR/$_arg_rpp_umd/pre_patch.sh &>$g_INFODIR/$_arg_rpp_umd.pre_patch.log
            then #{
                fn_write_event $LINENO I -1 "PRE script FAILED TO EXECUTE for $_arg_rpp_umd <- $LINENO of $g_PROGNAME"
            else #}{
                $cmd_RM -f $g_INFODIR/$_arg_rpp_umd.pre_patch.done &>$g_NULL
                $cmd_TOUCH $g_INFODIR/$_arg_rpp_umd.pre_patch.done
            fi #}
        fi #}
    fi #}

    return 0
}

################################################################################
### Purpose: Given a requirements string or a string with a lexical comparator
###          (described below), an rpm name, and a comparison release/version,
###          and a required release/version, will compare the comparison
###          release/version against the required release/version, then
###          determine if the comparison satisfies the lexical comparator.
###          e.g, if comparison release/version is greater than the required
###          release/version, then lexical comparator '>' would be satisfied,
###          while lexical comparator '=' would not.
###          The lexical comparator is contained in the string, and is one of
###          the following values:
###          Value  Meaning
###          -----  -------
###           =     Equal to.
###           <     Less than.
###           >     Greater than.
###           <=    Less than or equal to.
###           =<    Alternate form of less than or equal to.
###           >=    Greater than or equal to.
###           =>    Alternate form of greater than or equal to.
### Args:    $1 calling $LINENO
###          $2 _arg_reqsat_comparator=$2
###          $3 _arg_reqsat_name=$3
###          $4 _arg_reqsat_comp_ver=$4
###          $5 _arg_reqsat_comp_rel=$5
###          $6 _arg_reqsat_req_ver=$6
###          $7 _arg_reqsat_req_rel=$7
### Returns: 0 on satisfied requirements, 1 if not.
fn_requires_satisfied()
{
    fn_chkargs $FUNCNAME $LINENO $# 7 7 "LINENO, lexical_comparator, name, cur_ver, cur_rel, req_ver, req_rel"

    local -r _arg_reqsat_comparator=$2
    local -r _arg_reqsat_name=$3
    local -r _arg_reqsat_comp_ver=$4
    local -r _arg_reqsat_comp_rel=$5
    local -r _arg_reqsat_req_ver=$6
    local -r _arg_reqsat_req_rel=$7

    ### Compare the passed in comparison version against the passed in
    ### required version.
    $cmd_RPMCOMPARE \
        $_arg_reqsat_name-$_arg_reqsat_comp_ver-$_arg_reqsat_comp_rel \
        $_arg_reqsat_name-$_arg_reqsat_req_ver-$_arg_reqsat_req_rel \
        >&$g_NULL
    local -r -i _compreq_rpmcomp_ret=$?
    local -i    _compreq_foundstatus=0
    if [[ $_compreq_rpmcomp_ret == $g_RPMCOMPARE_RET_EQUAL ]]; then #{
        [[ $(echo "$_arg_reqsat_comparator" | $cmd_GREP "=" 2>$g_NULL) ]] \
            && return 0 ### comparator contains '=', and they match.
    elif [[ $_compreq_rpmcomp_ret == $g_RPMCOMPARE_RET_OLDER ]]; then #}{
        [[ $(echo "$_arg_reqsat_comparator" | $cmd_GREP "<" 2>$g_NULL) ]] \
            && return 0 ### comparator contains '<', and cur < req
    elif [[ $_compreq_rpmcomp_ret ==  $g_RPMCOMPARE_RET_NEWER ]];then #}{
        [[ $(echo "$_arg_reqsat_comparator" | $cmd_GREP ">" 2>$g_NULL) ]] \
            && return 0 ### comparator contains '>', and cur > req
    else #}{ [[ $_compreq_rpmcomp_ret == $g_RPMCOMPARE_RET_ERR ]]
        ### There was an error in the $cmd_RPMCOMPARE call.
        ### Best we can do is log it, and consider the comparison a match.
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "There was an error in the $cmd_RPMCOMPARE call comparing \"$_arg_reqsat_name-$_arg_reqsat_comp_ver-$_arg_reqsat_comp_rel\" to \"$_arg_reqsat_name-$_arg_reqsat_req_ver-$_arg_reqsat_req_rel\""
        return 0
    fi #}

    return 1
}

################################################################################
### Purpose: Does all the script setup
### Args:    $1 calling $LINENO
###          $* the arguments passed to the script.
### Returns: n/a
fn_setup()
{
    [[ ! -d $g_INFODIR ]] && $cmd_MKDIR -p $g_INFODIR
    [[ ! -e "$g_READMEDIR" ]] && $cmd_MKDIR -p $g_READMEDIR

    ### Lets enable I/O redirection to capture any stdout and stderr to a
    ### file. The reason we do this is because if any call in this script
    ### generates output, we can capture it. This can be very handy for
    ### debugging. We can still generate specific stdout logging with the
    ### function fn_log() below. This I/O redirection is restored to normal
    ### in the function fn_trap()
    exec 6>&1 ### Link file descriptor 6 with stdout to save stdout
    exec 7>&2 ### Link file descriptor 7 with stderr to save stderr
    exec 1>>$g_LOG   ### redirect stdout and stderr to logfile.
    exec 2>>$g_LOG   ### redirect stdout and stderr to logfile.

    ### Check the gscr_DEBUG variable to be sure it is set correctly.
    if [[ ! $gscr_DEBUG || ${gscr_DEBUG/[0-9]/} ]]
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$g_SCRIPTERR_PREFIX gscr_DEBUG variable invalid, it must be set to an integer value between 0 and 9, returning RET_SCRIPT_DEBUGINVALID=$RET_SCRIPT_DEBUGINVALID"
        return $RET_SCRIPT_DEBUGINVALID
    fi #}

    ### We wanted to wait until we had I/O redirection on, and gscr_DEBUG
    ### checked before we called fn_log.
    fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$g_PROGNAME $g_VERSION; $($cmd_DATE) gscr_DEBUG=$gscr_DEBUG; args($#)=\"$*\""

    ### Check any other gscr_* variables to be sure they are set correctly.
    if [[ $gscr_CHECKSIG == no ]]
    then #{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "DEBUG: gscr_CHECKSIG=\"$gscr_CHECKSIG\" for debugging"
    elif [[ $gscr_CHECKSIG != yes ]]; then #}{
        fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$g_SCRIPTERR_PREFIX gscr_CHECKUXMSIG variable invalid, it must be set to \"yes\" or \"no\", returning RET_SCRIPT_CHECKUMDSIGINVALID=$RET_SCRIPT_CHECKUMDSIGINVALID"
        return $RET_SCRIPT_CHECKUMDSIGINVALID
    fi #}

    ### This script must be run as root.
    [[ $UID != 0 ]] && fn_exit $FUNCNAME $LINENO RET_NOTROOT "You must run this script as root"

    ### This script should be made executable and run directly rather than
    ### sourced from the shell (i.e., it should be run using the command line:
    ###   ./scriptname
    ### rather than:
    ###   . ./scriptname
    ### or:
    ###   bash ./scriptname
    ### Sourcing the script from the shell breaks the behaviour of the exit
    ### command so we will now check to be sure the script was run directly.
    [[ ${-/i/} != $- ]] && fn_exit $FUNCNAME $LINENO RET_NOTSOURCEABLE "You must not source this script, but run it directly instead"

    ### Determine the system architecture
    g_arch=$($cmd_UNAME -m)
    case "$g_arch" in #{

        "i386") #{
            g_usbdev="/dev/sda1"
            ;; #}

        "ppc") #{
            g_usbdev="/dev/sdb1"
            ;; #}

        "i686") #{
            g_usbdev="/dev/sda1"
            g_arch=i386 ### redefine i686 as i386
            ;; #}

        *) #{
            ### TODO consider adding:
            ### echo -e "-1\tSystem Failure: Unknown Platform" >$g_ACTIVESTATUS
            ### here, and similar code anywhere else there's a fatal error.
            fn_exit $FUNCNAME $LINENO RET_UNKNOWN_ARCH "Unknown system architecture"
            ;; #}

    esac #}

    ### For each RET_* declaration except RET_OK there has to be a
    ### corresponding case in fn_errors(). Let's ensure that.
    if [[ $gscr_ENABLE_GLOBAL_DEBUG -eq 1 ]]
    then
        local -i _setup_errors_parsed=0
        _setup_errors_parsed=$(egrep -c '^[ ]+\$RET_[0-9A-Z_]*\)' $g_PROGPATH 2>$g_NULL)
        ((_setup_errors_parsed++)) ### to handle RET_OK
        local -i _setup_errors_declared=0
        _setup_errors_declared=$(egrep -c '^\<declare[ ]+-[ir][ ]+-[ir][ ]+RET_[0-9A-Z_]*=[0-9]+' $g_PROGPATH 2>$g_NULL)
        [[ $_setup_errors_declared != $_setup_errors_parsed ]] && fn_exit $FUNCNAME $LINENO RET_SCRIPT_DECLMISMATCH "RET_ declaration vs. handler mismatch"
    fi

    ### Adjust any return values.
    local _setup_retval=
    for _setup_retval in        \
        g_RPMCOMPARE_RET_OLDER  \
        g_RPMCOMPARE_RET_EQUAL  \
        g_RPMCOMPARE_RET_NEWER  \
        g_RPMCOMPARE_RET_ERR
    do #{
        fn_massage_ret $LINENO $_setup_retval
        eval "${_setup_retval}=$?"
    done #}

    fn_mkdir_perms $LINENO $g_PATCHTMPDIR 0755
    fn_mkdir_perms $LINENO $g_INFODIR 0755

    ### The user and group permissions for http daemon.
    local -r _setup_HTTPD_USER=www
    local -r _setup_HTTPD_GROUP=www

    $cmd_CHOWN $_setup_HTTPD_USER:$_setup_HTTPD_GROUP $g_PATCHTMPDIR &>$g_NULL \
        || fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$cmd_CHOWN $_setup_HTTPD_USER:$_setup_HTTPD_GROUP $g_PATCHTMPDIR returned error"
}


### SECTION: MAIN #############################################################{

### So that the main loop can use local variables, we encompass the entire
### main block of code in fn_main().
fn_main()
{
    [[ 0 != $# ]] \
        && local -r _arg_main_first_arg=$1 \
        || local -r _arg_main_first_arg=

    ### See the full explanation for each case in fn_usage.
    case "$_arg_main_first_arg" in #{

        ### Usage: -v
        ### Returns: system release version
        "-v") #{
            fn_check_usage $LINENO $_arg_main_first_arg $# 0
            ### _main_query_version stores release
            local -r _main_query_version=$($cmd_RPM -q system-release --queryformat "%{VERSION} \n")
            [[ $_main_query_version ]] \
                && fn_say $FUNCNAME $LINENO "$_main_query_version"
            fn_log $g_LOGWARN $FUNCNAME $LINENO "$_arg_main_first_arg: returning RET_OK=$RET_OK"
            return $RET_OK
            ;; #}

        ### If you call this script with no parameters, this is the case
        ### that's run. It returns the "software inventory"
        ""|"--inventory") #{
            ### We need to send the output to file descriptor 6, which is where
            ### stdout was preserved to when I/O redirection was turned on as
            ### well as sending it to $g_INVENTORYLOG
            fn_lockfile $LINENO $g_INVENTORYLOG
            $cmd_RPM -qa --queryformat '%{NAME}\t%{VERSION}-%{RELEASE}\tOperating System\t%{INSTALLTIME:date}\n' | $cmd_TEE -a $g_INVENTORYLOG >&6
            fn_unlockfile $LINENO $g_INVENTORYLOG
            fn_log $g_LOGWARN $FUNCNAME $LINENO "no arguments, returning RET_OK=$RET_OK"
            return $RET_OK
            ;; #}

        ### Usage: --status
        "--status") #{
            fn_check_usage $LINENO $_arg_main_first_arg $# 0
            ### Although inline-ing fn_read_status would improve performace of
            ### calls to --status, it would make this case longer and would
            ### thereby hamper the performace of other calls.
            ### fn_read_status() reads file $g_ACTIVESTATUS
            fn_read_status $LINENO
            fn_log $g_LOGWARN $FUNCNAME $LINENO "$_arg_main_first_arg: returning RET_OK=$RET_OK"
            return $RET_OK
            ;; #}

        ### Let's handle the protocols, namely 'ftp', 'http', 'https', 'samba',
        ### 'usb' and 'em'. If you add to this list of protocols, be sure to
        ### also handle in the case $_arg_main_protocol handler or script will
        ### exit with $RET_RUNTIME_MAIN_PROTO_BADMETHOD.
        ### Usage:
        ###   --ftp   <address> <user_name> <user_password> <remote_path>
        ###   --http  <address> <user_name> <user_password> <remote_path>
        ###           <ssl:YES/NO>
        ###   --https <address> <user_name> <user_password> <remote_path>
        ###           <ssl:YES/NO>
        ###   --samba <address> <user_name> <user_password> <remote_path>
        ###   --usb   <path>
        ###   --em
        "--ftp" | "--http" | "--https" | "--samba" | "--usb" | "--em") #{

            ### $g_PATCHCACHE file is created in fn_build_list() which we
            ### will call shortly. Lets lock $g_PATCHCACHE against concurrent
            ### access now and remove it if it already exists. This will
            ### ensure --cache functions as expected. If for some reason the
            ### code exits before we unlock $g_PATCHCACHE, it will be unlocked
            ### automatically by fn_trap().

            fn_lockfile $LINENO $g_PATCHCACHE
            $cmd_RM -f $g_PATCHCACHE &>$g_NULL

            local -r _arg_main_protocol=$(echo $1 | $cmd_SED -e 's/^--//')
            if [[ ! $_arg_main_protocol ]]
            then #{
                fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$g_SCRIPTERR_PREFIX --ftp|http|https|samba|usb|em chosen, but cannot parse protocol, returning RET_SCRIPT_PARSE_PROTOCOL=$RET_SCRIPT_PARSE_PROTOCOL"
                return $RET_SCRIPT_PARSE_PROTOCOL
            fi #}

            fn_make_temp_dir $LINENO

            fn_write_event $LINENO I -1 "Start Scanning $_arg_main_protocol"

            fn_validate_tz $LINENO

            ### $_main_patch_protocol is set to $_arg_main_protocol, but in the
            ### case of http or https, it may be reset as documented below.
            local _main_patch_protocol=$_arg_main_protocol
            local _main_url=
            case "$_arg_main_protocol" in #{

            "ftp") #{
                fn_check_usage $LINENO $_arg_main_first_arg $# 4
                shift ### skip the method name

                ### In the call to fn_scan_ftp_location() below, the
                ### numbered arguments are: ftp_ip_address, user_name,
                ### user_password and remote_path
                if ! fn_scan_ftp_location $LINENO _main_url $1 $2 $3 $4
                then #{
                    fn_log $g_LOGALWAYS $FUNCNAME $LINENO "--$_arg_main_protocol: fn_scan_ftp_location \"$1\" \"$2\" \"$3\" \"$4\" failed, returning RET_FTP=$RET_FTP"
                    return $RET_FTP
                fi #}
                ;; #}

            "http" | "https") #{
                fn_check_usage $LINENO $_arg_main_first_arg $# 5
                shift ### skip the method name

                ### In the call to fn_scan_http_location() below, the
                ### numbered args are: ipaddrr, user, password, remotepath,
                ### and ssl (TRUE or FALSE.) _main_patch_protocol is passed
                ### as a callback and gets re-set to http or https depending
                ### on the setting of ssl.
                if ! fn_scan_http_location $LINENO \
                        _main_url _main_patch_protocol $1 $2 $3 $4 $5
                then #{
                    fn_log $g_LOGALWAYS $FUNCNAME $LINENO "--$_arg_main_protocol: fn_scan_http_location \"$1\" \"$2\" \"$3\" \"$4\" \"$5\" failed, returning RET_HTTP=$RET_HTTP"
                    return $RET_HTTP
                fi #}
                ;; #}

            "samba") #{
                #fn_check_usage $LINENO $_arg_main_first_arg $# 4
                shift ### skip the method name
                local _smb_sub_dir="."
                if [ $# != 4 ]; then 
                    echo -e "$_smb_sub_dir" >$g_INFODIR/smb_subfolder
                else
                    _smb_sub_dir=$(echo "$4" | $cmd_SED 's#\\#/#g')
                    echo -e "$_smb_sub_dir" >$g_INFODIR/smb_subfolder
                fi 
                ### Script introduced to correct the slash ( Ipaddress/Resource )
                local _smb_net_addr=$(echo "$1" | $cmd_SED 's#\\#/#g')
                ### In the call to fn_scan_samba_location() below, the
                ### numbered args are: ipaddr, user, password and rpath.
                if ! fn_scan_samba_location $LINENO _main_url "$_smb_net_addr" $2 $3 $_smb_sub_dir
                then #{
                    fn_log $g_LOGALWAYS $FUNCNAME $LINENO "--$_arg_main_protocol: fn_scan_samba_location \"$_smb_net_addr\" \"$2\" \"$3\" \"$_smb_sub_dir\" failed, returning RET_SAMBA=$RET_SAMBA"
                    return $RET_SAMBA
                fi #} 
                ;; #}

            "usb") #{
                fn_check_usage $LINENO $_arg_main_first_arg $# 1
                shift ### skip the method name

                ### In the call to fn_scan_usb_location() below, $1 is
                ### rpath (usbpath)
                if ! fn_scan_usb_location $LINENO _main_url $1
                then #{
                    fn_log $g_LOGALWAYS $FUNCNAME $LINENO "--$_arg_main_protocol: fn_scan_usb_location $1 failed, returning RET_USB=$RET_USB"
                    return $RET_USB
                fi #}
                ;; #}

            "em") #{
                fn_check_usage $LINENO $_arg_main_first_arg $# 0
                shift ### skip the method name

                if ! fn_scan_EM_location $LINENO _main_url
                then #{
                    fn_log $g_LOGALWAYS $FUNCNAME $LINENO "--$_arg_main_protocol: fn_scan_EM_location failed, returning RET_EM=$RET_EM"
                    return $RET_EM
                fi #}
                [[ ! -d $_main_url ]] && $cmd_MKDIR -p $_main_url &>$g_NULL
                ;; #}

            *) #{
                fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$g_RUNTIMEERR_PREFIX method $_arg_main_protocol not handled, returning RET_RUNTIME_MAIN_PROTO_BADMETHOD=$RET_RUNTIME_MAIN_PROTO_BADMETHOD"
                return $RET_RUNTIME_MAIN_PROTO_BADMETHOD
                ;; #}

            esac #}

            fn_write_event $LINENO I -1 "Done Scanning $_arg_main_protocol "

            fn_write_event $LINENO I -1 "Start Building from $_arg_main_protocol <- $LINENO of $g_PROGNAME"

            ### Some of the fn_scan_ functions can generate a value for
            ### $_main_url that has whitespace in it, so we quote $_main_url
            ### wherever we use it below.
            local _smb_sub_dir=.
            if [[ -e "$g_INFODIR/smb_subfolder" ]]  
            then #{
              read _smb_sub_dir <$g_INFODIR/smb_subfolder
            fi #}
            local _main_build_list_err=
            if ! fn_build_list $LINENO "$_main_url" $_main_patch_protocol \
                    _main_build_list_err $_smb_sub_dir
            then #{
                fn_write_status $LINENO "$_main_build_list_err"
                fn_write_event $LINENO I -1 "$_main_build_list_err <- $LINENO of $g_PROGNAME"
                fn_log $g_LOGALWAYS $FUNCNAME $LINENO "--$_arg_main_protocol: fn_build_list \"$_main_url\" $_main_patch_protocol failed, error message \"$_main_build_list_err\", returning RET_BUILD_LIST=$RET_BUILD_LIST"
                return $RET_BUILD_LIST
            fi #}
            fn_write_status $LINENO "Building_End"
            fn_write_event $LINENO I -1 "Done Building from $_arg_main_protocol <- $LINENO of $g_PROGNAME"

            $cmd_RM -f $g_PATCHTMPDIR/* &>$g_NULL
            fn_log $g_LOGWARN $FUNCNAME $LINENO "--$_arg_main_protocol: returning RET_OK=$RET_OK"
            return $RET_OK
            ;; #}

        ### Usage: --cache
        "--cache") #{
            fn_check_usage $LINENO $_arg_main_first_arg $# 0
            ### There should not be an error if file $g_PATCHCACHE
            ### doesn't exist.
            fn_lockfile $LINENO $g_PATCHCACHE
            [[ -e $g_PATCHCACHE ]] && fn_cat $LINENO $g_LOGVERBOSE $g_PATCHCACHE
            fn_unlockfile $LINENO $g_PATCHCACHE
            fn_log $g_LOGWARN $FUNCNAME $LINENO "$_arg_main_first_arg: returning RET_OK=$RET_OK"
            return $RET_OK
            ;; #}

        ### Usage:
        ###   --apply <patch_name> <patch_version>
        ###   --apply
        ### TODO: Could be streamlined to call --donly then --aonly, but first
        ### need to understand why --aonly slightly different for --apply.
        "--apply") #{
            shift ### skip the $_arg_main_first_arg
            if [[ $# -ge 2 ]]
            then #{

                fn_validate_tz $LINENO

                if  fn_optional_selections $*; then
                    fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$_arg_main_first_arg: Optional Components < $* >are selected"
                fi

                if ! fn_do_donly $LINENO $g_NOFORCE $*; then #{
                    fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$_arg_main_first_arg: fn_do_donly failed, returning RET_DOWNLOAD=$RET_DOWNLOAD"
                    return $RET_DOWNLOAD
                fi #}

                if ! fn_apply_patch $LINENO $*; then #{
                    fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$_arg_main_first_arg: fn_apply_patch failed, returning RET_AONLY=$RET_AONLY"
                    return $RET_AONLY
                fi #}

            else #}{
                ### No arguments, just query updates currently being applied
                fn_query_apply $LINENO
            fi #}

            fn_log $g_LOGWARN $FUNCNAME $LINENO "$_arg_main_first_arg: returning RET_OK=$RET_OK"
            return $RET_OK
            ;; #}

        ### Usage: --donly <patch_name> <patch_version>
        "--donly") #{
            fn_check_usage $LINENO $_arg_main_first_arg $# 2
            shift ### skip the $_arg_main_first_arg
            fn_validate_tz $LINENO

            if ! fn_do_donly $LINENO $g_NOFORCE $1 $2
            then #{
                fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$_arg_main_first_arg: fn_do_donly failed, returning RET_DONLY=$RET_DONLY"
                return $RET_DONLY
            fi #}

            fn_log $g_LOGWARN $FUNCNAME $LINENO "$_arg_main_first_arg: returning RET_OK=$RET_OK"
            return $RET_OK
            ;; #}

        ### Usage: --aonly <patch_name> <patch_version>
        "--aonly") #{
            fn_check_usage $LINENO $_arg_main_first_arg $# 2
            shift ### skip the $_arg_main_first_arg
            fn_validate_tz $LINENO

            if ! fn_apply_patch $LINENO $1 $2
            then #{
                fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$_arg_main_first_arg: fn_apply_patch failed, returning RET_AONLY=$RET_AONLY"
                return $RET_AONLY
            fi #}

            fn_log $g_LOGWARN $FUNCNAME $LINENO "$_arg_main_first_arg: returning RET_OK=$RET_OK"
            return $RET_OK
            ;; #}

        ### Usage: --rback <patch_name> <patch_version>
        "--rback") #{
            fn_check_usage $LINENO $_arg_main_first_arg $# 2
            shift ### skip -the --rback
            fn_validate_tz $LINENO
            echo $* >>$g_RBACKLOG
            if ! fn_remove_transaction $LINENO $1 $2
            then #{
                ### Need to update active status
                ### Is that a TODO?
                fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$_arg_main_first_arg: fn_remove_transaction $1 $2 failed, returning RET_RBACK=$RET_RBACK"
                return $RET_RBACK
            fi #}
            fn_log $g_LOGWARN $FUNCNAME $LINENO "$_arg_main_first_arg: returning RET_OK=$RET_OK"
            return $RET_OK
            ;; #}

        ### Usage:
        ###   --sched <patch_name> <patch_version> <download_time> <apply_time>
        ###   --sched
        ### See SECTION: "Conventions, Notes" for an explanation of the
        ### five fields that make up a download/apply time.
        "--sched") #{
            fn_check_usage $LINENO $_arg_main_first_arg $# 0 12

            ### Since we're about to operate on schedules, let's use the
            ### fn_lockfile() function to create a lock file, preventing
            ### concurrent access to schedule related code.
            fn_lockfile $LINENO $g_SCHEDULER

            shift ### skip the $_arg_main_first_arg
            if [[ $# -eq 12 ]]
            then #{
                fn_validate_tz $LINENO
                ### Call to fn_schedule_transaction takes $LINENO <patch_name>
                ### <patch_version> <download_time> <apply_time>
                fn_schedule_transaction $LINENO $*
                local -r -i _main_schedule_transaction_retval=$?
                [[ $RET_OK == $_main_schedule_transaction_retval ]] \
                    || fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Failure in fn_schedule_transaction, returning fn_schedule_transaction return value of $_main_schedule_transaction_retval"
                fn_unlockfile $LINENO $g_SCHEDULER
                return $_main_schedule_transaction_retval
            fi #}

            ### If we got to here, there were no arguments to --sched, so
            ### we just query what has been schedule so far
            fn_lockfile $LINENO $g_INFODIR/schedule.scd
            [[ -e $g_INFODIR/schedule.scd ]] \
                && fn_cat $LINENO $g_LOGVERBOSE $g_INFODIR/schedule.scd
            fn_unlockfile $LINENO $g_INFODIR/schedule.scd

            fn_unlockfile $LINENO $g_SCHEDULER
            ;; #}

        ### Usage:
        ###   --msched <patch_name> <patch_version> <download_time> <apply_time>
        ###   --msched <patch_name> <patch_version>
        ### See comment for --sched for explanation of download_time and
        ### apply_time.
        "--msched") #{
            fn_check_usage $LINENO $_arg_main_first_arg $# 2 12

            ### Since we're about to operate on schedules, let's use the
            ### fn_lockfile() function to create a lock file, preventing
            ### concurrent access to schedule related code.
            fn_lockfile $LINENO $g_SCHEDULER

            shift ### skip the $_arg_main_first_arg
            fn_validate_tz $LINENO

            ### Call to fn_modify_schedule takes $LINENO <patch_name>
            ### (represented by $1) <patch_version> (represented by $2)
            ### FALSE and optionally <download_time> <apply_time>
            ### (represented by $3 through $12.)
            [[ $# -eq 2 ]] \
                && fn_modify_schedule $LINENO $1 $2 FALSE \
                || fn_modify_schedule $LINENO $1 $2 FALSE \
                    $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12}
            local -r -i _main_modify_schedule_retval=$?
            [[ $RET_OK == $_main_modify_schedule_retval ]] \
                || fn_log $g_LOGALWAYS $FUNCNAME $LINENO "Failure in fn_modify_transaction, returning fn_modify_schedule return value of $_main_modify_schedule_retval"
            fn_unlockfile $LINENO $g_SCHEDULER
            return $_main_modify_schedule_retval
            ;; #}

        ### Usage: --rsched
        "--rsched") #{

            ### Since we're about to operate on schedules, let's use the
            ### fn_lockfile() function to create a lock file, preventing
            ### concurrent access to schedule related code.
            fn_lockfile $LINENO $g_SCHEDULER

            fn_validate_tz $LINENO
            if ! fn_remove_schedule $LINENO $2 $3
            then #{
                ### need to update $g_ACTIVESTATUS
                fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$_arg_main_first_arg: fn_remove_schedule failed, returning RET_RSCHED_GEN=$RET_RSCHED_GEN"
                fn_unlockfile $LINENO $g_SCHEDULER
                return $RET_RSCHED_GEN
            fi #}
            fn_log $g_LOGWARN $FUNCNAME $LINENO "$_arg_main_first_arg: returning RET_OK=$RET_OK"
            fn_unlockfile $LINENO $g_SCHEDULER
            return $RET_OK
            ;; #}

        ### Usage: --warnings <patch_name> <patch_version>
        "--warnings") #{
            fn_check_usage $LINENO $_arg_main_first_arg $# 2
            shift ### skip the $_arg_main_first_arg
            fn_list_warnings $LINENO $1 $2
            fn_log $g_LOGWARN $FUNCNAME $LINENO "$_arg_main_first_arg: returning RET_OK=$RET_OK"
            return $RET_OK
            ;; #}

        ### Usage: --hist
        "--hist") #{
            fn_check_usage $LINENO $_arg_main_first_arg $# 0
            fn_lockfile $LINENO $g_PATCHHISTORY
            [[ -e $g_PATCHHISTORY ]] \
                && fn_cat $LINENO $g_LOGVERBOSE $g_PATCHHISTORY
            fn_unlockfile $LINENO $g_PATCHHISTORY
            fn_log $g_LOGWARN $FUNCNAME $LINENO "$_arg_main_first_arg: returning RET_OK=$RET_OK"
            return $RET_OK
            ;; #}

        ### Usage:
        ###   --errors <error_number>
        ###   --errors
        "--errors") #{
            fn_check_usage $LINENO $_arg_main_first_arg $# 0 1
            shift ### skip the $_arg_main_first_arg
            local -i _main_errors_seekval=$RET_OK
            [[ $# != 0 ]] && _main_errors_seekval=$1
            fn_errors $LINENO $_main_errors_seekval
            fn_log $g_LOGWARN $FUNCNAME $LINENO "$_arg_main_first_arg: returning RET_OK=$RET_OK"
            return $RET_OK
            ;; #}

        ### Usage: --setinprogress
        "--setinprogress") #{
            fn_check_usage $LINENO $_arg_main_first_arg $# 0
            fn_write_status $LINENO "Working"
            fn_log $g_LOGWARN $FUNCNAME $LINENO "$_arg_main_first_arg: returning RET_OK=$RET_OK"
            return $RET_OK
            ;; #}

        ### Usage: --files <patch_name>
        "--files") #{
            fn_check_usage $LINENO $_arg_main_first_arg $# 1
            shift ### skip the $_arg_main_first_arg

            local _main_files_package=
            if ! fn_get_umd_tag_value $FUNCNAME $LINENO $g_gutv_RAW \
                "$g_INFODIR" $1.$g_arch.umd \
                "PACKAGE" _main_files_package
            then #{
                fn_log $g_LOGALWAYS $FUNCNAME $LINENO "$_arg_main_first_arg: fn_get_umd_tag_value failed, returning RET_FILES_NO_TAGVALUE=$RET_FILES_NO_TAGVALUE"
                return $RET_FILES_NO_TAGVALUE
            fi #}

            if [[ $_main_files_package ]]
            then #{
                fn_cat $LINENO $g_LOGVERBOSE $g_INFODIR/$1.$g_arch.umd.rpms ### cat the list of rpms to stdout.
                fn_log $g_LOGWARN $FUNCNAME $LINENO "$_arg_main_first_arg: found list, returning RET_OK=$RET_OK"
                return $RET_OK
            else #}{
                fn_log $g_LOGVERBOSE $FUNCNAME $LINENO "$_arg_main_first_arg: empty list, returning RET_FILES_NOLIST=$RET_FILES_NOLIST"
                return $RET_FILES_NOLIST
            fi #}
            ;; #}

        ### Usage: --hascomponents <patch_name> <patch_version>
        "--hascomponents") #{
            fn_check_usage $LINENO $_arg_main_first_arg $# 2

            ### If there are components, i.e., if there are populated
            ### COMPONENT tags in .umd file, then exit with $RET_OK
            ### else exit with $RET_NOCOMPONENTS. Note that EM tries to
            ### get components list regardless of what --hascomponents
            ### returns.
            shift ### skip the $_arg_main_first_arg
            if $cmd_XPATHPARSE $g_INFODIR/$1-$2.$g_arch.umd \
                    "//COMPONENT/text()" >&$g_NULL
            then #{
                return $RET_OK
            else #}{
                return $RET_NOCOMPONENTS
            fi #}
            ;; #}

        ### Usage: --components <patch_name> <patch_version>
        "--components") #{
            fn_check_usage $LINENO $_arg_main_first_arg $# 2
            shift ### skip the $_arg_main_first_arg

            local -r _main_outfile=$g_INFODIR/$1-$2.$g_arch.umd.opts
            $cmd_RM -f $_main_outfile &>$g_NULL

            local    _main_component=
            while read -r _main_component
            do #{
                echo "$_main_component" >>$_main_outfile
                fn_say $FUNCNAME $LINENO "$_main_component"
            done < <($cmd_XPATHPARSE $g_INFODIR/$1-$2.$g_arch.umd "//COMPONENT/text()" 2>$g_NULL) #}

            return $RET_OK
            ;; #}

        ### Usage: -l <patch_id>
        "-l") #{ $1 is patch_id
            fn_check_usage $LINENO $_arg_main_first_arg $# 1
            shift ### skip the $_arg_main_first_arg

            local _main_list_file=
            for _main_list_file in $g_READMEDIR/{Readme,Warnings}-$1.txt
            do #{
                [[ -f $_main_list_file ]] \
                    && fn_cat $LINENO $g_LOGVERBOSE $_main_list_file \
                    || fn_log $g_LOGWARN $FUNCNAME $LINENO "No \"$_main_list_file\" file present"
            done #}

            fn_log $g_LOGWARN $FUNCNAME $LINENO "$_arg_main_first_arg: returning RET_OK=$RET_OK"
            return $RET_OK
            ;; #}

        ### Usage: -d
        "-d") #{
            fn_check_usage $LINENO $_arg_main_first_arg $# 0
            ### _main_query_installtime stores build_date
            local -r _main_query_installtime=$($cmd_RPM -q system-release \
                --queryformat "%{INSTALLTIME:date} \n")
            [[ $_main_query_installtime ]] \
                && fn_say $FUNCNAME $LINENO "$_main_query_installtime"
            fn_log $g_LOGWARN $FUNCNAME $LINENO "$_arg_main_first_arg: returning RET_OK=$RET_OK"
            return $RET_OK
            ;; #}

        ### Usage: --test
        "--test") #{
            shift ### skip the $_arg_main_first_arg
            fn_optional_selections $*
            fn_log $g_LOGWARN $FUNCNAME $LINENO "$_arg_main_first_arg: returning RET_OK=$RET_OK"
            return $RET_OK
            ;; #}

        ### Usage: --help
        "--help" | *) #{
            ### We don't call fn_check_usage() here because we want to
            ### show usage for --help regardless of extra parameters.
            shift ### skip the $_arg_main_first_arg
            fn_usage $* ### exits script with value $RET_USAGE
            ;; #}

        ### TODO: --test removed from legacy. Consider re-introducing.

    esac #}
}

### Set trap to call fn_trap on exit. Trap signals:
###
###    Num  Sig      Meaning
###    ---  -------  ------------------
###    0    EXIT     On exit from shell
###    1    SIGHUP   Clean tidyup
###    2    SIGINT   Interrupt (CTRL-C)
###    3    SIGQUIT  Quit
###    6    SIGABRT  Abort
###    15   SIGTERM  Terminate
trap fn_trap SIGHUP SIGINT SIGQUIT SIGABRT SIGTERM EXIT

### Perform script setup.
fn_setup $*

### Call the main loop.
fn_main $*
declare -r -i g_main_RETVAL=$?

[[ $g_main_RETVAL != 0 ]] \
    && fn_log $g_LOGALWAYS MAIN $LINENO "$($cmd_DATE) Reached end of script, fn_main() returned non-zero: $g_main_RETVAL" \
    || fn_log $g_LOGVERBOSE MAIN $LINENO "$($cmd_DATE) Reached end of script, fn_main() returned $g_main_RETVAL"

g_exitval=$g_main_RETVAL
exit $g_exitval

### SECTION: MAIN #############################################################}

### There should be nothing after the next line.
### See Conventions, Notes for purpose of close bracket at end of this line    }
