#!/bin/sh

# Name		: /public/scripts/integbychg
# Purpose	: Integrate from one configuration to another according to 
#		  a given submitted changelist number.
# By		: Yariv Sheizaf
# Date		: 19.7.2001


echo ""
echo "Submitted changelist number ?"
echo ""
read ANS

CHG=$ANS


p4 change -o $CHG 1>/dev/null 2>&1
if [ "$?" != "0" ]
then
	echo ""
	echo "Changelist No. "$CHG" is not exist. Exit..."
	echo ""
	exit 1
fi

ISSUBMITTED=`p4 describe $CHG | /usr/bin/head -1 | awk '{print $NF}'`
if [ "$ISSUBMITTED" = "*pending*" ]
then
	echo ""
	echo "Changelist No. "$CHG" is still pending. Exit..."
	echo ""
	exit 1
fi

## Create new pending changelist 
p4 change -o $CHG | sed 's/'$CHG'/new/' | p4 change -i > $$.newchg

NEWCHG=`awk '{print $2}' $$.newchg`


echo ""
echo "Target configuration name ?"
echo ""
read ANS
TRGCNF=$ANS

## Check configuration existing in P4 DB
ISCNF="n"
for i in `p4 dirs //Globecom/\* | awk -F/ '{print $NF}'`
do
	if [ "$i" = "$TRGCNF" ]
	then
		ISCNF="y"
	fi
done
if [ "$ISCNF" = "n" ]
then
	echo ""
	echo $TRGCNF" is not a valid configuration. Exit..."
	echo ""
	exit 1
fi


p4 describe -s $CHG | grep "^... //" | awk -F# '{print $1}' | sed 's/... //' | sed 's/ /@@@/g' > $$.flist

IS1CNF=`awk -F/ '{print $4}' $$.flist | sort | uniq | wc -l | awk '{print $1}'`
if [ "$IS1CNF" != "1" ]
then
	echo ""
	echo "There are more than one source configuration in changelist No. "$CHG
	echo ""
	exit 1
fi

SRCCNF=`awk -F/ '{print $4}' $$.flist | sort | uniq`
if [ "$SRCCNF" = "$TRGCNF" ]
then
	echo ""
	echo "Source and target configuration are identical. Exit..."
	echo ""
	exit 1
fi


for i in `cat $$.flist`
do
	SRCFILE=`echo $i | sed 's/@@@/ /g'`
	TRGFILE=`echo $SRCFILE | sed 's/'$SRCCNF'/'$TRGCNF'/'`
	p4 integrate -c $NEWCHG -f -d -i -v "$SRCFILE" "$TRGFILE"
	p4 resolve -at -af "$TRGFILE"
done

p4 submit -c $NEWCHG

rm -f $$.*


echo ""
echo "Press any key to exit"
echo ""
read ANS


exit 0