#!/bin/bash
set -u

# Make it so Sample Depot users bruno and earl have a password.
# Start state: Bruno may or may not already have a password set.
# Just attempt to set it and ignore errors if already set.

#==============================================================================
# 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 OverrideCfgValue=0
declare CfgValue=
declare P4DVersionString=
declare P4DMajorVersion=
declare P4DBuild=
declare P4D_VERSION=

# shellcheck disable=SC1091
source /p4/common/bin/p4_vars "$SDPInstance"

# Setting a brand new password (bruno and/or earl may each be getting one for
# the first time here) while dm.user.resetpassword=1 immediately flags that
# new password as needing a reset -- the same chicken-and-egg this SDP already
# works around in mkrep.sh; mirror that same temporarily-disable/restore
# pattern here.
CfgValue=$(p4 -ztag -F %Value% configure show dm.user.resetpassword)
if [[ "$CfgValue" == 1 ]]; then
   OverrideCfgValue=1
   echo "Warning: dm.user.resetpassword is set to 1; temporarily setting to 0 while setting passwords."
   p4 configure set dm.user.resetpassword=0
fi

for user in bruno earl; do
   echo "As user $P4USER, setting password for user '$user'."
   yes "$(cat "$SDP_ADMIN_PASSWORD_FILE")" | p4 -s passwd "$user"

   echo "Logging in user '$user' after password change."
   p4 login -a "$user"
done

if [[ "$OverrideCfgValue" -eq 1 ]]; then
   P4DVersionString=$(p4 -ztag -F %serverVersion% info -s 2>/dev/null)
   P4DMajorVersion=$(echo "$P4DVersionString" | cut -d / -f 3)
   P4DBuild=$(echo "$P4DVersionString" | cut -d / -f 4 | cut -d ' ' -f 1)
   P4D_VERSION="${P4DMajorVersion}.${P4DBuild}"

   # shellcheck disable=SC2072
   if [[ "$P4D_VERSION" > "2026.1" ]]; then
      echo "Unsetting dm.user.resetpassword back to default value."
      p4 configure unset dm.user.resetpassword
   else
      echo "Setting dm.user.resetpassword back to original value of 1."
      p4 configure set dm.user.resetpassword=1
   fi
fi
