#!/bin/bash
set -u

# Create service user on commit (if needed).
# Start state: The super user is logged in. The ServiceUsers group exists and
# gives an unlimited ticket and super access. The ServerID of the commit may
# or may not already have a user/password.
# Goal: Create the service user if needed and add it to the group.

#==============================================================================
# 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 MasterServiceUser=
declare MasterServiceUserSpecFile=
declare -i ErrorCount=0

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

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

[[ "$SERVERID" == "$P4MASTER_ID" ]] || bail "Run only on commit server."

MasterServiceUser="svc_$SERVERID"
MasterServiceUserSpecFile="${MasterServiceUser}.user.p4s"

msg "Ensuring service user exists: $MasterServiceUser."
msg "Running: p4 -s user -f -i .LT. $MasterServiceUserSpecFile"
p4 -s user -f -i < "$MasterServiceUserSpecFile" ||\
   errmsg "Error creating service user with this spec:\\n$(cat "$MasterServiceUserSpecFile")\\n\\n"

msg "Ensuring service user is in ServiceUsers group."
p4 group -o ServiceUsers | sed '$ s/^[[:space:]]*$/\t'"$MasterServiceUser"'\n/' | p4 group -i

# shellcheck disable=SC2143
if [[ -n "$(p4 group -o ServiceUsers | grep "$MasterServiceUser")" ]]; then
   msg "Verified: User $MasterServiceUser is in ServiceUsers group."
else
   errmsg "Failed to add $MasterServiceUser to ServiceUsers group."
fi

msg "Setting password for $MasterServiceUser"
yes "$(uuidgen)" | p4 -s passwd "$MasterServiceUser"

msg "Running: p4 configure set $SERVERID#serviceUser=$MasterServiceUser"
p4 configure set "$SERVERID"#serviceUser="$MasterServiceUser"

msg "Sleeping a few seconds so this metadata can replicate to the edge."
sleep 5

if [[ "$ErrorCount" -eq 0 ]]; then
   msg "\\nDone. User $MasterServiceUser is ready to use."
else
   msg "\\nProcssing done, but user $MasterServiceUser may not be ready to use."
fi

exit "$ErrorCount"
