#!/bin/bash

# Detect if the command was precisely 'p4 stream -o'.  If so, process, otherwise
# just PASS.  Process means do 'p4 stream -o' and supply the current stream name.

declare -i StreamCommand=0
declare -i ArgCountIsOne=0
declare -i FlagIsDashO=0
declare -i StreamFound=0
declare Workspace=
declare Stream=
declare tmpFile="/tmp/p4_stream-o.rewrite.$$.$RANDOM"
### declare log=/tmp/p4_stream-o.log
export P4BIN=${P4BIN:-p4}

/bin/rm -f $tmpFile
### /bin/rm -f $log

while read line; do
   if [[ $line == "command: stream" ]]; then
      StreamCommand=1
      echo $line >> $tmpFile
   elif [[ $line == "argCount: 1" ]]; then
      ArgCountIsOne=1
      echo argCount: 2 >> $tmpFile
   elif [[ $line == "workspace: "* ]]; then
      Workspace=${line#workspace: }
      Stream=$($P4BIN -ztag -F %Stream% client -o $Workspace 2>/dev/null)
      [[ -n "$Stream" ]] && StreamFound=1
   elif [[ $line == "Arg0: -o" ]]; then
      FlagIsDashO=1
      echo -e "Arg0: -o\nArg1: $Stream" >> $tmpFile
   else
      echo $line >> $tmpFile
   fi
done < /dev/stdin

if [[ $StreamCommand -eq 1 && $ArgCountIsOne -eq 1 && $FlagIsDashO -eq 1 && $StreamFound -eq 1 ]]; then
   echo "action: REWRITE"
   ### echo "action: REWRITE" > $log
   cat $tmpFile
   ### cat $tmpFile >> $log
   /bin/rm -f $tmpFile
   exit 1
else
   echo "action: PASS"
   ### echo "action: PASS" > $log
   /bin/rm -f $tmpFile
   exit 0
fi

exit 2
