#!/bin/bash
set -u
#==============================================================================
# Copyright and license info is available in the LICENSE file included with
# the Server Deployment Package (SDP), and also available online:
# https://workshop.perforce.com/view/p4-sdp/main/LICENSE
#------------------------------------------------------------------------------
#==============================================================================
# Declarations and Environment
# Version ID Block. Relies on +k filetype modifier.
#------------------------------------------------------------------------------
# shellcheck disable=SC2016
declare VersionID='$Id: //p4-sdp/r26.1.0/Server/Unix/p4/common/bin/templates/template.sh#1 $ $Change: 33565 $'
declare VersionStream=${VersionID#*//}; VersionStream=${VersionStream#*/}; VersionStream=${VersionStream%%/*};
declare VersionCL=${VersionID##*: }; VersionCL=${VersionCL%% *}
declare Version=${VersionStream}.${VersionCL}
[[ "$VersionStream" == r* ]] || Version="${Version^^}"
declare ThisScript=${0##*/}
declare ThisUser=
declare Args="$*"
declare CmdLine="$0 $Args"
declare ThisHost=${HOSTNAME%%.*}
declare -i Debug=${SDP_DEBUG:-0}
declare -i ErrorCount=0
declare -i WarningCount=0
declare -i SilentMode=0
declare -i LogIdx=0
declare Log=
declare LogTimestamp=
declare OldLogTimestamp=
declare LogLink=
declare H1="=============================================================================="
declare H2="------------------------------------------------------------------------------"
declare SDPInstance=${SDP_INSTANCE:-}
declare SDPRoot=${SDP_ROOT:-/p4}
declare SDPCommon="$SDPRoot/common"
declare SDPCommonBin="$SDPCommon/bin"
declare SDPCommonLib="$SDPCommon/lib"
declare SDPEnv="$SDPCommonBin/p4_vars"
# Color support for interactive operation.
declare GREEN=
declare RED=
declare YELLOW=
declare RESET=
### EDITME Choose behavior:
### Option 1: Initialize NoOp to 0 making DRY RUN/Preview mode the default, and
### require '-y' for Live Operation mode.
### Option 2: Initialize NoOp to 1 making Live Operation mode the default, and
### provide '-n' for DRY RUN/Preview mode.
### Option 3: If not supporting DRY RUN/Preview mode, remove NoOp and handling
### of '-y/-n' in the command line processing block.
### Use Option 1 for more dangerous scripts for which operating in Live Run mode
### is potentially dangerous. The '-n' and '-y' command line options are
### reserved even if unused.
declare -i NoOp=0
#==============================================================================
# Local Functions
function msg () { echo -e "$*"; }
function msgn () { echo -e -n "$*"; }
function msg_green { msg "${GREEN}$*${RESET}"; }
function msg_yellow { msg "${YELLOW}$*${RESET}"; }
function msg_red { msg "${RED}$*${RESET}"; }
function dbg () { [[ "$Debug" -eq 0 ]] || msg "DEBUG: $*"; }
function dbg2 () { [[ "$Debug" -lt 2 ]] || msg "DEBUG: $*"; }
function errmsg () { msg_red "\nError: ${1:-Unknown Error}\n"; ErrorCount+=1; }
function warnmsg () { msg_yellow "\nWarning: ${1:-Unknown Warning}\n"; WarningCount+=1; }
function bail () { errmsg "${1:-Unknown Error}"; exit "${2:-1}"; }
#==============================================================================
# Load SDP Library Functions.
if [[ -d "$SDPCommonLib" ]]; then
# shellcheck disable=SC1090 disable=SC1091
source "$SDPCommonLib/logging.lib" ||\
bail "Failed to load bash lib [$SDPCommonLib/logging.lib]. Aborting."
# shellcheck disable=SC1090 disable=SC1091
source "$SDPCommonLib/run.lib" ||\
bail "Failed to load bash lib [$SDPCommonLib/run.lib]. Aborting."
# shellcheck disable=SC1090 disable=SC1091
source "$SDPCommonLib/utils.lib" ||\
bail "Failed to load bash lib [$SDPCommonLib/utils.lib]. Aborting."
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 a
# 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 "Missing required parameter <RequiredParameter>."
#------------------------------------------------------------------------------
function usage
{
local style=${1:--h}
local usageErrorMessage=${2:-Unset}
if [[ "$usageErrorMessage" != Unset ]]; then
msg "\n\nUsage Error:\n\n$usageErrorMessage\n\n"
fi
msg "USAGE for $ThisScript v$Version:
$ThisScript EDITME <RequiredParameter> [-option] [-i <sdp_instance>] [-L <log>] [-si] [-n] [-d|-D]
or
$ThisScript [-h|-man|-V]
"
if [[ $style == -man ]]; then
msg "
DESCRIPTION: EDITME
OPTIONS:
-i <sdp_instance>
Specify the SDP Instance. If not specified, the \$SDP_INSTANCE variable is
referenced, otherwise the default is '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
EDITME_DEFAULT_LOG
NOTE: This script is self-logging. That is, output displayed on the screen
is simultaneously captured in the log file. Using redirection operators like
like '> log' or '2>&1' or using 'tee' are unnecessary (but harmless).
-si
Operate silently. All output (stdout and stderr) are redirected to the log
only; no output appears on the terminal (except for help/usage info, usage
errors, or version checks on startup). The '-si' option cannot be used with
'-L off'.
EDITME: This is intended to be used when running scripts from the crontab. By
preventing any output, it prevents email from being sent by cron daemon
directly, as cron does when a script called from cron generates any output.
This script is then responsible for email handling or other notifications, if
any is to be done.
-n
Enable DRY RUN/Preview mode, displaying commands that would affect data
rather than executing them.
-D
Set extreme debugging verbosity.
HELP OPTIONS:
-h Display short help message.
-man Display man-style help message.
-V Display version info for this script.
FILES:
EXAMPLES:
SEE ALSO:
"
fi
exit 2
}
#==============================================================================
# Command Line Processing
declare SampleArgument=""; ### EDITME
declare -i ShiftArgs=0
set +u
while [[ $# -gt 0 ]]; do
case $1 in
(-s) SampleArgument="$2"; ShiftArgs=1;; ### EDITME
(-h) usage -h;;
(-man|--help) usage -man;;
(-V|--version) show_versions; exit 0;;
(-i) SDPInstance="$2"; ShiftArgs=1;;
(-L) Log="$2"; ShiftArgs=1;;
(-si) SilentMode=1;;
(-n) NoOp=1;;
#(-y) NoOp=0;; ### EDITME: Use '-n' or '-y', not both. See NoOp initialization in Declarations.
(-d) Debug=1;;
(-D) Debug=1; set -x;; # Use bash 'set -x' extreme debug mode.
(*) usage -h "Unknown arg ($1).";;
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
# shellcheck disable=SC1090
source "$SDPEnv" "$SDPInstance" ||\
bail "Could not do: source \"$SDPEnv\" \"$SDPInstance\""
#==============================================================================
# Command Line Verification
[[ "$SilentMode" -eq 1 && "$Log" == off ]] && \
usage -h "Cannot use '-si' with '-L off'."
#==============================================================================
# Main Program
trap terminate EXIT SIGINT SIGTERM
# Detect support for colors
if [[ $SilentMode -eq 0 ]] \
&& command -v tput >/dev/null 2>&1 \
&& [[ -t 1 ]] \
&& [[ "$(tput colors)" -ge 8 ]]; then
RED="$(tput setaf 1)"
GREEN="$(tput setaf 2)"
YELLOW="$(tput setaf 3)"
RESET="$(tput sgr0)"
else
RED=; GREEN=; YELLOW=; RESET=
fi
# Logging setup. See the Logging section of SDP_CodingStandard_bash.adoc
# for the full description of the log file naming, LogLink symlink, atomic
# creation, and redirection strategy implemented below.
# Summary:
# Default log: $LOGS/<ScriptName>.<YYYY-MM-DD-HHMMSS>.log
# LogLink: $LOGS/<ScriptName>.log (symlink to most recent log)
# -L <file>: Write to specified file instead; no LogLink created.
# -L off: Logging disabled entirely.
if [[ "$Log" != off ]]; then
# If $Log is not yet defined, set it to a reasonable default.
if [[ -z "$Log" ]]; then
[[ -d "${LOGS:-}" ]] ||\
bail "Log directory does not exist: [${LOGS:-unset}]. Verify SDP_ROOT [$SDPRoot] and SDP instance [$SDPInstance] are correct."
LogTimestamp=$(date +'%Y-%m-%d-%H%M%S')
Log="$LOGS/${ThisScript%.sh}.${LogTimestamp}.log"
# Atomically create the log file using noclobber to avoid a race
# condition when the script is invoked multiple times concurrently.
# If the seconds-granularity filename is already taken (concurrent
# invocation in the same second), append an incrementing integer suffix.
# Note: Millisecond precision is intentionally avoided here because the
# %3N date format specifier is a GNU extension not supported on macOS.
until ( set -C; : > "$Log" ) 2>/dev/null; do
Log="$LOGS/${ThisScript%.sh}.${LogTimestamp}.${LogIdx}.log"
LogIdx+=1
done
fi
# The LogLink symlink has no timestamp. It points to the most recent log file.
LogLink="$LOGS/${ThisScript%.sh}.log"
if [[ -e "$LogLink" ]]; then
if [[ -L "$LogLink" ]]; then
rm -f "$LogLink"
else
# If the name that should be a symlink is not a symlink, move it aside before
# creating the symlink.
OldLogTimestamp=$(get_old_log_timestamp "$LogLink")
mv -f "$LogLink" "${LogLink%.log}.${OldLogTimestamp}.log" ||\
bail "Could not move old log file aside; tried: mv -f \"$LogLink\" \"${LogLink%.log}.${OldLogTimestamp}.log\""
fi
fi
ln -sf "$Log" "$LogLink" ||\
bail "Could not create log symlink: ln -sf \"$Log\" \"$LogLink\""
# Redirect stdout and stderr to a log file. When redirecting to a log,
# suppress color codes because they detract from readability in logs.
if [[ "$SilentMode" -eq 0 ]]; then
if [[ -n "$GREEN" ]]; then
exec > >( tee \
>(sed -r \
-e 's/\x1B\[[0-9;]*[a-zA-Z]//g' \
-e 's/\x1B\(B//g' >>"$Log"))
else
exec > >(tee -a "$Log")
fi
exec 2>&1
else
exec >"$Log"
exec 2>&1
fi
msg "${H1}\nLog is: $Log\n"
fi
ThisUser=$(id -n -u)
msg "Starting $ThisScript v$Version as $ThisUser@$ThisHost on $(date) with \\n$CmdLine"
if [[ "$NoOp" -eq 0 ]]; then
msg "\nOperating in Live Operation mode."
else
msg "\nOperating in DRY RUN (Preview) mode."
fi
### EDITME BEGIN - Replace this entire sample block with real business logic.
### Delete everything from this line through the EDITME END marker below.
# Sample: msg_green/warnmsg/errmsg for basic status output.
msg_green "Happy Message"
warnmsg "Be safe!"
# Sample: msgn() for output that continues on the same line. Use msgn() to
# display a label before performing a check or operation whose result will
# complete the line, keeping related status together without an intervening
# blank line.
msgn "Checking SDP instance [$SDPInstance] on $ThisHost..."
/bin/sleep 1
msg " done."
# Sample: run() to execute a command with optional description and NoOp support.
run "ls /tmp" "List temp area."
run "ls" "Sample Arg specified with '-s <arg>' is [$SampleArgument]. Directory List:" 1 1
run "/bin/sleep 1" "Taking a short nap." 1 0
# Sample: run() with a pipeline.
run "ls -lrt|grep \"Dec 16\"|head -2|tail -1" "Showing last file:" 1 1
# Sample: warnmsg/errmsg/dbg/dbg2.
warnmsg "Sample WarningMsg 1"
errmsg "Sample Error Message 2"
warnmsg "Sample WarningMsg 3"
errmsg "Sample Error Message 4"
dbg "Regular debug message."
dbg2 "Extra Verbose debug message."
# Sample: rrun() to execute commands on a remote host.
rrun localhost "sleep 2\nls -lrt /tmp/" "Doing an ls on simulated remote host." 1 1 0
rrun localhost "ls -l /tmp/*" "Grepping remote output for /tmp/hello" 0 0 "/tmp/hello" ||\
warnmsg "/tmp/hello was not found in remote output."
### EDITME END
if [[ "$ErrorCount" -eq 0 && "$WarningCount" -eq 0 ]]; then
msg_green "${H2}\nAll processing completed successfully.\n"
elif [[ "$ErrorCount" -eq 0 ]]; then
warnmsg "${H2}\nProcessing completed with no errors, but there were $WarningCount warnings. Review the above output carefully.\n"
else
errmsg "${H2}\nProcessing completed, but there were $ErrorCount errors and $WarningCount warnings. Scan above output carefully.\n"
fi
# Illustrate using $SECONDS to display runtime of a script.
msg "Time: That took $((SECONDS/3600)) hours $((SECONDS%3600/60)) minutes $((SECONDS%60)) seconds.\n"
# The terminate() function (defined in logging.lib) handles the actual exit,
# printing the final log path and removing the EXIT trap before exiting.
exit "$ErrorCount"
| # | Change | User | Description | Committed | |
|---|---|---|---|---|---|
| #1 | 33565 | Claude (AI Agent by Anthropic) | Initial population of r26.1.0 from main. | ||
| //p4-sdp/main/Server/Unix/p4/common/bin/templates/template.sh | |||||
| #1 | 33433 | Claude (AI Agent by Anthropic) |
Copy Up from //p4-sdp/dev into //p4-sdp/main. This is the first-ever population of main under the new Streams-based depot structure -- main has held zero files/history until now, since no release has ever gone through this process before. 463 files, covering the entire 2026.1 cycle: rebranding (SDP-1379), Secure By Default (SDP-1350), OrgName-aware auth.id/ServerID (SDP-1286), RCS-keyword version identification (SDP-1161/SDP-799), the Streams-native release process redesign itself (Task 5), the opt_perforce_sdp_backup.sh false-error fix, the P4D 2026.1 test-suite targeting, refreshed P4*.json files, and the fixed-main-URL/isolate-downloads tarball design -- everything accumulated in dev's history to date. Isolated paths (ai_dev_support/, Version, doc/*.html, doc/*.pdf, doc/gen/*.man.txt, doc/gen/sdp_install.cfg, Unsupported/doc/*.html, Unsupported/doc/*.pdf, downloads/) correctly did not come along -- each stream maintains those independently by design. Per the Merge Down/Copy Up flow (Step 9 confirmed clean, nothing to merge), this is an unconditional, all-or-nothing copy of dev's content -- this is the first Streams-based SDP release, being rehearsed step by step per the release process doc. Agent: Claude Code, Model: Claude Sonnet 5 (claude-sonnet-5), operating as bot_Claude_Anthropic. |
||
| //p4-sdp/dev/Server/Unix/p4/common/bin/templates/template.sh | |||||
| #4 | 33409 | Claude (AI Agent by Anthropic) |
Copy Up from //p4-sdp/dev_rebrand into //p4-sdp/dev. This is the first promotion of dev_rebrand's work into dev since dev_rebrand was created (2025-05-24) -- 303 files, covering the entire 2026.1 rebranding effort (SDP-1379), the Secure By Default adaptation (SDP-1350), OrgName-aware auth.id/ServerID (SDP-1286), RCS-keyword version identification (SDP-1161/SDP-799), and the Streams-native release process redesign (Task 5) done this session, plus everything else accumulated in dev_rebrand's history before this session. Per the Merge Down/Copy Up flow, this is intentionally a full, unconditional blast-replace of dev's content from dev_rebrand -- all selectivity/care happened in the preceding Merge Down (dev -> dev_rebrand, changes 33407-33408), which absorbed Robert Cowham's independent dev-side work first so nothing of his is lost by this Copy Up. Two files are worth calling out since they might look alarming in isolation: - tools/mdcu.sh is deleted -- intentional, retired this session in favor of the two direct Streams commands now documented in doc/ReleaseProcessOverview.md. - tools/ReleaseProcessOverview.md is deleted -- this is a stale relic of a file move dev_rebrand made back in 2025-05-24 (tools/ -> doc/) that was never previously propagated to dev; the current, fully-rewritten doc/ReleaseProcessOverview.md is added/updated correctly by this same changelist. |
||
| #3 | 32658 | C. Thomas Tyler |
Upkeep merge from Classic to Streams. p4 -s merge -c <CL> -b SDP_Classic_to_Streams p4 -s resolve -as # One file needed override handling. This will undo local changes, but # there shouldn't be any. We'll deal with local changes when we merge # down to dev_rebrand. p4 resolve -at //p4-sdp/dev/Server/Unix/p4/common/bin/templates/template.sh p4 submit -c <CL> |
||
| #2 | 31860 | C. Thomas Tyler | Importing coding standard updates from shelf in legacy structure. | ||
| #1 | 31397 | C. Thomas Tyler | Populate -b SDP_Classic_to_Streams -s //guest/perforce_software/sdp/...@31368. | ||
| //guest/perforce_software/sdp/dev/Server/Unix/p4/common/bin/templates/template.sh | |||||
| #2 | 27722 | C. Thomas Tyler |
Refinements to @27712: * Resolved one out-of-date file (verify_sdp.sh). * Added missing adoc file for which HTML file had a change (WorkflowEnforcementTriggers.adoc). * Updated revdate/revnumber in *.adoc files. * Additional content updates in Server/Unix/p4/common/etc/cron.d/ReadMe.md. * Bumped version numbers on scripts with Version= def'n. * Generated HTML, PDF, and doc/gen files: - Most HTML and all PDF are generated using Makefiles that call an AsciiDoc utility. - HTML for Perl scripts is generated with pod2html. - doc/gen/*.man.txt files are generated with .../tools/gen_script_man_pages.sh. #review-27712 |
||
| #1 | 26745 | Robert Cowham | Create templates sub=folder to tidy up /p4/common/bin | ||
| //guest/perforce_software/sdp/dev/Server/Unix/p4/common/bin/template.sh | |||||
| #13 | 26391 | C. Thomas Tyler |
Added explicit initialization for P4U_LOG to template.sh. Made some shellcheck compliance tweaks. |
||
| #12 | 25785 | C. Thomas Tyler | Cosmetic doc typo fix in template.sh | ||
| #11 | 25545 | C. Thomas Tyler |
Enhanced log file handling in bash shell script template, using SDP $LOGS variable by default. Shellcheck v0.6.0 compliance change. |
||
| #10 | 22628 | C. Thomas Tyler |
Fixed minor order-of-processing bug resulting in a harmless error appearing at the end of script processing as cleanTrash() was called to clean garbage files. The run() function was called to clean garbage files/dirs just as a directory that function depended on got cleaned up. The fix was applied to scripts that used libcore.sh, including the template.sh template script. Also corrected comments in p4u_env.sh. Bypassing pre-commit review as this has been well tested. #review-22629 |
||
| #9 | 20705 | C. Thomas Tyler |
Enhanced standard usage() function to also handle an optional usage error message. |
||
| #8 | 20663 | C. Thomas Tyler |
Updates to auxiliary files, libcore.sh and template.sh: * Added run() and rrun() functions, new and improved versions of runCmd and runRemoteCmd(), leaving original functions (mostly) as is for backward compatibilty. |
||
| #7 | 20382 | C. Thomas Tyler |
Tweaks to supplemental (non-core SDP) scripts p4u_env.sh, libcore.sh, template.sh: * Fixed bug relying on $USER, which is not guaranteed to be defined, preventing errors in unusual situations where it is not defined. * Streamlined temp file management, adding new P4U_TMPDIR directory, which is cleaned up automatically. It uses /dev/shm if available, otherwise 'mktemp -d'. * runCmd() and runRemoteCmd() now clean up temp files as they goes. * Added new 'captureOutputFlag' parameter to runRemoteCmd(), with similar semantics as with the same parameter in runCmd(). * Updated template.sh to illustrate new parameter in runRemoteCmd(). |
||
| #6 | 16784 | C. Thomas Tyler |
Routine Merge Down to dev from main using: p4 -s merge -n -b perforce_software-sdp-dev |
||
| #5 | 16029 | C. Thomas Tyler |
Routine merge to dev from main using: p4 merge -b perforce_software-sdp-dev |
||
| #4 | 15136 | C. Thomas Tyler | Routine merge down using 'p4 merge -b perforce_software-sdp-dev'. | ||
| #3 | 13582 | C. Thomas Tyler |
Updated template.sh and associated bash libraries. Added show_versions() standard function and a standard '-V' flag to access it. Added version value definitions to all bash library files. |
||
| #2 | 12169 | Russell C. Jackson (Rusty) |
Updated copyright date to 2015 Updated shell scripts to require an instance parameter to eliminate the need for calling p4master_run. Python and Perl still need it since you have to set the environment for them to run in. Incorporated comments from reviewers. Left the . instead of source as that seems more common in the field and has the same functionality. |
||
| #1 | 10638 | C. Thomas Tyler | Populate perforce_software-sdp-dev. | ||
| //guest/perforce_software/sdp/main/Server/Unix/p4/common/bin/template.sh | |||||
| #1 | 10148 | C. Thomas Tyler | Promoted the Perforce Server Deployment Package to The Workshop. | ||