#!/bin/bash
set -u

declare -i ErrorCount=0
declare -i Debug=0
declare -i HostCount=0
declare Timeout=5s
declare Host=
declare -i HostFailCount=0
declare -a HostFailList
declare RsyncCmd=
declare ThisHost=${HOSTNAME%%.*}
declare HostPrefix=

function msg () { echo -e "$*"; }
function dbg () { [[ "$Debug" -eq 0 ]] || msg "DEBUG: $*"; }
function errmsg () { msg "\nError: ${1:-Unknown Error}\n"; ErrorCount+=1; }
function bail () { errmsg "${1:-Unkown Error}"; exit "${2:-1}"; }

if [[ "$ThisHost" == p4c-bos-01 ]]; then
   HostPrefix=p4
elif [[ "$ThisHost" == bos-helix-01 ]]; then
   HostPrefix=helix
else
   bail "Run this on 'p4c-bos-01' (BSW Gen7+) or 'bos-helix-01' (BSW Gen6), not '$ThisHost'."
fi

for Host in ${HostPrefix}-0{2..5}; do
   echo Host="$Host"
   for Dir in /p4/common /p4/sdp; do
      RsyncCmd="rsync -e \"ssh -q\" -av \"$Dir/\" \"$Host:$Dir\""
      msg "Running: $RsyncCmd"
      # shellcheck disable=SC2086
      if ! eval timeout $Timeout $RsyncCmd; then
         errmsg "Could not do: $RsyncCmd"
         HostFailList[HostFailCount]="$Host"
         HostFailCount+=1
      fi
   done
   HostCount+=1
done

if [[ "$ErrorCount" -eq 0 ]]; then

   msg "\nSuccess: Push SDP completed OK to $HostCount hosts."
else
   msg "\nPush SDP attempted to $HostCount hosts; $ErrorCount errors encountered for these hosts: ${HostFailList[*]}."
fi
