#!/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

declare ThisScript="${0##*/}"
declare ThisUser=
declare CmdLine="$0 $*"
declare SDPInstance=UnsetSDPInstance
declare Version=4.6.5
declare -i Debug=0
declare -i NoOp=0
declare -i ErrorCount=0
declare -i WarningCount=0
declare -i IgnorePreflightErrors=0
declare -i ManualUpgrade=0
declare -i PreflightOnly=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 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 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}"; }

#------------------------------------------------------------------------------
# This function takes as input an SDP version string, and returns a version
# id of the form YYYY.N.CL, where YYYY is the year, N is an incrementing
# release ID with a given year, and CL is a changelist identifier. The
# YYYY.N together comprise the major version, often shortened to YY.N, e.g.
# r20.1 for the 2020.1 release.
#
# The full SDP Version string looks something like this:
# Rev. SDP/MultiArch/2019.3/26494 (2020/04/23).
#
# This function parses that full string and returns a value like: 2019.3.26494
function get_sdp_version_from_string () {
   local versionString="${1:-}"
   local version=
   version="20${versionString##*/20}"
   version="${version%% *}"
   version="${version/\//.}"
   echo "$version"
}

#------------------------------------------------------------------------------
# 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
      if $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
# errror, usually $1 should be -h so that the longer usage message doesn't
# obsure 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
      echo -e "\\n\\nUsage Error:\\n\\n$usageErrorMessage\\n\\n"
   fi

   # tag::includeManual[]
   echo "USAGE for $ThisScript v$Version:

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

or

$ThisScript [-h|-man]
"
   if [[ $style == -man ]]; then
      echo -e "
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

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
given machine.

For example, a typical master 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 phase execute depend on the what binaries
are 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'; 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'; 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 ugprades 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'; fix problems if needed until it reports clean.
   3. upgrade.sh

UPGRADE PREPARATION

The steps for deploying new binaries to server amchines 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 constitue 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.

MASTER 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.

When the master server is upgraded, two rotations of the master server's journal
occur during processing.  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.

Later, after the p4d has started and p4d performs its journaled upgrade
processing, a second journal rotation occurs in Phase 5. This second journal
rotation captures all upgrade-related processing in a seprate numbered journal.

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 'uprade.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 gapped\" 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, procesing starts
	immediately upon successful completion of prelfight checks.

 -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.

	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.  Do not run this
	script with redirection operators like '> log' or '2>&1', and do not
	use '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.

DEBUGGING OPTIONS:
 -n	No-Op.  In No-Op mode, no actions that affect data or structures are
	taken.  Instead, commands that would be run are displayed.  This
	command can also be educational, showing various steps that will occur
	during an upgrade.

 -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: 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 executes the upgrade after successful completion of preflight checks,
	and aborts if preflight checks detected any issues.

	EXAMPLE 2: 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 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:

	\$ upgrade.sh

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.
"
   fi

   exit 1
}

#------------------------------------------------------------------------------
# Function: terminate
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.
   [[ "$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;;
      (-h) usage -h;;
      (-man) usage -man;;
      (-n) NoOp=1;;
      (-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.
      (*)
         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

[[ -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)

msg "Started $ThisScript v$Version as $ThisUser@${HOSTNAME%%.*} 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.

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

# shellcheck disable=SC1090
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_LIS:-},crontab -L off -online"
else
   VerifyCmd="$P4CBIN/verify_sdp.sh $SDPInstance -skip ${VERIFY_SDP_SKIP_TEST_LIS:-},crontab -L off"
fi

msg "Running verify_sdp.sh as part of preflight chekcs."
# 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
   errmsg "The verify_sdp.sh script reported preflight errors. Correct these and try again."
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}"
         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
               errmsg "The staged $Bin binary in $BinariesDir is an older version [$OldVersion] than the live version [$NewVersion]. Downgrades are not supported."
               continue
            fi
         else
            msg "The $Bin v$NewVersion binary does not need to be upgraded."
            continue
         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
            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 implicilty
               # 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 [[ "$ErrorCount" -eq 0 ]]; then
   msg "Verified: Preflight checks passed ($WarningCount warnings)."
else
   if [[ "$IgnorePreflightErrors" -eq 1 ]]; then
      warnmsg "Prelfight 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
   msg "No upgrades are needed based on binaries staged in $BinariesDir."
fi

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

if [[ -z "$UpgradeHelixBinaries" ]]; then
   msg "\\nExiting because no upgrades are needed."
   exit 0
fi

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

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

#------------------------------------------------------------------------------
# Phase 1 - Establish a clean rollback point.
if [[ "$ManualUpgrade" -eq 0 ]]; then
   if [[ "$UpgradeHelixBinaries" == *"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) on replica 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"* && -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 skiping the schmea 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 retart 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."
                     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
                              msg "\\n\\n"
                           fi
                        done

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

                  run "$P4CBIN/rotate_journal.sh $SDPInstance" \
                     "Upgrade offline_db via journal rotation on master/commit server." ||\
                     bail "Journal rotation failed during offline_db upgrade phase."
               fi
            else
               msg "Skipping second journal rotation as this is only a patch upgrade."
            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 retart 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 proctions 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."
else
   errmsg "Finished $P4SERVER Upgrade, but there were errors. Review this log."
fi

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