#!/bin/sh
#
#	$Id: gmtpatch.sh,v 1.2 2009/10/23 18:32:37 remko Exp $
#
#	gmtpatch - Manage installation of GMT patches between releases
#
if [ ${#} -ne 1 ]; then
	echo "usage: gmtpatch TREE" >&2
	echo "	(TREE is usually 4 for GMT 4.x)"
	exit -1
fi
TREE=$1

# Make sure curl is available

x=`type -t curl`
if [ "x$x" = "x" ]; then
	echo "curl is not installed but needed by gmtpatch." >&2
	echo "[See http://curl.haxx.se for more information]"  >&2
	exit -1
fi

if [ -f gmtpatch.sh ] & [ -f ../gmt_bench-marks ]; then	# Make sure we are in GMT/
	cd ..
fi

# Make sure the patch directory exists
mkdir -p .gmtpatchdir

# Get ftp site
site=`grep GMT_site src/config.mk | awk '{print $3}'`

# Get the list of available patches

curl ftp://$site/gmt/$TREE/errata/patches.lis --remote-name

# See if there are some we haven't installed already

comm -23 patches.lis .gmtpatchdir/patches.lis > files.lis

if [ -z files.lis ]; then
	echo "gmtpatch.sh: No new updates available"  >&2
	exit 1
fi

n=0
while read name; do	# Install one patch at the time
	n=`expr $n + 1`
	echo "gmtpatch.sh: Patching $name"
	curl ftp://$site/pub/gmt/$TREE/errata/$name --remote-name
	patch -p0 -N < $name
	mv $name .gmtpatchdir
done < files.lis
(cd .gmtpatchdir; ls *.txt > patches.lis)

echo "gmtpatch.sh: $n patches applied"  >&2
echo "gmtpatch.sh: You may now run make install"  >&2
