#!/bin/sh

# Parameters:
#        $1 = Change list description
#        $2 = client spec.

echo "Executing $0 "$@""

stat=0

if [ $# -lt 1 -o $# -gt 2 ]
then
   echo
   echo $0, Error: Incorrect number of parameters
   echo The parameters received were "$@"
   exit 1
fi


if [ "$DEBUG" = "0" ]
then
   set -vx
fi

if [ x$WORK_DIR = x ]
then
    WORK_DIR="."
    echo "WORK_DIR undefined. Using current directory `pwd`"
fi

if [ x$LOG_DIR = x ]
then
    LOG_DIR="."
    echo "LOG_DIR undefined. Using current directory `pwd`"
fi


opt=""

# Get client definition.
eval `p4 set | grep P4CLIENT | awk '{print $1}'`

if [ $# -eq 2 ]
then
# set command to use client $2
   opt="-c $2"
   P4CLIENT=$2
fi

trap "$0, Received signal. Cleaning up; rm $WORK_DIR/change.txt" 1 2 15

# Do not use -s parameter.  It will corrupt change.txt with info: edits.
p4 $opt change -o | sed 's/<enter description here>/'"$1"'/' > \
   $WORK_DIR/change.txt

if [ $? -ne 0 ]
then
   echo "$0, Error: Could not modify changelist. Submit aborted"
   exit 1
fi

echo Output being sent to $LOG_DIR/submit.log
echo "********** Build date `date` **********" >> $LOG_DIR/submit.log


p4 $opt -s opened | grep ^error:
p4sub_stat=$?


if [ $p4sub_stat -ne 0 -a "$TEST" != "0" ]
then
   p4 $opt -s submit -i < $WORK_DIR/change.txt >> $LOG_DIR/submit.log 2>&1
   stat=$?

   if [ $stat -ne 0 ]
   then
      echo $0, Error: Command p4 $opt -s submit -i < $WORK_DIR/change.txt failed
      echo "see $LOG_DIR/submit.log"
   fi

elif [ "$TEST" = "0" ]
then
   echo "$0, Warning: $1 not submitted due to test run."
else
   echo "$0, Warning: $1 not submitted due to no files opened for $P4CLIENT"
fi


rm $WORK_DIR/change.txt

exit $stat