#!/bin/bash
#
# Import updates from the somewhat excentric freeswan distribution.
#
# Freeswan patches the kernel with a "smart" patch script.  This 
# script cleans up after freeswan's "smart" patching.
#
# import-freeswan.sh <int-kernel-dir> <freeswan-dir>
# 
# int-kernel-dir is the full path to a directory patched with the international # kernel patch, but without the freeswan patches.  freeswan-dir is where the 
# freeswan distribution is located.

INT=$1
FREESWAN=$2
# strip trailing slashes
INT=${INT%/}
FREESWAN=${FREESWAN%/}

if [ ! -e $INT -o ! -e $FREESWAN ]; then
	echo "Either $INT or $FREESWAN are missing!"
fi

mkdir -p $INT.freeswan
(cd $INT.freeswan; lndir ../`basename $INT` .)

(cd $FREESWAN; make patches KERNELSRC=$INT.freeswan)
find $INT.freeswan \( \( -name '*.ipsecmd5' \) -o \( -name '*.preipsec' \)  \
	-o \( -name '*.wipsec' \) -o \( -name '*.mangled' \) \) -print | 
	while read a; do 
		echo "Removing $a ..."
		rm $a;
	done


#(cd $FREESWAN; make klink KERNELSRC=$INT.freeswan)
cp -R $FREESWAN/klips/net/ipsec $INT.freeswan/net/ipsec


# The kernel part of freeswan is referring to ../../../lib/freeswan.h
# which is something we have to fix.
# Also the Makefile is referring to ../../../lib/libkernel.a and
# ../../../libdes.a
# We have to move the lib directory from the freeswan distribution
# into the kernel distribution and fix the references.
cp -R $FREESWAN/lib $INT.freeswan/net/ipsec/
find $INT.freeswan/net/ipsec -follow -iname '*.[ch]' -o -name Makefile | 
	while read a; do
		perl -pi -e 's/\.\.\/\.\.\/\.\.\/lib/lib/' $a 
	done

# Now the makefile in net/ipsec is extremely flawed.  It depends on
# ../../../lib/libdes.a (now lib/libdes.a), but it has no rule to make
# that library.  So we patch the Makefile somewhat.
perl -pi -e 'if (m/DESLIB=lib/) { print "$_\n\$(DESLIB):\n\t( cd lib; \$(MAKE) libdes.a )\n\n" }' $INT.freeswan/net/ipsec/Makefile

# Fix another bug in the freeswan-1.1/lib/Makefile file.  Inadequate
# quoting of the $(CC) variable.
perl -pi -e 's/\$\(CC\)/\"\$\(CC\)\"/' $INT.freeswan/net/ipsec/lib/Makefile


# references to ../../../lib to point to lib

diff -urN $INT $INT.freeswan > $INT/../`basename $INT`.freeswan.patch 
