#!/bin/bash
set -u

#------------------------------------------------------------------------------
# Version ID Block. Relies on +k filetype modifier.
# VersionID='$Id: //p4-sdp/dev_c2s/Server/Unix/p4/common/bin/triggers/enforce_change_type.sh#2 $ $Change: 31472 $'

# Install in triggers table wtih a pair of entries like this:
# Triggers:
#    company.protectform form-in change "/p4/common/site/bin/triggers/enforce_change_type.sh %formfile%"
#    company.protectform change-commit //... "/p4/common/site/bin/triggers/enforce_change_type.sh %changelist%"

# This will take either a changelist number (all numeric) or a temp file path (the form file), and make
# adjustments as needed to ensure all changelists are restricted. This works in conjunction with having
# the 'defaultChangeType' configurable set to 'restricted'. This script ensures there is no sneaking around
# the policy.

# Future Proofing consideration: Currently, the only possible values for the Type field of a changelist
# are 'public' and 'restricted'. This is not expected to change. If it ever did for some reason, this
# code would need review.

declare -i ErrorCount=0
declare Parameter=${1:-}
declare FormFile=
declare Changelist=
declare TmpFile=

function msg () { echo -e "$*"; }
function errmsg () { msg "\\nError: ${1:-Unknown Error}\\n"; ErrorCount+=1; }
function bail () { errmsg "${1:-Unknown Error}"; exit "$ErrorCount"; }
source /p4/common/bin/p4_vars 1


if [[ -n "$Parameter" ]]; then
   if [[ "$Parameter" =~ ^[0-9]+$ ]]; then
      Changelist="$Parameter"
   else
      FormFile="$Parameter"
   fi
else
   bail "Bad usage: FormFile parameter required."
fi

if [[ -n "$FormFile" ]]; then
   [[ -r "$FormFile" ]] || bail "FormFile $FormFile does not exist."

   if grep -E -q '^Type:\s*public' $FormFile; then
      sed -E -i -e 's/^Type:.*$/Type: restricted/g' "$FormFile"
   fi
else # Deal with submitted CL.
   # Ensure change type is restricted.
   TmpFile=$(mktemp)
   p4 change -o "$Changelist" > "$TmpFile" ||\
      bail "Could not do: p4 change -o $Changelist"

   if grep -E -q '^Type:\s*public' "$TmpFile"; then
      p4 --field Type=restricted change -o "$Changelist" | p4 change -f -i
   fi

   rm -f "$TmpFile"
fi

exit 0
