#!/bin/bash
set -u

# Start state: User perforce may or may not have a valid
# ticket on all servers in the fleet. It is inteded to be called on
# p4c-bos-01.
# Goal: Ensure primrary super user is logged in everywhere.

#==============================================================================
# Declarations and Environment

# Version ID Block. Relies on +k filetype modifier.
#------------------------------------------------------------------------------
# shellcheck disable=SC2016
declare VersionID='$Id: //p4-sdp/dev_c2s/Server/Unix/p4/common/bin/mkrep.sh#3 $ $Change: 31580 $'
declare VersionStream=${VersionID#*//}; VersionStream=${VersionStream#*/}; VersionStream=${VersionStream%%/*};
declare VersionCL=${VersionID##*: }; VersionCL=${VersionCL%% *}
declare Version=${VersionStream}.${VersionCL}
[[ "$VersionStream" == r* ]] || Version="${Version^^}"

declare SDPInstance=${1:-${SDP_INSTANCE:-1}}
declare -i LoginOKCount=0
declare -i ErrorCount=0

function msg () { echo -e "$*"; }
function errmsg () { msg "\\nError: ${1:-Unknown Error}\\n"; ErrorCount+=1; }

msg "Calling: $PWD/create_master_service_user.sh"
if $PWD/create_master_service_user.sh; then
   msg "Verified: create_master_service_user.sh reported OK."
else
   errmsg "Errors were reported by create_master_service_user.sh."
fi

for host in p4-0{1..5}; do
   msg "Logging in primary super user on host $host."
   if timeout 20s ssh -q "$host" /p4/common/bin/p4login "$SDPInstance" -v; then
      LoginOKCount+=1
   else
      errmsg "Failed to do 'p4login $SDPInstance -v' on host $host."
   fi

   msg "Logging in replication service user on host $host."
   if timeout 20s ssh -q "$host" /p4/common/bin/p4login "$SDPInstance" -v -service; then
      LoginOKCount+=1
   else
      errmsg "Failed to do 'p4login $SDPInstance -v -service' on host $host."
   fi
done

if [[ "$ErrorCount" -eq 0 ]]; then
   msg "SUCCESS: Login OK on all targeted hosts."
else
   errmsg "Logins failed on $ErrorCount hosts; OK on only $LoginOKCount hosts."
fi

exit "$ErrorCount"
