#!/bin/bash
#==============================================================================
# Copyright and license info is available in the LICENSE file included with
# the Server Deployment Package (SDP), and also available online: # https://swarm.workshop.perforce.com/projects/perforce-software-sdp/view/main/LICENSE
#------------------------------------------------------------------------------
set -u

#==============================================================================
# Declarations and Environment

# Version ID Block. Relies on +k filetype modifier.
#------------------------------------------------------------------------------
# shellcheck disable=SC2016
declare VersionID='$Id: //p4-sdp/dev_c2s/Server/Unix/p4/common/bin/upgrade.sh#3 $ $Change: 31580 $'
declare VersionStream=${VersionID#*//}; VersionStream=${VersionStream#*/}; VersionStream=${VersionStream%%/*};
declare VersionCL=${VersionID##*: }; VersionCL=${VersionCL%% *}
declare Version=${VersionStream}.${VersionCL}
[[ "$VersionStream" == r* ]] || Version="${Version^^}"

declare ThisScript="${0##*/}"
declare ThisHost=
declare ThisUser=
declare CmdLine="$0 $*"
declare SDPInstance=UnsetSDPInstance
declare -i Debug=0
declare -i NoOp=1
declare -i ErrorCount=0
declare -i WarningCount=0
declare -i IgnorePreflightErrors=0
declare -i ManualUpgrade=0
declare -i PreflightOnly=0
declare -i Force=0
declare -i DoProtectionsCommentStyleUpgrade=0
declare -i DoP4DMajorVersionUpgrade=0
declare -i P4D2019_1_StorageUpgrades=0
declare -i P4D2019_1_Plus=0
declare -i P4D2020_2_Plus=0
declare -i SilentMode=0
declare -i RestartP4D=0
declare -i RestartBroker=0
declare -i RestartProxy=0
declare -i OnlineUpgrade=1
declare -i OverrideDowngradePrevention=0
declare PreUpgradeScript=/p4/common/site/upgrade/pre-upgrade.sh
declare PreUpgradeCmd=
declare PostUpgradeScript=/p4/common/site/upgrade/post-upgrade.sh
declare PostUpgradeCmd=
declare UpgradeJournal=
declare VOpts=
declare BinariesDir="/p4/sdp/helix_binaries"
declare HelixBinaries="p4 p4d p4broker p4p"
declare UpgradeHelixBinaries=
declare UpgradeServiceList=
declare RestartCandidates=
declare Bin=
declare BinPath=
declare NewVersionNamedBin=
declare InstanceLinkPath=
declare VersionLinkPath=
declare OldMajorVersion=
declare OldBuildCL=
declare OldVersion=
declare NewMajorVersion=
declare NewBuildCL=
declare NewVersion=
declare VersionInfo=
declare LiveMajorVersion=
declare LiveBuildCL=
declare LiveVersion=
declare VerifyCmd=
declare Log=
declare TmpFile_1=
declare TmpFile_2=

#==============================================================================
# Local Functions
function msg () { echo -e "$*"; }
function dbg () { [[ "$Debug" -eq 1 ]] && msg "DEBUG: $*"; }
function errmsg () { msg "\\nError: (line: ${BASH_LINENO[0]}) $*" >&2; ErrorCount+=1; }
function warnmsg () { msg "\\nWarning: (line: ${BASH_LINENO[0]}) $*"; WarningCount+=1; }
function bail() { errmsg "(line: ${BASH_LINENO[0]}) ${1:-Unknown Error}\\n" >&2; exit "${2:-1}"; }

#------------------------------------------------------------------------------
# Function: run ($cmd, $desc, $honorNoOp)
#
# Input:
#
# $cmd  - Command to execute, including arguments.
#
# $desc - Description of command to run. Optional; default is no description.
#
# $honorNoOp - If set to 1, command is always executed; NoOp setting is ignored.
#    Optional, default is 0.
#------------------------------------------------------------------------------
function run () { 
   declare cmd="${1:-echo}"
   declare desc="${2:-}"
   declare honorNoOp="${3:-1}"

   [[ -n "$desc" ]] && msg "$desc"
   msg "Running: $cmd"

   if [[ "$NoOp" -eq 1 && "$honorNoOp" -eq 1 ]]; then
      msg "NO_OP: Would run $cmd"
      return 0
   else
      # shellcheck disable=SC2086
      if eval $cmd; then
         return 0
      else
         return 1
      fi
   fi
}

#------------------------------------------------------------------------------
# Function: usage (required function)
#
# Input:
# $1 - style, either -h (for short form) or -man (for man-page like format).
# The default is -h.
#
# $2 - error message (optional).  Specify this if usage() is called due to
# user error, in which case the given message displayed first, followed by the
# standard usage message (short or long depending on $1).  If displaying an
# error, usually $1 should be -h so that the longer usage message doesn't
# obscure the error message.
#
# Sample Usage:
# usage
# usage -h
# usage -man
# usage -h "Incorrect command line usage."
#------------------------------------------------------------------------------
function usage
{
   declare style=${1:--h}
   declare usageErrorMessage=${2:-Unset}

   if [[ "$usageErrorMessage" != Unset ]]; then
      msg "\\n\\nUsage Error:\\n\\n$usageErrorMessage\\n\\n"
   fi

   msg "USAGE for $ThisScript version $Version:

$ThisScript <instance> [-p|-I] [-M] [-Od] [-c] [-y] [-L <log>] [-d|-D]

or

$ThisScript [-h|-man]
"
   if [[ $style == -man ]]; then
      msg "
DESCRIPTION:

    This script upgrades the following Helix Core software:

    * p4d, the Perforce Helix Core server
    * p4broker, the Helix Broker server
    * p4p, the Helix Proxy server
    * p4, the command line client

    The preferred process for using this script is to start with the services
    to be upgraded (p4d, p4broker, and/or p4p ) up and running at the
    start of processing. The p4d service must be online if it is to be
    upgraded.

    Details of each upgrade are described below. Prior to executing any upgrades, a
    preflight check is done to help ensure upgrades will go smoothly.  Also, checks
    are done to determine what (if any) of the above software products need to be
    updated.

    To prepare for an upgrade, new binaries must be update in the $BinariesDir
    directory.  This is generally done using the get_helix_binaries.sh script in
    that directory.  Binaries in this directory are not referenced by live running
    servers, and so it is safe to upgrade files in this directory to stage for a
    future upgrade at any time. Also, the SDP standard PATH does not include this
    directory, as verified by the verify_sdp.sh script.

THE INSTANCE BIN DIR

    The 'instance bin' directory, /p4/<instance>/bin, (e.g. /p4/1/bin for instance
    1), is expected to contain *_init scripts for services that operate on the
    current machine.

    For example, a typical commit server machine for instance 1 might have the
    following in /p4/1/bin:

    * p4broker_1_init script
    * p4broker_1 symlink
    * p4d_1_init script
    * p4d_1 symlink or script
    * p4_1 symlink (a reference to the 'p4' command line client)

    A server machine for instance 1 that runs only the proxy server would have the
    following in /p4/1/bin:

    * p4p_1_init script
    * p4p_1 symlink
    * p4_1 symlink

    The instance bin directory is never modified by the 'upgrade.sh' script.
    The addition of new binaries and update of symlinks occur in $P4CBIN.

    The existence of *_init scripts for any given binary determines whether this
    script attempts to manage the service on a given machine, stopping it before
    upgrades, restarting it afterward, and other processing in the case of p4d.

    Note that Phase 2, adding new binaries and updating symlinks, will occur for
    all binaries for which new staged versions are available, regardless of
    whether they are operational on the given machine.

THE COMMON DIR

    This script performs it operations in the SDP common bin dir, $P4CBIN.

    Unlike the instance bin directory, the $P4CBIN directory is expected
    to be identical across all machines in a topology.  Scripts and symlinks
    should always be the same, with only temporary differences while global
    topology upgrades are in progress.

    Thus, all binaries available to be upgraded will be upgraded in Phase 2, even
    if the binary does not operate on the current machine. For example, if a new
    version of 'p4p' binary is available, a new version will be copied to
    $P4CBIN and symlink references updated there. However, the p4p binary will
    not be stopped/started.

GENERAL UPGRADE PROCESS

    This script determines what binaries need to be upgraded, based on what new
    binaries are available in the $BinariesDir directory compared to what binaries
    the current instance uses.

    There are 5 potential phases. Which phases execute depend on the set of binaries
    being upgraded.  The phases are:

    * PHASE 1 - Establish a clean rollback point.
    This phase executes on the master if p4d is upgraded.

    * PHASE 2 - Install new binaries and update SDP symlinks in $P4CBIN.
    This phase executes for all upgrades.

    * PHASE 3 - Stop services to be upgraded.
    This phase executes for all upgrades involving p4d, p4p, p4broker.
    Only a 'p4' client only upgrade skips this phase.

    * PHASE 4 - Perforce p4d schema upgrades
    This step involves the 'p4d -xu' processing. It executes if p4d is upgraded
    to a new major version, and occurs on the master as well as all replicas/edge
    servers. The behavior of 'p4d -xu' differs depending on whether the server is
    the master or a replica.

    This phase is skipped if upgrading to a patch of the same major version, as
    patches do not require 'p4d -xu' processing.

    * PHASE 5 - Start upgraded services.
    This phase executes for all upgrades involving p4d, p4p, p4broker.
    Only a 'p4' client only upgrade skips this phase.

SPECIAL CASE - TO OR THRU P4D 2019.1

    If you are upgrading from a version that is older than 2019.1, services
    are NOT restarted after the upgrade in Phase 5, except on the master.
    Services must be restarted manually on all other servers.

    For these 'to-or-thru' 2019.1 upgrades, after ensuring all replicas/edges
    are caught up (per 'p4 pull -lj'), shutdown all servers other than the
    master.

    Proceeding outer-to-inner, execute this script like so on all machines
    except the master:

    1. Deploy new executables in $BinariesDir
    2. Stop p4d.
    3. Run 'verify_sdp.sh -skip cron,version'; fix problems if needed until it reports clean.
    4. Run 'upgrade.sh -M' to update symlinks.
    5. Do the upgrade manually with:  p4d -xu
    6. Leave the server offline.

    On the master, execute like this:

    1. Deploy new executables in $BinariesDir
    2. Run 'verify_sdp.sh -skip cron,version'; fix problems if needed until it reports clean.
    3. upgrade.sh

    When the script completes (it will wait for 'p4 storage' upgrades),
    restart services manually after the upgrade in the 'inner-to-outer'
    direction.  Restart services on replicas/edges going inner-to-outer

    This procedure requiring extra steps is specific to 'to-or-thru' P4D 2019.1
    upgrades.  For upgrades starting from P4D 2019.1 or later, things are simpler.

UPGRADES FOR P4D 2019.1+

    For upgrades where the P4D start version is 2019.1 and going to any subsequent
    version, run this script going outer-to-inner. On each machine, it leaves the
    services online and running.  Going in the outer-to-inner direction an all
    servers, do:

    1. Deploy new executables in $BinariesDir
    2. Run 'verify_sdp.sh -skip cron,version'; fix problems if needed until it reports clean.
    3. upgrade.sh

UPGRADE PREPARATION

   The steps for deploying new binaries to server machines and running verify_sdp.sh
   (and potentially correcting any issues it discovers) can and should be done before
   the time or even day of any planned upgrade.

UPGRADING HELIX CORE - P4D

    The p4d process, the Perforce Helix Core Server, is the center of the Perforce
    Helix universe, and the only server with a significant database component.
    Most of the upgrade phases above are about performing the p4d upgrade.

    This 'upgrade.sh' script requires that the 'p4d' service be running at the
    beginning of processing if p4d is to be upgraded, and will abort if p4d is
    not running.

ORDER OF UPGRADES

    Any given Perforce Helix installation will have least one p4d master server, and
    may have several other p4d servers deployed on different machines as replicas and
    edge servers.  When upgrading multiple p4d servers for any given instance (i.e.
    any given data set, with a unique set of changelist numbers and users), the order
    in which upgrades are performed matters.  Upgrades must be done in \"outer to
    inner\" order.

    The master server, at the center of the topology, is the innermost server and
    must be upgraded last. Any replicas or edge servers connected directly to the
    master constitute the next outer circle.  These can be upgraded in any order
    relative to each other, but must be done before the master and after any
    replicas farther out from the master in the topology.  So this 'upgrade.sh'
    script should be run first on the server machines that are \"outermost\" from
    the master from a replication perspective, and moving inward. The last run is
    done on the master server machine.

    Server machines running only proxies and brokers do not have a strict order
    dependency for upgrades. These are commonly done in the same \"outer to inner\"
    methodology as p4d for process consistency rather than strict technical need.

    See the SDP_Guide.Unix.html for more information related to performing global
    topology upgrades.

COMMIT SERVER JOURNAL ROTATIONS

    This script helps minimize downtime for upgrades by taking advantage of the SDP
    offline checkpoint mechanism.  Rather than wait for a full checkpoint, a journal
    is rotated and replayed to the offline_db.  This typically takes very little
    time compared to a checkpoint, reducing downtime needed for the overall upgrade.
    It also prepares the offline_db in case a rollback is needed.

    When the commit server is upgraded, two rotations of the commit server's journal
    occur during processing for major upgrades, and a single journal rotation is done
    for patch upgrades.  The first journal rotation occurs before any upgrade
    processing occurs, i.e. before the new binaries are added and symlinks are
    updated. This gives a clean rollback point.  This journal is immediately replayed
    to the offline_db.

    Later, after p4d has started performs its journaled upgrade processing, a second
    journal rotation occurs in Phase 5 if a major upgrade was done. This second
    journal rotation captures all upgrade-related processing in a separately numbered
    journal.  This second journal is not applied to the offline_db by this script.
    Instead, the replay of the second journal to the offline_db will occur the next
    time a call is made to the daily_checkpoint.sh or rotate_journal.sh, e.g. via
    routine crontab.  For a p4d patch upgrade, there will not be any upgrade
    processing.

    In the very unlikely event that a rollback were to ever be needed, the
    offline_db is left in a state that it could be used for a fast rollback
    on the commit server.

MULTI-SERVER OUTER-TO-INNER UPGRADES
    Before starting an outer-to-inner upgrade involving multiple p4d servers,
    (standby, edge, and other p4d replica servers), a manual journal rotation
    should be done on the commit server before starting to call upgrade.sh
    on each of the p4d servers in outer-to-inner order.  Take note of the
    journal counter used for this pre-start journal rotation.  It can be
    useful in event of a rollback.  That journal may need to be replayed
    to the offline_db on all servers other than the commit in a rollback
    scenario.

    In preparation in days or weeks before an upgrade, every p4d server in
    the topology should be checked to ensure its offline_db is healthy
    and current.

ROLLBACK
    In the very unlikely event that a rollback is needed, bear in mind the
    following:
    * There is no standard procedure for rolling back, because a procedure
    would need to take into account the reason a decision was made to
    rollback.  Presumably the decision would be driven by some kind of
    failure. A large factor in determining whether rollback is practical
    is the point in the process at which a rollback is needed.  In some
    situations, a 'Fix and Roll Forward' approach may be more pragmatic
    than a rollback, and should always be considered.
    * This script and supporting documentation will help prepare your data
    for as smooth a rollback as possible should it ever become necessary.
    * To best prepare for a rollback, it is essential to manage user
    lockout as part of your overall maintenance procedure.  Then let users
    back in after you have confirmed you are moving forward.  User lockout
    is outside the scope of this script, but can be managed using several
    possible methods such as:
      - Crafting a special Protections table to be used during maintenance,
      - Using \"Down for Maintenance\" brokers,
      - Using network and/or on-host firewall rules,
      - Using temporary ports for maintenance.
    * If Phase 2 (update of symlinks and binaries) completed and must be
    undone, than can be achieved by putting the pre-upgrade binaries in
    place in the directory /p4/sdp/helix_binaries, named simply p4, p4d,
    p4broker, and p4p.  Then run a command like this example for Instance 1:

    upgrade.sh 1 -M -I -y

    This will change symlinks back to reference the older versions.  The
    new binaries will still exist in /p4/common/bin, but will no longer
    be referenced for Instance 1.

UPGRADING HELIX BROKER

    Helix Broker (p4broker) servers are commonly deployed on the same machine as a
    Helix Core server, and can also be deployed on stand-alone machines (e.g.
    deployed to a DMZ host to provide secure access outside a corporate firewall).

    Helix Brokers configured in the SDP environment can use a default configuration
    file, and may have other configurations. The default configuration is the done
    defined in /p4/common/config/p4_N.broker.cfg (or a host-specific override file
    if it exists named /p4/common/config/p4_N.broker.<short_hostname>.cfg).  Other
    broker configurations may exist, such as a DFM (Down for Maintenance) broker
    config /p4/common/config/p4_N.broker.dfm.cfg.

    During upgrade processing, this 'upgrade.sh' script only stops and restarts the
    broker with the default configuration. Thus, if coordinating DFM brokers, first
    manually shutdown the default broker and start the DFM brokers before calling
    this script. This script will leave the DFM brokers running while adding the
    new binaries and updating the symlinks.  (Note: Depending on how services
    are configured, this DFM configuration might not survive a machine reboot.
    typically the default broker will come online after a machine reboot).

    This 'upgrade.sh' script will stop the p4broker service if it is running at the
    beginning of processing.  If it was stopped, it will be restarted after the new
    binaries are in place and symlinks are updated. If p4broker was not running at the
    start of processing, new binaries are added and symlinks updated, but the
    p4broker server will not be started.

UPGRADING HELIX PROXY

    Helix Proxy (p4p) are commonly deployed on a machine by themselves, with no p4d
    and no broker. It may also be run on the same machine as p4d.

    This 'upgrade.sh' script will stop the p4p service if it is running at the
    beginning of processing.  If it was stopped, it will be restarted after the new
    binaries are in place and symlinks are updated. If p4p was not running at the
    start of processing, new binaries are added and symlinks updated, but the p4p
    server will not be started.

UPGRADING HELIX P4 COMMAND LINE CLIENT

    The command line client, 'p4', is upgraded in Phase 2 by addition of new
    binaries and updating of symlinks.

STAGING HELIX BINARIES

    If your server can reach the Perforce FTP server over the public internet, a
    script can be used from the $BinariesDir directory to get the latest
    binaries:

    \$ cd $BinariesDir
    \$ ./get_helix_binaries.sh

    If your server cannot reach the Perforce FTP server, perhaps due to outbound
    network firewall restrictions or operating on an \"air gap\" network,
    use the '-n' option to see where Helix binaries can be acquired from:

    \$ cd $BinariesDir
    \$ ./get_helix_binaries.sh -n

OPTIONS:
 <instance>
    Specify the SDP instance name to add.  This is a reference to the Perforce
    Helix Core data set. This defaults to the current instance based on the
    \$SDP_INSTANCE shell environment variable. If the SDP shell environment is
    not loaded, this option is required.

 -p Specify '-p' to halt processing after preflight checks are complete,
    and before actual processing starts. By default, processing starts
    immediately upon successful completion of preflight checks.

 -Od
    Specify '-Od' to override the rule preventing downgrades.

    WARNING: This is an advanced option intended for use by or with the
    guidance of Perforce Support or Perforce Consulting.

 -I
    Specify '-I' to ignore preflight errors. Use of this flag is STRONGLY
    DISCOURAGED, as the preflight checks are essential to ensure a safe
    and smooth migration. If used, preflight checks are still done so
    their errors are recorded in the upgrade log, and then the migration
    will attempt to proceed.

    WARNING: This is an advanced option intended for use by or with the
    guidance of Perforce Support or Perforce Consulting.

 -M
    Specify '-M' if you plan to do a manual upgrade. With this option,
    only Phase 2 processing, adding new staged binaries and updating
    symlinks, is done by this script.

    If '-M' is used, this script does not check that services to
    be upgraded are online at the start of processing, nor does it
    attempt to start to stop services.  If '-M' is used, the
    services should be stopped manually before calling this script,
    and then started manually after.

    WARNING: This is an advanced option intended for use by or with the
    guidance of Perforce Support or Perforce Consulting.

 -c
    Specify '-c' to execute a command to upgrade the Protections table
    comment format after the p4d upgrade, by using a command like:

        p4 protect --convert-p4admin-comments -o | p4 -s protect -i

    By default, this Protections table conversion is not performed.  In some
    environments with custom policies related to update of the protections
    table, this command may not work.

    The new style of comments and the '--convert-p4admin-comments' option
    was introduced in P4D 2016.1.

 -L <log>
    Specify the path to a log file, or the special value 'off' to disable
    logging.  By default, all output (stdout and stderr) goes to this file
    in the /p4/N/logs directory (where N is the SDP instance name):

    upgrade.p4_N.<datestamp>.log

    NOTE: This script is self-logging.  That is, output displayed on the
    screen is simultaneously captured in the log file.  Redirection
    operators like '> log' and '2>&1' are not required, nor is 'tee'.

    Logging can only be disabled with '-L off' if the '-n' or '-p' flags
    are used. Disabling logging for actual upgrades is not allowed.

 -y
    Specify the '-y' option to confirm that the upgrade should be done.

    By default, this script operates in No-Op mode, meaning no actions
    that affect data or structures are taken.  Instead, commands that would
    be run are displayed.  This mode can be educational, showing various
    steps that will occur during an actual upgrade.

DEBUGGING OPTIONS:
 -d     Increase verbosity for debugging.

 -D     Set extreme debugging verbosity, using bash '-x' mode. Also implies -d.

HELP OPTIONS:
 -h	Display short help message
 -man	Display man-style help message

EXAMPLES:
    EXAMPLE 1: Preflight Only

    To see if an upgrade is needed for this instance, based on binaries
    staged in $BinariesDir, use the '-p' flag to execute only the preflight
    checks, and disable logging, as in this example:

    \$ cd /p4/common/bin
    \$ ./upgrade.sh 1 -p -L off

    EXAMPLE 2: Typical Usage

    Typical usage is with just the SDP instance name as an argument, e.g.
    instance '1', and no other parameters, as in this example:

    \$ cd /p4/common/bin
    \$ ./upgrade.sh 1

    This first runs preflight checks, and aborts if preflight checks
    detected any issues. The it gives a preview of the upgrade. A
    successful preview completes with a line near the end that looks like
    this sample:

    Success: Finished p4_1 Upgrade.

    If the preview is successful, then proceed with the real upgrade using
    the -y flag:

    \$ ./upgrade.sh 1 -y

    EXAMPLE 3: Simplified

    If the standard SDP shell environment is loaded, upgrade.sh will be in
    the path, so the 'cd' command to /p4/common/bin is not needed. Also,
    the SDP_INSTANCE shell environment variable will be defined, so the
    'instance' parameter can be dropped, with simply a call to the script
    needed.  First do a preview:

    \$ upgrade.sh

    Review the output of the preview, looking for the 'Success: Finished'
    message near the end of the output. If that exists, then execute again
    with the '-y' flag to execute the actual migration:

    \$ upgrade.sh -y

CUSTOM PRE- AND POST- UPGRADE AUTOMATION HOOKS:
    This script can execute custom pre- and post- upgrade scripts. This
    can be useful to incorporate site-specific elements of an upgrade.

    If the file /p4/common/site/upgrade/pre-upgrade.sh exists and is
    executable, it will be executed as a pre-upgrade script. If the file
    /p4/common/site/upgrade/post-upgrade.sh exists and is executable,
    it will be executed as a post-upgrade script.

    Pre- and post- upgrade scripts are called with an SDP instance
    parameter, and an optional '-y' flag to confirm actual processing is
    to be done.  Custom scripts are expected to operate in preview mode
    by default, taking no actions that affect data (just as this script
    behaves).  If this upgrade.sh script is given the '-y' flag, that
    option is passed to the custom script as well, indicating active
    processing should occur.

    Pre- and post- upgrade scripts are expected to exit with a zero exit
    code to indicate success, and non-zero to indicate failure.

    The custom pre-upgrade script is executed after standard preflight
    checks complete successfully.  If the '-I' flag is used to ignore the
    status of preflight checks, the custom pre-upgrade script is
    executed regardless of the status of preflight checks. Preflight
    checks are executed before actual upgrade processing commences. If a
    custom pre-upgrade script indicates a failure, the overall upgrade
    process aborts.

    The post-upgrade custom script is executed after the main upgrade
    is successful.

    Success or failure of pre- and post- upgrade scripts is reported in
    the log.  These scripts do not require independent logging, as all
    standard and error output is captured in the log of this upgrade.sh
    script.

    TIP: Be sure to fully test custom scripts in a test environment
    before incorporating them into an upgrade on production systems.

SEE ALSO:
    The $P4CBIN/verify_sdp.sh script is used for preflight checks.

    The $BinariesDir/get_helix_binaries.sh script acquires new binaries
    for upgrades.

    Both scripts sport the same '-h' (short help) and '-man' (full manual)
    usage options as this script.

LIMITATIONS:
    This script does not handle upgrades of 'p4dtg', Helix Swarm,
    Helix4Git, or any other software. It only handles upgrades of
    p4d, p4p, p4broker, and the p4 client binary on the SDP-managed
    server machine on which it is executed.
"
   fi

   exit 1
}

#------------------------------------------------------------------------------
# Function: terminate
# shellcheck disable=SC2317
function terminate
{
   # Disable signal trapping.
   trap - EXIT SIGINT SIGTERM

   # Ensure a non-zero exit code if the trap was triggered by anything other
   # than the 'exit 0' at the end of the Main Program.
   # shellcheck disable=SC2324
   [[ "$BASH_COMMAND" == *"exit 0"* ]] || ErrorCount+=1

   msg "\\n$ThisScript: EXITCODE: $ErrorCount\\n"
   [[ "$Log" != "off" ]] && msg "Log is: $Log"

   # With the trap removed, exit.
   exit "$ErrorCount"
}

#==============================================================================
# Command Line Processing

declare -i shiftArgs=0

set +u
while [[ $# -gt 0 ]]; do
   case $1 in
      (-c) DoProtectionsCommentStyleUpgrade=1;;
      (-p) PreflightOnly=1;;
      (-M) ManualUpgrade=1;;
      (-I) IgnorePreflightErrors=1;;
      (-Od) OverrideDowngradePrevention=1;;
      (-f) Force=1;;
      (-h) usage -h;;
      (-man) usage -man;;
      (-y) NoOp=0;;
      (-d) Debug=1;;
      (-si) SilentMode=1;;
      (-L) Log="$2"; shiftArgs=1;;
      (-D) Debug=1; set -x;; # Debug; use bash 'set -x' high verbosity debugging mode.
      (-n) usage -h "The '-n' option (preview mode) is now default behavior, so '-n' is no longer needed.\\nA new '-y' confirmation flag is required to perform an actual upgrade.  See EXAMPLES in 'upgrades.sh -man'.";;
      (-*) usage -h "Unknown option '$1' specified.";;
      (*)
         if [[ "$SDPInstance" == "UnsetSDPInstance" ]]; then
            SDPInstance="$1"
         else
            usage -h "Instance $1 specified after already being specified as $SDPInstance. Only one instance can be specified."
         fi
      ;;
   esac

   # Shift (modify $#) the appropriate number of times.
   shift; while [[ $shiftArgs -gt 0 ]]; do
      [[ $# -eq 0 ]] && usage -h "Incorrect number of arguments."
      shiftArgs=$shiftArgs-1
      shift
   done
done
set -u

# Default SDPInstance to the SDP_INSTANCE shell environment variable
# if no value was specified on the command line.
if [[ "$SDPInstance" == "UnsetSDPInstance" ]]; then
   if [[ -n "${SDP_INSTANCE:-}" ]]; then
      SDPInstance="$SDP_INSTANCE"
   else
      usage -h "No instance specified and SDP shell environment is not loaded."
   fi
fi

if [[ "$Log" == "off" ]]; then
   if [[ "$NoOp" -eq 0 && "$PreflightOnly" -eq 0 ]]; then
      usage -h "Disabling logging with '-L off' is only allowed with '-p' and/or '-n' flags."
   fi
fi

[[ "$SilentMode" -eq 1 && "$Log" == "off" ]] && \
   usage -h "Cannot use '-si' with '-L off'."

[[ "$PreflightOnly" -eq 1 && "$IgnorePreflightErrors" -eq 1 ]] && \
   usage -h "Cannot use '-p' with '-I'."

#==============================================================================
# Main Program

# Pre-Preflight checks occur before logging starts, to ensure essential utils
# (including those needed for logging) are available in the PATH.
for util in awk date id sed tee touch; do
   if ! command -v $util > /dev/null; then
      errmsg "Cannot find this essential util in PATH: $util"
   fi
done

if [[ "$ErrorCount" -ne 0 ]]; then
   bail "Aborting due to essential tools not available in directories listed in the PATH."
fi

# Load SDP controlled shell environment.
# shellcheck disable=SC1091
source /p4/common/bin/p4_vars "$SDPInstance" ||\
   errmsg "Failed to load SDP environment."

[[ -n "$Log" ]] ||\
   Log="${LOGS:-/tmp}/upgrade.p4_${SDPInstance}.$(date +'%Y%m%d-%H%M%S').log"

# Set LOGFILE to be compatible with functions like log() in backup_functions.sh.
export LOGFILE="${Log}"

if [[ "$Log" != off ]]; then
   touch "$Log" || bail "Couldn't touch log file [$Log]."
fi

trap terminate EXIT SIGINT SIGTERM

# Redirect stdout and stderr to the log file.
if [[ "$Log" != "off" ]]; then
   # Redirect stdout and stderr to a log file.
   if [[ "$SilentMode" -eq 0 ]]; then
      exec > >(tee "$Log")
      exec 2>&1
   else
      exec >"$Log"
      exec 2>&1
   fi
fi

ThisUser=$(whoami)
ThisHost=$(hostname -s)

msg "Started $ThisScript version $Version as $ThisUser@$ThisHost on $(date) as:\\n$CmdLine\\n"

[[ "$ManualUpgrade" -eq 1 ]] && warnmsg "Expert option '-M' (manual upgrade) specified."
[[ "$IgnorePreflightErrors" -eq 1 ]] && warnmsg "Expert option '-I' (ignore preflight errors)."

TmpFile_1=$(mktemp)
TmpFile_2="${TmpFile_1}.2"

# Standard Preflight checks after logging has started.

# shellcheck disable=SC1090 disable=SC1091
source "$P4CBIN/backup_functions.sh" ||\
   errmsg "Failed to load SDP backup_functions.sh lib.\\n"

set_vars

cd "$P4CBIN" || errmsg "Failed to cd to $P4CBIN."
msg "Operating in: $PWD"

# P4DInitScript is defined with set_vars() from backup_functions.sh.
# shellcheck disable=SC2154
if [[ -x "$P4DInitScript" && "$ManualUpgrade" -eq 0 ]]; then
   VerifyCmd="$P4CBIN/verify_sdp.sh $SDPInstance -skip ${VERIFY_SDP_SKIP_TEST_LIST:-},cron,version -L off -online"
else
   VerifyCmd="$P4CBIN/verify_sdp.sh $SDPInstance -skip ${VERIFY_SDP_SKIP_TEST_LIST:-},cron,version -L off"
fi

msg "Calling verify_sdp.sh as part of preflight checks."
# Call verify_sdp.sh with honorNoOp=0 so it is called even in NoOp mode.
if run "$VerifyCmd" \
   "Verifying SDP instance $SDPInstance:" 0; then
   msg "\\nVerified: verify_sdp.sh is OK."
else
   if [[ -x "$P4DInitScript" && "$ManualUpgrade" -eq 0 ]]; then
      errmsg "The verify_sdp.sh script reported preflight errors. Correct these and try again. TIP: If the only errors reported are related to the p4d service not being online, simply start the p4d service, and then try the upgrade again. The upgrade process expects the p4d service to be online at the start of processing (as it is designed to minimize downtime)."
   else
      errmsg "The verify_sdp.sh script reported preflight errors. Correct these and try again."
   fi
fi

for Bin in $HelixBinaries; do
   BinPath="$BinariesDir/$Bin"
   if [[ -e "$BinPath" ]]; then
      VOpts="-V"
      # For p4d, we must supply an existing dir with '-r' to suppress ugly
      # error messages related to P4ROOT not existing, e.g. if run on a
      # proxy-only or broker-only host.
      [[ "$Bin" == p4d ]] && VOpts="-V -r /tmp"

      if [[ -x "$BinPath" ]]; then
         if [[ "$Bin" == "p4" ]]; then
            InstanceLinkPath="${Bin}_bin"
         else
            InstanceLinkPath="${Bin}_${SDPInstance}_bin"
         fi

         if [[ -L "$InstanceLinkPath" ]]; then
            # shellcheck disable=SC2086
            OldMajorVersion=$("./$InstanceLinkPath" $VOpts | grep -i Rev. | awk -F / '{print $3}')
            # shellcheck disable=SC2086
            OldBuildCL=$("./$InstanceLinkPath" $VOpts | grep -i Rev. | awk -F / '{print $4}' | awk '{print $1}')
            OldVersion="${OldMajorVersion}.${OldBuildCL}"
            case "$Bin" in
               (p4)
                  LiveMajorVersion="$OldMajorVersion"
                  LiveBuildCL="$OldBuildCL"
                  LiveVersion="$OldVersion"
               ;;
               (p4d)
                  # shellcheck disable=SC2154
                  if [[ -x "$P4DInitScript" ]]; then
                     VersionInfo=$("$P4BIN" -p "$P4PORT" -ztag -F %serverVersion% info -s 2>/dev/null)
                     if [[ -n "$VersionInfo" ]]; then
                        # Trim off the date string, e.g. " (2020/09/08)"
                        VersionInfo=${VersionInfo%% (*}
                        LiveMajorVersion=$(echo "$VersionInfo" | awk -F / '{print $3}')
                        LiveBuildCL=$(echo "$VersionInfo" | awk -F / '{print $4}')
                        LiveVersion="${LiveMajorVersion}.${LiveBuildCL}"
                     else
                        LiveVersion="NoLiveP4D"
                     fi
                  else
                     LiveVersion="NoLiveP4D"
                  fi
               ;;
               (p4broker)
                  # shellcheck disable=SC2154
                  if [[ -x "$P4BrokerInitScript" ]]; then
                     VersionInfo=$("$P4BIN" -p "$P4BROKERPORT" -ztag -F %brokerVersion% info -s 2>/dev/null)

                     if [[ -n "$VersionInfo" ]]; then
                        # Trim off the date string, e.g. " (2020/09/08)"
                        VersionInfo=${VersionInfo%% (*}
                        LiveMajorVersion=$(echo "$VersionInfo" | awk -F / '{print $3}')
                        LiveBuildCL=$(echo "$VersionInfo" | awk -F / '{print $4}')
                        LiveVersion="${LiveMajorVersion}.${LiveBuildCL}"
                     else
                        LiveVersion="NoLiveP4Broker"
                     fi
                  else
                     LiveVersion="NoLiveP4Broker"
                  fi
               ;;
               (p4p)
                  # shellcheck disable=SC2154
                  if [[ -x "$P4ProxyInitScript" ]]; then
                  VersionInfo=$("$P4BIN" -p "$PROXY_PORT" -ztag -F %proxyVersion% info -s 2>/dev/null)

                     if [[ -n "$VersionInfo" ]]; then
                        # Trim off the date string, e.g. " (2020/09/08)"
                        VersionInfo=${VersionInfo%% (*}
                        LiveMajorVersion=$(echo "$VersionInfo" | awk -F / '{print $3}')
                        LiveBuildCL=$(echo "$VersionInfo" | awk -F / '{print $4}')
                        LiveVersion="${LiveMajorVersion}.${LiveBuildCL}"
                     else
                        LiveVersion="NoLiveP4Proxy"
                     fi
                  else
                     LiveVersion="NoLiveP4Proxy"
                  fi
               ;;
            esac
         else
            msg "Skipping $Bin upgrade as there is no current symlink: $InstanceLinkPath"
            continue
         fi

         # shellcheck disable=SC2086
         NewMajorVersion=$("$BinPath" $VOpts | grep -i Rev. | awk -F / '{print $3}')
         # shellcheck disable=SC2086
         NewBuildCL=$("$BinPath" $VOpts | grep -i Rev. | awk -F / '{print $4}' | awk '{print $1}')
         NewVersion="${NewMajorVersion}.${NewBuildCL}"

         if [[ "$OldVersion" != "$NewVersion" ]]; then
            # A lexigraphical comparison is good for our needs here.
            if [[ "$OldVersion" < "$NewVersion" ]]; then
               msg "The $Bin binary will be upgraded from $OldVersion to $NewVersion."
               UpgradeHelixBinaries+="$Bin "
               [[ "$Bin" != "p4" ]] && UpgradeServiceList+="$Bin "
            else
               if [[ "$OverrideDowngradePrevention" -eq 0 ]]; then
                  errmsg "The staged $Bin binary in $BinariesDir [$NewVersion] is an older version than what is in place [$OldVersion]. Downgrades are not supported."
                  continue
               else
                  warnmsg "Downgrade detected. Downgrade will be attempted due to '-Od'."
                  UpgradeHelixBinaries+="$Bin "
                  [[ "$Bin" != "p4" ]] && UpgradeServiceList+="$Bin "
               fi
            fi
         else
            # If there are multiple instances to be upgraded, the upgrade of the first
            # instance will upgrade the major version symlink (e.g. p4d_2020.1_bin or
            # similar) to point to the latest patch binary, e.g. p4d_2020.1.2007551.
            # Live running binaries for other instances will still be on the older version,
            # and will need just a service bounce to update them to the latest patch.
            if [[ "$Bin" == "p4" || "$LiveVersion" == "NoLive"* || "$OldVersion" == "$LiveVersion" ]]; then
               msg "The $Bin v$NewVersion binary does not need to be upgraded."
               continue
            else
               if [[ "$LiveVersion" < "$OldVersion" ]]; then
                  msg "The live running $Bin binary will be restarted to update from $LiveVersion to $NewVersion."
                  UpgradeServiceList+="$Bin "
               else
                  if [[ "$OverrideDowngradePrevention" -eq 0 ]]; then
                     errmsg "The live running $Bin binary version [$LiveVersion] is newer than what is is in place [$OldVersion]. Downgrades are not supported."
                     continue
                  else
                     warnmsg "Downgrade detected. Downgrade will be attempted due to '-Od'."
                     UpgradeServiceList+="$Bin "
                  fi
               fi
            fi
         fi

         if [[ "$Bin" == "p4d" ]]; then
            if [[ "$OldMajorVersion" != "$NewMajorVersion" ]]; then
               msg "A major version upgrade for p4d is needed. A schema upgrade will be performed."
               DoP4DMajorVersionUpgrade=1
            elif [[ "$LiveMajorVersion" != "NoLiveP4D" && "$LiveMajorVersion" != "$NewMajorVersion" ]]; then
               msg "A major version upgrade for the live running p4d is needed. A schema upgrade will be performed."
               DoP4DMajorVersionUpgrade=1
            else
               msg "P4D patch upgrade is needed, but not a major version upgrade. No schema upgrade will be performed."
            fi

            # A lexigraphical comparison is good for our needs here.
            # shellcheck disable=SC2072
            if [[ "$NewMajorVersion" > "2020.1" ]]; then
               msg "New P4D version is 2020.2+. Modern upgrade logic applies, and 'p4 upgrades' will be used."
               P4D2019_1_Plus=1
               P4D2020_2_Plus=1
            elif [[ "$NewMajorVersion" > "2019.0" ]]; then
               msg "New P4D version is 2019.1+. Modern upgrade logic applies."
               P4D2019_1_Plus=1
            else
               msg "P4D version pre-2019.1, so legacy upgrade logic will be applied."
            fi

            # A lexigraphical comparison is good for our needs here.
            # shellcheck disable=SC2072
            if [[ "$OldMajorVersion" < "2019.0" && "$NewMajorVersion" > "2019.0" ]]; then
               msg "This upgrade goes 'to or thru' P4D 2019.1. Upgrades to db.storage will be done."

               # Even if the user did not specify '-M', we still implicitly
               # disable online upgrade for 'to-or-thru' P4D 2019.1 upgrade,
               # except on the master server itself.
               if [[ "$OnlineUpgrade" -eq 1 ]]; then
                  msg "For any server other than the master, services will be stopped at the start of"
                  msg "processing for 'to-or-thru' P4D 2019.1 upgrades, and will not be restarted"
                  msg "automatically.  For the master, services will be restarted after the upgrade"
                  msg "so that online processing completes and the second journal rotation occurs."
                  msg "After the upgrade.sh completes entirely done on the master (including the"
                  msg "online portion of upgrades, which this script will wait for), a manual of"
                  msg "services on all other machines is required in the 'inner-to-outer' direction"
                  msg "relative to the master."
                  msg "\\nThis applies to 'to-or-thru' P4D 2019.1 upgrades only. This script will"
                  msg "behave differently when the starting P4D version is P4D 2019.1+, such that"
                  msg "upgrades will be simpler, and follow 'outer-to-inner' order."
               fi
               P4D2019_1_StorageUpgrades=1
               [[ "$SERVERID" == "$P4MASTER_ID" ]] || OnlineUpgrade=0
            fi
         fi

      else
         errmsg "The staged $BinPath is not binary."
      fi
   else
      msg "There is no staged $BinPath binary; skipping $Bin."
   fi
done

#------------------------------------------------------------------------------
if [[ -x "$PreUpgradeScript" ]]; then
   PreUpgradeCmd="$PreUpgradeScript $SDPInstance"
   [[ "$NoOp" -eq 0 ]] && PreUpgradeCmd+=" -y"

   if [[ "$IgnorePreflightErrors" -eq 0 ]]; then
      msg "\\nA custom pre-upgrade script exists and will be executed if preflight checks\\nare successful. The pre-upgrade command line will be:\\n\\t$PreUpgradeCmd\\n"
   else
      msg "\\nA custom pre-upgrade script exists and will be executed after preflight checks\\nare attempted. The pre-upgrade command line will be:\\n\\t$PreUpgradeCmd\\n"
   fi
fi

if [[ -x "$PostUpgradeScript" ]]; then
   PostUpgradeCmd="$PostUpgradeScript $SDPInstance"
   [[ "$NoOp" -eq 0 ]] && PostUpgradeCmd+=" -y"

   msg "\\nA custom post-upgrade script exists and will be executed if the upgrade is\\nsuccessful. The post-upgrade command line will be:\\n\\t$PostUpgradeCmd\\n"
fi

if [[ "$ErrorCount" -eq 0 ]]; then
   msg "Verified: Preflight checks passed ($WarningCount warnings)."
else
   if [[ "$IgnorePreflightErrors" -eq 1 ]]; then
      warnmsg "Preflight checks FAILED. Proceeding and resetting error count to 0 after preflight checks due to '-I' flag."
      ErrorCount=0
   else
      bail "Aborting due to failed preflight checks."
   fi
fi

if [[ -z "$UpgradeHelixBinaries" ]]; then
   if [[ -z "$UpgradeServiceList" ]]; then
      msg "No upgrades are needed based on binaries staged in $BinariesDir."
   else
      msg "No upgrades are needed based on binaries staged in $BinariesDir, but service restarts are needed for these: $UpgradeServiceList"
   fi
fi

if [[ "$PreflightOnly" -eq 1 ]]; then
   msg "\\nExiting early after successful preflight checks due to '-p'."
   exit 0
fi

if [[ -z "$UpgradeHelixBinaries" && -z "$UpgradeServiceList" ]]; then
   if [[ "$Force" -eq 1 ]]; then
      msg "\\nNo upgrades are needed. Proceeding anyway due to '-f'.\\n"
   else
      msg "\\nExiting because no upgrades are needed."
      exit 0
   fi
fi

#------------------------------------------------------------------------------
# Preflight checks completed. Continue on!

msg "Start $P4SERVER Upgrade as $ThisUser@${HOSTNAME%%.*} at $(date)."

if [[ "$ErrorCount" -eq 0 || "$IgnorePreflightErrors" -eq 1 ]]; then
   if [[ -n "$PreUpgradeCmd" ]]; then
      msg "\\nExecuting custom pre-upgrade command:\\n\\t$PreUpgradeCmd"

      if $PreUpgradeCmd; then
         msg "\\nThe custom pre-upgrade command indicated success."
      else
         bail "\\nAlthough the standard preflight checks were successful, the custom pre-upgrade command indicated failure. Aborting the upgrade."
      fi
   fi
fi

#------------------------------------------------------------------------------
# Phase 1 - Establish a clean rollback point.
if [[ "$ManualUpgrade" -eq 0 ]]; then
   if [[ "$UpgradeHelixBinaries" == *"p4d"* || "$UpgradeServiceList" == *"p4d"* ]]; then
      if [[ "$SERVERID" == "$P4MASTER_ID" ]]; then
         msg "\\nPhase 1: Establish a clean rollback point for p4d upgrades."
         run "$P4CBIN/rotate_journal.sh $SDPInstance" \
            "Rotating journal to provide a clean rollback point." ||\
            bail "Journal rotation failed. No upgrade processing has been done. Aborting upgrade."

         if [[ "$NoOp" -eq 0 ]]; then
            if grep -q "End $P4SERVER journal rotation" "$LOGS/checkpoint.log"; then
               msg "Verified: Journal rotation completed OK."
            else
               bail "Could not verify journal rotation completed OK. No upgrade processing has been done. Aborting upgrade."
            fi
         else
            msg "NO_OP: Journal rotation completed OK."
         fi
      else
         # P4DInitScript is defined with set_vars() from backup_functions.sh.
         # shellcheck disable=SC2154
         if [[ -x "$P4DInitScript" ]]; then
            msg "Skipping Phase 1 (p4d journal rotation) for ServerID $SERVERID, as this is only needed on master server."
         else
            msg "Skipping Phase 1 (p4d journal rotation) as p4d does not run on this machine."
         fi
      fi
   else
      msg "Skipping Phase 1 (p4d journal rotation) as p4d does not need to be upgraded."
   fi
else
   msg "Skipping Phase 1 (p4d journal rotation) due to '-M'."
fi

#------------------------------------------------------------------------------
# Phase 2 - Install new binaries and update SDP symlinks.
msg "\\nPhase 2: Install new binaries and update SDP symlinks in $PWD."

for Bin in $UpgradeHelixBinaries; do
   BinPath="$BinariesDir/$Bin"
   VOpts="-V"
   # For p4d, we must supply an existing dir with '-r' to suppress ugly
   # error messages related to P4ROOT not existing, e.g. if run on a
   # proxy-only or broker-only host.
   [[ "$Bin" == p4d ]] && VOpts="-V -r /tmp"
   # shellcheck disable=SC2086
   NewMajorVersion=$("$BinPath" $VOpts | grep -i Rev. | awk -F / '{print $3}')
   # shellcheck disable=SC2086
   NewBuildCL=$("$BinPath" $VOpts | grep -i Rev. | awk -F / '{print $4}' | awk '{print $1}')
   NewVersion="${NewMajorVersion}.${NewBuildCL}"
   VersionLinkPath="${Bin}_${NewMajorVersion}_bin"
   if [[ "$Bin" == "p4" ]]; then
      InstanceLinkPath="${Bin}_bin"
   else
      InstanceLinkPath="${Bin}_${SDPInstance}_bin"
   fi

   # shellcheck disable=SC2086
   OldMajorVersion=$("./$InstanceLinkPath" $VOpts | grep -i Rev. | awk -F / '{print $3}')
   # shellcheck disable=SC2086
   OldBuildCL=$("./$InstanceLinkPath" $VOpts | grep -i Rev. | awk -F / '{print $4}' | awk '{print $1}')
   OldVersion="${OldMajorVersion}.${OldBuildCL}"

   NewVersionNamedBin="${Bin}_$NewVersion"
   if [[ ! -f "$NewVersionNamedBin" ]]; then
      run "cp $BinariesDir/$Bin $NewVersionNamedBin" ||\
         errmsg "Failed to copy $BinariesDir/$Bin to $NewVersionNamedBin"
   fi
   run "ln -f -s $NewVersionNamedBin $VersionLinkPath" \
      "Updating major version symlink $VersionLinkPath" ||\
      errmsg "Failed to updated major version symlink."
   run "ln -f -s $VersionLinkPath $InstanceLinkPath" \
      "Updating instance symlink $InstanceLinkPath" ||\
      errmsg "Failed to updated major version symlink."
done

if [[ "$ManualUpgrade" -eq 1 ]]; then
   if [[ "$ErrorCount" -eq 0 ]]; then
      msg "\\nDone with no errors. Stopping after Phase 2 (adding binaries and updating symlinks) due to '-M'."
      exit 0
   else
      bail "\\nPhase 2 done with $ErrorCount errors. Stopping after Phase 2 (adding binaries and updating symlinks) due to '-M'."
   fi
fi

#------------------------------------------------------------------------------
# Phase 3 - Stop services to be upgraded.

# Phase 2 will add binaries and update symlinks to keep /p4/common/bin in
# sync everywhere, even though services aren't operational on all machines.
# Here in Phase 3, we only stop/restart services active on this machine.
for Bin in $UpgradeServiceList; do
   if [[ "$Bin" == "p4broker" ]]; then
      # shellcheck disable=SC2154
      [[ -x "$P4BrokerInitScript" ]] && RestartCandidates+="p4broker "
   fi

   if [[ "$Bin" == "p4p" ]]; then
      # shellcheck disable=SC2154
      [[ -x "$P4ProxyInitScript" ]] && RestartCandidates+="p4p "
   fi

   if [[ "$Bin" == "p4d" ]]; then
      # shellcheck disable=SC2154
      [[ -x "$P4DInitScript" ]] && RestartCandidates+="p4d "
   fi
done

if [[ -n "$RestartCandidates" ]]; then
   msg "\\nPhase 3: Stop services to be upgraded (if operating): $RestartCandidates."

   # Stop services to be upgraded if they have an init script and are up.
   # In the case of a p4broker, only interact with the default p4broker config;
   # do not manage other broker configurations, such as 'dfm' (Down for
   # Maintenance) configs.
   for Bin in $RestartCandidates; do
      if [[ "$Bin" == "p4broker" ]]; then
         if is_server_up p4broker; then
            RestartBroker=1
            if [[ "$NoOp" -eq 0 ]]; then
               stop_p4broker
            else
               msg "NO_OP: Would stop p4broker now."
            fi
         else
            msg "Broker (p4broker) with default config was not running, and will not be started after the upgrade."
         fi
      fi

      if [[ "$Bin" == "p4p" ]]; then
         if is_server_up p4p; then
            RestartProxy=1
            if [[ "$NoOp" -eq 0 ]]; then
               stop_p4p
            else
               msg "NO_OP: Would stop p4p now."
            fi
         else
            msg "Proxy (p4p) was not running, and will not be started after the upgrade."
         fi
      fi

      if [[ "$Bin" == "p4d" ]]; then
         # P4DInitScript is defined with set_vars() from backup_functions.sh.
         # shellcheck disable=SC2154
         if [[ -x "$P4DInitScript" ]]; then
            RestartP4D=1
            if [[ "$NoOp" -eq 0 ]]; then
               stop_p4d
            else
               msg "NO_OP: Would stop p4d now."
            fi
         fi
      fi
   done
else
   msg "Skipping Phase 3 (stop services) because no running services were upgraded."
fi

#------------------------------------------------------------------------------
# Phase 4 - Perforce p4d schema upgrades
if [[ ( "$UpgradeHelixBinaries" == *"p4d"* || "$UpgradeServiceList" == *"p4d"* ) && -x "$P4DInitScript" ]]; then
   if [[ "$DoP4DMajorVersionUpgrade" -eq 1 ]]; then
      msg "\\nPhase 4: Perform p4d schema upgrades."

      # For P4D versions >= 19.1, schema upgrades are journaled, and thus are
      # applied to the offline_db through the journal rotation process.
      # For older versions of p4d, we run the 'p4d -xu' separately in the offline_db.
      if [[ "$P4D2019_1_Plus" -eq 1 ]]; then
         UpgradeJournal="$P4JOURNAL"
      else
         UpgradeJournal=off
      fi

      run "$P4DBIN -r $P4ROOT -J $UpgradeJournal -xu" \
         "Upgrading databases in $P4ROOT." ||\
         bail "Failed to upgrade root database."

      # Upgrade the offline database on the master and on edge servers.
      # This only applies to pre-2019.1 upgrades.
      if [[ "$P4REPLICA" == "FALSE" ]] || [[ "$EDGESERVER" -eq 1 ]]; then
         if [[ "$P4D2019_1_Plus" -eq 0 ]]; then
            msg "Upgrading databases in $OFFLINE_DB as this is a pre-19.1 server upgrade."

            # The value of '-t localhost:0000' is necessary for syntax reasons;
            # it is ignored. This allows upgrade of offline databases without needing
            # a license file; there isn't one in offline_db, only P4ROOT.  A valid
            # license file is required to actually start the server process and have
            # it listen on a port.

            run "$P4DBIN -r $OFFLINE_DB -J $UpgradeJournal -xu -t localhost:0000" \
               "Upgrading databases in $OFFLINE_DB." ||\
               bail "Failed to upgrade offline_db"
         fi
      else
         msg "Skipping '-xu' update of offline_db; not on master or edge."
      fi
   else
      msg "Skipping Phase 4 (schema upgrade) as p4d upgrade is a patch rather than a major version upgrade." 
   fi
else
   # Display a message indicating that we're skipping the schema upgrade only if
   # we're on a machine with p4d operating.  Otherwise, no message is needed.
   if [[ -x "$P4DInitScript" ]]; then
      msg "Skipping Phase 4 (schema upgrade) as p4d does not need to be upgraded."
   fi
fi

#------------------------------------------------------------------------------
# Phase 5 - Start upgraded services.
if [[ -n "$RestartCandidates" ]]; then
   msg "\\nPhase 5: Restart upgraded services: $RestartCandidates."

   # Start upgraded services if they have an init script. In the case of a
   # broker, also check that it has a default configuration file, as brokers are
   # often configured but run only on demand with a non-default configuration file
   # (e.g. in maintenance mode with a 'dfm' (Down for Maintenance) config.
   for Bin in $RestartCandidates; do
      if [[ "$Bin" == "p4d" ]]; then
         if [[ "$RestartP4D" -eq 1 ]]; then
            if [[ "$NoOp" -eq 0 ]]; then
               if [[ "$OnlineUpgrade" -eq 1 ]]; then
                  msg "Starting Helix Core (p4d)."
                  start_p4d
               else
                  msg "Skipping restart of Helix Core (p4d). Start it manually when ready."
               fi
            else
               msg "NO_OP: Would start p4d now."
            fi
         fi

         # For p4d 2019.1+ upgrades, do an extra journal rotation post-upgrade
         # to apply journal changes to the offline_db (if on the master).
         if [[ "$P4D2019_1_Plus" -eq 1 && "$RestartP4D" -eq 1 ]]; then
            if [[ "$SERVERID" == "$P4MASTER_ID" ]]; then
               if [[ "$P4D2019_1_StorageUpgrades" -eq 1 ]]; then
                  run "$P4BIN storage -w" "Waiting for db.storage upgrades. This may take a while." ||\
                     errmsg "The 'p4 storage -w' command reported errors."
               fi

               if [[ "$DoP4DMajorVersionUpgrade" -eq 1 ]]; then
                  if [[ "$P4D2020_2_Plus" -eq 1 ]]; then
                     msg "Waiting for all upgrades per 'p4 upgrades' to complete. The log is: $TmpFile_1."
                     if [[ "$NoOp" -eq 0 ]]; then
                        echo -ne "Waiting ..."

                        # In theory, this could be an infinite loop. However,
                        # the safest way to code this is to simply wait for
                        # all upgrades to complete, as they may take an
                        # arbitrarily long time.
                        # shellcheck disable=SC2078 disable=SC2161
                        while [[ 1 ]]; do
                           "$P4BIN" upgrades > "$TmpFile_1" 2>&1
                           dbg "Output of 'p4 upgrades' in $TmpFile_1:"
                           [[ "$Debug" -eq 1 ]] && cat "$TmpFile_1"
                           # If we see anything other than 'completed' or
                           # 'failed', keep waiting.
                           if grep -qiEv ' (completed|failed)' "$TmpFile_1"; then
                              echo -n "."
                              sleep 3
                           else
                              break
                           fi
                        done

                        if ! grep -qi ' failed' "$TmpFile_1"; then
                           msg "\\nProcessing of upgrades completed OK.\\n"
                        else
                           errmsg "The 'p4 upgrades' command reported failed steps:"
                           cat "$TmpFile_1"
                           msg "\\n\\n"
                        fi
                        rm -f "$TmpFile_1"
                     else
                        msg "NO_OP: Would have waited for 'p4 upgrades'."
                     fi
                  fi

                  run "$P4BIN admin journal" \
                     "Capturing upgrade processing via journal rotation on commit server." ||\
                     bail "Journal rotation failed."
               else
                  msg "Skipping second journal rotation for this patch upgrade. A second journal rotation is done only for major version upgrades."
               fi
            else
               msg "Skipping second journal rotation for ServerID $SERVERID, as this is only needed on the master."
            fi
         fi
      fi

      if [[ "$Bin" == "p4broker" ]]; then
         if [[ "$RestartBroker" -eq 1 ]]; then
            if [[ "$OnlineUpgrade" -eq 1 ]]; then
               if [[ "$NoOp" -eq 0 ]]; then
                  msg "Starting Broker (p4broker)."
                  start_p4broker
               else
                  msg "NO_OP: Would start p4broker now."
               fi
            else
               msg "Skipping restart of p4broker with default config. Start it manually when ready."
            fi
         else
            msg "Skipping start of p4broker with default config (not online at start of upgrade)."
         fi
      fi

      if [[ "$Bin" == "p4p" ]]; then
         if [[ "$RestartProxy" -eq 1 ]]; then
            if [[ "$OnlineUpgrade" -eq 1 ]]; then
               if [[ "$NoOp" -eq 0 ]]; then
                  msg "Starting Proxy (p4p)."
                  start_p4p
               else
                  msg "NO_OP: Would start p4p now."
               fi
            else
               msg "Skipping start of p4p. Start it manually when ready."
            fi
         else
            msg "Skipping start of p4p (not online at start of upgrade)."
         fi
      fi
   done
else
   msg "Skipping Phase 5 (restart services) because no running services were upgraded."
fi

# Upgrade protections on master if '-c' was specified.
if [[ "$DoProtectionsCommentStyleUpgrade" -eq 1 ]]; then
   if [[ "$SERVERID" == "$P4MASTER_ID" ]]; then
      msg "Upgrading protections table comment format."
      if "$P4BIN" protect -o | grep -v '^Update:' > "$TmpFile_1"; then
         if "$P4BIN" protect --convert-p4admin-comments -o | grep -v '^Update:' > "$TmpFile_2"; then
            if ! diff -q "$TmpFile_1" "$TmpFile_2"; then
               msg "Protections table comment conversion diffs are:"
               diff -q "$TmpFile_1" "$TmpFile_2"

               if [[ "$NoOp" -eq 0 ]]; then
                  if "$P4BIN" -s protect -i < "$TmpFile_2"; then
                     msg "Protections table comments updated."
                  else
                     errmsg "There was a problem updating the Protections table comments."
                  fi
               else
                  msg "NO_OP: Would update protections with comment conversion."
               fi
            else
               msg "The '-c' flag was specified, but no protections table updates are needed."
            fi
         else
            errmsg "Error capturing protections table with --convert-p4admin-comments option."
         fi
      else
         errmsg "Error capturing protections table."
      fi
      rm -f "$TmpFile_1" "$TmpFile_2"
   fi
fi

if [[ "$ErrorCount" -eq 0 ]]; then
   msg "\\nSuccess: Finished $P4SERVER Upgrade."

   if [[ -n "$PostUpgradeCmd" ]]; then
      msg "\\nExecuting custom post-upgrade command:\\n\\t$PostUpgradeCmd"

      if $PostUpgradeCmd; then
         msg "\\nThe custom post-upgrade command indicated success."
      else
         errmsg "\\nAlthough the primary upgrade was successful, the custom post-upgrade command indicated failure."
      fi
   fi
else
   errmsg "Finished $P4SERVER Upgrade, but there were errors. Review this log."
fi

if [[ "$NoOp" -ne 0 ]]; then
   msg "NO_OP: This was done in No-Op (No Operation/Preview) mode. No actual upgrade was done. Add the '-y' flag to perform the actual upgrade."
fi

# See the terminate() function, which is really where this script exits.
exit 0
