#!/bin/bash

if [ "$#" -lt 4 ]; then
   echo "Incorrect number of parameters."
   echo "Usage:"
   echo "$0 SDP_INSTANCE REPLICA_NAME SVCUSER_PASSWORD MASTERPORT <mandatory>"
   exit 1
fi

export SDP_INSTANCE=$1
export REPNAME=$2
export PASSWORD=$3
export REPPORT=$4
export MANDATORY=${5:-nomandatory}

REPMASTER=$(echo $P4MASTERPORT | sed "s/\..*//")

. /p4/common/bin/p4_vars $SDP_INSTANCE

if [[ $MANDATORY == mandatory ]]; then
   $P4BIN server -o $REPNAME | sed "s/^Services:\tstandard/Services:\tforwarding-standby/" | sed "s/nomandatory/mandatory/" | sed "$ a ReplicatingFrom: ${REPMASTER}" | $P4BIN server -i
else
   $P4BIN server -o $REPNAME | sed "s/^Services:\tstandard/Services:\tforwarding-standby/" | sed "$ a ReplicatingFrom: ${REPMASTER}" | $P4BIN server -i
fi

$P4BIN configure set "${REPNAME}#P4TARGET=${REPPORT}"
$P4BIN configure set "${REPNAME}#serviceUser=svc_${REPNAME}"
$P4BIN configure set "${REPNAME}#journalPrefix=/p4/${SDP_INSTANCE}/journals.rep/p4_${SDP_INSTANCE}"
$P4BIN configure set "${REPNAME}#serverlog.file.1=/p4/${SDP_INSTANCE}/logs/audit.csv"
$P4BIN configure set "${REPNAME}#db.replication=readonly"
$P4BIN configure set "${REPNAME}#lbr.replication=shared"
$P4BIN configure set "${REPNAME}#startup.1=journalcopy -i 0"
$P4BIN configure set "${REPNAME}#startup.2=pull -L -i 0"

if ! ($P4BIN user -o svc_${REPNAME} | grep "^Type:.*service" > /dev/null); then
   $P4BIN user -o svc_${REPNAME} | sed -e "s/^User:/Type: service\nUser:/g" -e "s/ldap/perforce/g" | $P4BIN user -f -i
   echo ${PASSWORD} > passwd.txt
   echo ${PASSWORD} >> passwd.txt
   $P4BIN passwd svc_${REPNAME} < passwd.txt
   rm passwd.txt
fi

$P4BIN group -o p4-replicas|sed -e "s/^Users:/Users:\n\tsvc_${REPNAME}/g" -e "s/43200/unlimited/g" -e "s/unset/unlimited/g" | $P4BIN group -i
#$P4BIN group -o service.g|sed -e "s/^Users:/Users:\n\tsvc_${REPNAME}/g" -e "s/43200/unlimited/g" -e "s/unset/unlimited/g" | $P4BIN group -i

#if ! ($P4BIN protect -o|grep "super group service.g" > /dev/null); then
#   $P4BIN protect -o| sed -e '$a\\tsuper group service.g * //...'| $P4BIN protect -i
#fi
