#!/bin/bash
set -u

#==============================================================================
# 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 -i ErrorCount=0
declare -i Debug=${DEBUG:-0}
declare ThisScript=${0##*/}
declare ScriptInstanceVarsTemplateFormatVersion=
declare ScriptP4VarsTemplateFormatVersion=
declare FileInstanceVarsTemplateFormatVersion=
declare FileP4VarsTemplateFormatVersion=

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

ScriptInstanceVarsTemplateFormatVersion=$(p4 grep -e SDPInstanceCfgFileNewFormatVersion= //guest/perforce_software/sdp/dev/Server/Unix/p4/common/sdp_upgrade/sdp_upgrade.sh|head -1|cut -d= -f2)
dbg "ScriptInstanceVarsTemplateFormatVersion=$ScriptInstanceVarsTemplateFormatVersion"

ScriptP4VarsTemplateFormatVersion=$(p4 grep -e SDPEnvFileNewFormatVersion= //guest/perforce_software/sdp/dev/Server/Unix/p4/common/sdp_upgrade/sdp_upgrade.sh|head -1|cut -d= -f2)
dbg "ScriptP4VarsTemplateFormatVersion=$ScriptP4VarsTemplateFormatVersion"

FileInstanceVarsTemplateFormatVersion=$(p4 grep -e ^SDP_INSTANCE_VARS_FORMAT= //guest/perforce_software/sdp/dev/Server/Unix/p4/common/config/instance_vars.template|tail -1|cut -d= -f2)

FileP4VarsTemplateFormatVersion=$(p4 grep -e ^SDP_P4_VARS_FORMAT //guest/perforce_software/sdp/dev/Server/Unix/p4/common/config/p4_vars.template|tail -1|cut -d= -f2)

if [[ "$ScriptInstanceVarsTemplateFormatVersion" == "$FileInstanceVarsTemplateFormatVersion" ]]; then
   msg "Format versions match for p4_N.vars: $ScriptInstanceVarsTemplateFormatVersion"
else
   errmsg "Format version mismatch for p4_N.vars: $ScriptInstanceVarsTemplateFormatVersion (script) vs. $FileInstanceVarsTemplateFormatVersion (file)."
fi

if [[ "$ScriptP4VarsTemplateFormatVersion" == "$FileP4VarsTemplateFormatVersion" ]]; then
   msg "Format versions match for p4_vars: $ScriptP4VarsTemplateFormatVersion"
else
   errmsg "Format version mismatch for p4_vars: $ScriptP4VarsTemplateFormatVersion (script) vs. $FileP4VarsTemplateFormatVersion (file)."
fi

if [[ "$ErrorCount" -eq 0 ]]; then
   msg "\\nVerified: Formats match."
else
   msg "\\nSome formats don't match. Fix it so they do."
fi

exit "$ErrorCount"
