#!/bin/bash
set -u

#------------------------------------------------------------------------------
# Version ID Block. Relies on +k filetype modifier.
# VersionID='$Id: //p4-sdp/dev_c2s/Unsupported/Maintenance/get_swarm_info.sh#2 $ $Change: 31472 $'

declare SwarmBaseURL=
declare SwarmVersionURL=
declare SwarmVersion=
declare Cmd=
declare -i ErrorCount=0
declare -i Debug=${DEBUG:-0}

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:-Unknown Error}"; exit "${2:-1}"; }

Cmd="p4 property -n P4.Swarm.URL -l"

# If 'timeout' utility is available, use it to avoid a hang if we don't get
# a response from p4d.
[[ -n "$(command -v timeout)" ]] && Cmd="timeout 10s $Cmd"

SwarmBaseURL=$($Cmd)

if [[ "$SwarmBaseURL" =~ ^P4.Swarm.URL ]]; then
   SwarmBaseURL=${SwarmBaseURL##* = }
   SwarmVersionURL="$SwarmBaseURL/api/version"
   dbg "SwarmBaseURL=$SwarmBaseURL\\nSwarmVersionURL=$SwarmVersionURL"
   SwarmVersion=$(curl -s "$SwarmVersionURL" | cut -d ':' -f 3)
   # SwarmVersion should look like:
   if [[ "$SwarmVersion" =~ SWARM ]]; then
      dbg "Raw SwarmVersion=$SwarmVersion"
      SwarmVersion=$(echo "$SwarmVersion" | sed -e 's@\\@@g' -e 's@SWARM/@SWARM @g' -e 's@^"@@g' -e 's@".*@@g')
      msg "Swarm Version is: $SwarmVersion"
   else
      errmsg "Could not get Swarm version with: 'curl -s \"$SwarmVersionURL\"'."
   fi
else
   msg "Could not get Swarm base URL with: $Cmd\\nAssuming Swarm does not exist here."
fi

