#!/bin/bash
set -u

# This script requires outbound internet access. Depending on your environment,
# it may also require HTTPS_PROXY to be defined, or may not work at all.

# Usage: get_latest_exes.sh [<version>] [<exe1>,<exe2>,...]
#
# Typical Usage (if SDP tar extracted to /hxdepots/sdp) is
# with no arguments, e.g.:
# cd /hxdepots/sdp/exes
# ./get_latest_exes.sh
#
# If no parameters are specified, the default version and list of
# executables to get is coded below. Note that the list of exes
# is comma-delimited.
#
# Sample usage specifying version:
# ./get_latest_exes.sh r20.1
#
# Sample getting r19.2 and skipping the proxy executable, p4p:
# cd /hxdepots/sdp/exes
# ./get_latest_exes.sh r19.2 p4,p4d,p4broker
#
# Note: Only supported release are available from the Perforce
# FTP server.

function msg () { echo -e "$*"; }
function errmsg () { msg "\\nError: ${1:-Unknown Error}\\n"; ErrorCount+=1; }
function warnmsg () { msg "\\nWarning: ${1:-Unknown Warning}\\n"; WarningCount+=1; }
function bail () { errmsg "${1:-Unkonwn Error}"; exit "${2:-1}"; }

declare DefaultPerforceHelixVersion=r20.1
declare DefaultExeList="p4 p4d p4broker p4p"

declare ThisScript=${0##*/}
declare Version=1.0.3
declare -i ErrorCount=0
declare -i WarningCount=0
declare -i RetryCount=0
declare -i RetryMax=2
declare -i RetryDelay=2
declare -i RetryOK=0
declare PerforceHelixVersion="${1:-$DefaultPerforceHelixVersion}"
declare ExeList="${2:-$DefaultExeList}"
declare Platform=linux26x86_64
declare PerforceFTPBaseURL="https://ftp.perforce.com/perforce"
declare ExeURL=
declare Cmd=

msg "\\nStarted $ThisScript v$Version as $USER@${HOSTNAME%%.*} at $(date)."

for exe in $(echo "$ExeList"|tr ',' ' '); do
   msg "\\nGetting $exe ..."
   ExeURL="${PerforceFTPBaseURL}/${PerforceHelixVersion}/bin.${Platform}/$exe"
   if [[ -f "$exe" ]]; then
      chmod +x "$exe"
      msg "Old version of $exe: $("./$exe" -V | grep Rev)"
      rm -f "$exe"
   fi

   Cmd="curl -k -O $ExeURL"
   msg "Running: $Cmd"

   if $Cmd; then
      chmod +x "$exe"
      msg "New version of $exe: $("./$exe" -V | grep Rev)"
   else
      warnmsg "Failed to download $exe with this URL: $ExeURL\\nRetrying ..."
      RetryCount+=0
      while [[ "$RetryCount" -le "$RetryMax" ]]; do
         RetryCount+=1
         sleep "$RetryDelay"
         msg "Retry $RetryCount of command: $Cmd"
         if $Cmd; then
            chmod +x "$exe"
            msg "New version of $exe: $("./$exe" -V | grep Rev)"
            RetryOK=1
            break
         else
            warnmsg "Retry $RetryCount failed again to download $exe with this URL: $ExeURL"
         fi
      done

      if [[ "$RetryOK" -eq 0 ]]; then
         errmsg "Failed to download $exe with this URL: $ExeURL"
         rm -f "$exe"
      fi
   fi
done

if [[ "$ErrorCount" -eq 0 ]]; then
   msg "\\nDownloading of exes completed OK."
else
   errmsg "\\There were $ErrorCount errors attempting to download exes."
fi

exit "$ErrorCount"
