#!/usr/bin/env bash
# Build patched tarfiles.

# We cannot fail.
set -e

# Remember where we are.
pwd=$PWD
release=$pwd/../../Release

# Pull in the current version number.
if [ "X$1" = "X-v" ]
then	shift
	version=$1
	shift
else	source x3270/version.txt
fi
base_version=${version%.*}

# Define the product list.
if [ $# -gt 0 ]
then	products="$*"
else	products="x3270 s3270 c3270 tcl3270 pr3287"
fi

# Figure out the patch level of the release.  That's the highest-numbered
# patch of any of the patches we find.  Note that so they sort as text,
# patch numbers are two digits, with an optional leading zero.  The patch level
# appended to the version number, however, doesn't have the zero.

#pl=0
#for product in $products
#do	patch_pattern="$release/Patches/$product-$version-*.txt"
#	patches=$(echo $patch_pattern)
#	if [ "$patches" != "$patch_pattern" ]
#	then	for patch in $patches
#		do	p=${patch##*-}
#			p=${p%.txt}
#			p=${p#0}
#			if [ $p -gt $pl ]
#			then	pl=$p
#			fi
#		done
#	fi
#done
#echo "Patch level is $pl."

# Now make tarballs from the patched versions.

for product in $products
do	patch_pattern="$release/Patches/$product-$version-*.txt"
	patches=$(echo $patch_pattern)
	if [ "$patches" != "$patch_pattern" ]
	then	echo "Constructing $product..."

	    	pl=0
		for patch in $patches
		do	p=${patch##*-}
			p=${p%.txt}
			p=${p#0}
			if [ $p -gt $pl ]
			then	pl=$p
			fi
		done
		echo "Patch level for $product is $pl."

		tdir=/usr/tmp/$product
		rm -rf $tdir
		mkdir $tdir
		cd $tdir
		tar -xzf $release/$product-$version.tgz
		for patch in $patches
		do	patch -p0 <$patch
		done
		cd $product-$base_version
		sed "s/^version=\"$version/&p$pl/" version.txt >v2
		chmod -w v2
		rm -f version.txt
		mv v2 version.txt
		if [ -f $pwd/x3270/README.p$pl ]
		then	cp -p $pwd/x3270/README.p$pl .
		fi
		cd ..
		tarball=$release/$product-${version}p$pl.tgz
		tar -czf $tarball $product-$base_version
		chmod -w $tarball
		cd $pwd
		rm -rf $tdir
	fi
done
