#!/bin/sh

set -x

if [ ! -f ../isapplied ]
then
    echo "Please run $0 from the patch-o-matic directory!"
    exit 1
fi

for x in converted-patch-o-matic-patch newnat5.tgz
do
    if [ ! -f $x ]
    then
	echo Missing $x, exiting...
	exit 1
    fi
done

mkdir tmp
mkdir pending
egrep 'PENDING_PATCHES[:+]*=' ../Makefile | while read LINE
do
    LINE=${LINE%%#*}
    LINE=${LINE##PENDING_PATCHES*=}
    for x in $LINE
    do
	# Ugly
	if [ -f $x.ipv6 ]
	then
	    mv $x.ipv6* tmp
	    mv ${x}* pending
	    mv tmp/$x.ipv6* .
	else
	    mv ${x}* pending
	fi
    done
done

mkdir base
egrep 'MOSTOFPOM_PATCHES[:+]*=' ../Makefile | while read LINE
do
    LINE=${LINE%%#*}
    LINE=${LINE##MOSTOFPOM_PATCHES*=}
    for x in $LINE
    do
	# Ugly
	if [ -f $x.ipv6 ]
	then
	    mv $x.ipv6* tmp
	    mv ${x}* base
	    mv tmp/$x.ipv6* .
	else
	    mv ${x}* base
	fi
    done
done
echo "pending base" > base/SUITE
echo "Patches which are working fine together." > base/DESCRIPTION

mkdir extra
mv *.patch* extra
rm -f extra/h323-conntrack-nat*
echo "pending base extra" > extra/SUITE
echo "Patches which are working fine together plus patches which might break other ones." > extra/DESCRIPTION

mkdir newnat
patch -p1 < converted-patch-o-matic-patch
echo "pending newnat base extra" > newnat/SUITE
echo "Patch suite based on the new NAT API." > newnat/DESCRIPTION

mv *.tgz newnat
cd newnat
for x in *.tgz
do
    tar xzf $x
    rm $x
done
cd ..
rmdir tmp

echo "Ready!"
echo "Now you can run first './runme'"
echo "then './runme suite'"
