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