#!/bin/bash

declare -i firstLineNumber
declare -i lastLineNumber
declare -i diffLineNumber

checkStanzaExists()
{
	# we want to check if the file has the license stanza.
	# That stanza shoud start with lines:
	# /*  BEGIN software license
	# *
	# * msXpertSuite - mass spectrometry software suite
	# and end with lines:
	# *  You should have received a copy of the GNU General Public License
	# *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
	# */

	# Get the line number of the first stanza line.

	firstLineNumber=$(grep -n 'BEGIN software license' \
		$1 \
		| sed 's/:.*$//g')

	lastLineNumber=$(grep -n 'END software license' \
		$1 \
		| sed 's/:.*$//g')

	# Increment for the last line with */

	lastLineNumber+=1

	diffLineNumber=${lastLineNumber}-${firstLineNumber}

	printf "File $1: firstLineNumber=${firstLineNumber} ; \
		lastLineNumber=${lastLineNumber}\ ;
	diffLineNumber=${diffLineNumber}\n"

	if [ ${diffLineNumber} -lt 28 ]
	then
		printf "Warning: the license stanza for file %b does not have the proper \
			line count." $1
		return 1
	fi

	return 0
}


checkStanzaExists $1
result=$?

printf "checkStanzaExists result: ${result}\n" 

if [ "${result}" != "0" ]
then
	echo "The file ${1} does not have the proper license stanza. Stopping processing."
	exit 1
fi

# At this point go on.

# sed -i '1,28d' $1
delCommand="sed -i '${firstLineNumber},${lastLineNumber}d' $1"
eval ${delCommand}

result=$?

printf "delCommand result: ${result}\n"

if [ "${result}" != "0" ]
then
	exit 1
fi

# At this point go on.

# Make a copy of the file
cp $1 $1-tmp

if [ "$?" != "0" ]
then
	printf "Failed to copy source file $1 to $1-tmp\n"
	exit 1
fi

cat license-stub.txt > $1

if [ "$?" != "0" ]
then
	printf "Failed to cat stub file to $1\n"
	exit 1
fi

cat $1-tmp >> $1

if [ "$?" != "0" ]
then
	printf "Failed to cat tmp file to $1\n"
	exit 1
fi

rm $1-tmp

exit 0
