#!/bin/bash
# Checked initialization for a newly created native service user. Preserve the
# site's password-reset policy: when it requires a first-login reset, initialize
# a temporary password then perform that reset as the service user itself.
# Source after p4_vars. No passwords are passed in command arguments or files.
sdp_initialize_service_password () {
   local ServiceUser=${1:?Service user required} FinalPassword=${2:?Password required}
   local Config= Reset= InitialPassword=
   Config=$("$P4BIN" -ztag configure show dm.user.resetpassword) || return $?
   Reset=$(awk '$1 == "..." && $2 == "Value" {print $3}' <<< "$Config") || return $?
   if [[ "$Reset" != 0 && "$Reset" != 1 ]]; then
      echo 'Cannot determine dm.user.resetpassword; service password was not changed.' >&2
      return 1
   fi
   if [[ "$Reset" == 0 ]]; then
      printf '%s\n%s\n' "$FinalPassword" "$FinalPassword" | "$P4BIN" passwd "$ServiceUser"
      return $?
   fi
   InitialPassword=$(od -An -N24 -tx1 /dev/urandom | tr -d ' \n') || return $?
   [[ "$InitialPassword" =~ ^[0-9a-f]{48}$ ]] || {
      echo 'Cannot generate initial service password; service password was not changed.' >&2
      return 1
   }
   InitialPassword="SdpInit${InitialPassword}!"
   printf '%s\n%s\n' "$InitialPassword" "$InitialPassword" | "$P4BIN" passwd "$ServiceUser" || return $?
   printf '%s\n%s\n%s\n' "$InitialPassword" "$FinalPassword" "$FinalPassword" |
      "$P4BIN" -u "$ServiceUser" passwd || return $?
}
