#!/bin/sh

if [ $# -ne 3 ]
then
   echo "Error: Incorrect parameters passed to $0"
   echo "Usage: $0 <depot root> <client root> <bom file>"
   echo
   echo "<depot root> would be something like '//oware/oware21/'"
   echo "<client root> would be '//build-clifford21/oware'"
   echo "These values will be prepended to the lines in the bom file to"
   echo "create the client spec view."
   echo "<bom file> is a file list to be added to the view for the client"
   echo
   echo "Note: The behavior may be unexpected with unusual characters such as space"
   exit 1
fi

stat=0
pass1=$1
pass2=$2

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

# Enclose roots in //<root>
index=0
for i in "$1" "$2"
do
 index=`expr $index + 1`
 eval pass$count="$i"
 echo $i | grep ^/ > /dev/null || \
         eval pass$index="//$i"
 echo $i | grep /$ > /dev/null && \
         eval pass$index=`expr "$i" : '\(.*[a-z|0-9]\)'`
done

eval depot_root="$pass1"
eval client_root="$pass2"
bom_file=$3


client=`echo $client_root | awk -F/ '{print $3}'`


if [ ! -f $bom_file ]
then
    echo "$0, $bom_file does not exist"
    exit 1
fi

if [ x$WORK_DIR = x ]
then
    WORK_DIR=/tmp
fi

if [ ! -d "$WORK_DIR" ]
then
    mkdir $WORK_DIR
    stat=`expr $stat + $?`
fi


# Create the client spec.
# If a client's View is empty then create a view line first.
p4 client -o $client | tee $WORK_DIR/client.tmp | grep ^View: > /dev/null \
        || echo View: >> $WORK_DIR/client.tmp
stat=`expr $stat + $?`


bom_operator 'echo "     "' $depot_root $client_root $bom_file >> \
       $WORK_DIR/client.tmp
stat=`expr $stat + $?`

echo Modifying $client
p4 -s -c $client client -i < $WORK_DIR/client.tmp
stat=`expr $stat + $?`

exit $stat

# The following was old way. I stopped this because I'd rather assume that
# we need to add the records each time. If there are duplifcates then it is
# an error in usage.  I want to discourage the use of updating the client spec
# instead of release.bom

# Only add records that are unique.

pattern=`awk -v from=$depot_root -v to=$client_root \
        '{print "\t"from$1,to$1}' $bom_file`
stat=`expr $stat + $?`

start=off
modified=false
for i in $pattern
do
    if [ $start != "on" ]
    then
       start=on
       record=$i  
    else
       record="$record $i"
# use fgrep because it doesn't know of regular expressions.  This allows it to
# match files like *.txt.
       fgrep "$record" $WORK_DIR/client.tmp > /dev/null

       if [ $? -eq 1 ]
       then
          echo "     "$record >> $WORK_DIR/client.tmp
          modified=true
       fi

       start=off
    fi
done


if [ "$modified" = "true" ]
then
    echo $client modified
    p4 -s -c $client client -i < $WORK_DIR/client.tmp
    stat=`expr $stat + $?`
fi

exit $stat