#!/bin/bash

CVS=echo
#CVS=`which cvs`

REPOSITORY=$1
NAME=$2
NEWNAME=$3

PREFIX=patch-o-matic/$REPOSITORY/$NAME.patch
DESTDIR=patch-o-matic-ng/$NEWNAME

mkdir $DESTDIR
$CVS add $DESTDIR

# strip Author and Version from help file
cat $PREFIX.help | egrep -v Author:\|Status: > $DESTDIR/help
$CVS add $DESTDIR/help

# generate info
cat $PREFIX.help | grep Author: > $DESTDIR/info
cat $PREFIX.help | grep Status: >> $DESTDIR/info
echo Repository: $REPOSITORY >> $DESTDIR/info
$CVS add $DESTDIR/info

# ugly trick, don't know if we need all diectories yet.  but we try
# to rmdir them later, which fails in case they are not empty anymore
TRYDIRS="linux/net/ipv4/netfilter linux/include/linux/netfilter_ipv4 linux/net/ipv6/netfilter linux/include/linux/netfilter_ipv6"
for d in $TRYDIRS; do
	mkdir -p $DESTDIR/$d
done

for f in $PREFIX.makefile*; do
	postfix=$(echo "${f##$PREFIX.makefile}" | sed -e s/-/_/)
	newfile=$DESTDIR/linux/net/ipv4/netfilter/Makefile.ladd$postfix
	cp $f $newfile
done

for f in $PREFIX.config.in*; do
	postfix=$(echo "${f##$PREFIX.config.in}" | sed -e s/-/_/)
	newfile=$DESTDIR/linux/net/ipv4/netfilter/Config.in.ladd$postfix
	cp $f $newfile
done

for f in $PREFIX.ip_conntrack.h*; do
	postfix=$(echo "${f##$PREFIX.ip_conntrack.h}" | sed -e s/-/_/)
	newfile=$DESTDIR/linux/include/linux/netfilter_ipv4/ip_conntrack.h.ladd$postfix
	cp $f $newfile
done

for d in $TRYDIRS; do
	rmdir -p $DESTDIR/$d
done

cp $PREFIX $DESTDIR/linux.patch
patch -d $DESTDIR/linux -p1 -i ../linux.patch -r /dev/null -b
find $DESTDIR/linux -name \*.orig -exec rm -f \{\} \;

# add to CVS
NEWFILES=`find $DESTDIR/linux \! -path \*CVS\*`
for f in $NEWFILES; do
	$CVS add $f
done

# we need to deal with patch and configure.help manually
cp $PREFIX.configure.help $DESTDIR/configure.help

