#!/bin/bash
#==============================================================================
# Copyright and license info is available in the LICENSE file included with
# the Helm Management System (HMS), and also available online:
# https://workshop.perforce.com/projects/p4-hms/main/LICENSE
set -u

# Generate an SDP instance-specific variant of the generic
# P4Broker config file, suitable for use with HMS Data Leakage
# Protection (DLP) Package.  Display to standard output.

# Usage: In these examples, replace 'N' with SDP instance name.
# cd /p4/common/config
# /p4/common/bin/gen_dlp_broker_cfg.sh N > p4_N.broker.cfg.ToBeReviewed
#
# After reviewing, remove the .ToBeReviewed suffix. Alternately, blend the
# generated content in an existing broker configuration file.

export SDP_INSTANCE=${1:-${SDP_INSTANCE:-Unset}}

if [[ "$SDP_INSTANCE" == Unset ]]; then 
   echo "Instance parameter not supplied." 
   echo "You must supply the SDP instance as a parameter to this script." 
   exit 1 
fi 

source /p4/common/bin/p4_vars "$SDP_INSTANCE"
declare BrokerLogLevel=1
declare BrokerConfigTemplate=p4_N.broker.cfg.t
declare P4CodeReviewUser=swarm
declare DLPVersionFile=Version
declare DLPVersion=

if [[ ! -r "$BrokerConfigTemplate" ]]; then
   echo "Error: Could not find broker config template: [$PWD/$BrokerConfigTemplate]."
   exit 1
fi

if [[ ! -r "$DLPVersionFile" ]]; then
   echo "Error: Could not find DLP Version file [$PWD/$DLPVersionFile]."
   exit 1
fi

DLPVersion=$(cat $DLPVersionFile)

sed -e "s|__P4PORT__|$P4PORT|g" \
   -e "s|__P4USER__|$P4USER|g" \
   -e "s|__P4BROKERPORT__|$P4BROKERPORT|g" \
   -e "s|__P4BINDIR__|${P4BIN%/*}|g" \
   -e "s|__BROKER_LOG_LEVEL__|$BrokerLogLevel|g" \
   -e "s|__LOGS__|$LOGS|g" \
   -e "s|__MAILTO__|$MAILTO|g" \
   -e "s|__SWARM_USER__|$P4CodeReviewUser|g" \
   -e "s|__DLP_VERSION__|$DLPVersion|g" \
   "$BrokerConfigTemplate"
