#!/bin/sh

# common apply/unpatch script for the Debian PowerPC patch

if ! test -d Documentation -a -d kernel; then
    echo >&2 "This does not look like a kernel top level directory, exiting."
    exit 1
fi

version=2.6.7-3ubuntu3
upstream=2.6.7
dir=/usr/src/kernel-patches/powerpc/$upstream/patches

patch="patch -s -l -p1"
if test "$1" = "unpatch"; then
    patch="$patch -R"
    doing="Backing out"
else
    doing="Applying"
fi

# list the patch parts and loop over them
for file in $($dir/list $dir $1); do

    name=${file%.diff}

    # test the patch part first.

    echo >&2 "Checking PowerPC patch part $name for $version..."
    if bzcat $dir/$file.bz2 | $patch --force --dry-run > /dev/null; then

	# if the test succeeds, apply the patch. After the test above,
	# it should apply cleanly, or something went wrong.
    
	echo >&2 "$doing PowerPC patch part $name for $version..."
	if ! bzcat $dir/$file.bz2 | $patch; then
	    echo >&2 "Something went horribly wrong, PowerPC patch part $name for $version failed."
	    exit 1
	fi

    else

	# if the test fails, try to determine what is happening and
	# act accordingly.

	echo -n >&2 "Skipping PowerPC patch part $name for $version, "
	if test "$1" != "unpatch" -a -f debian/APPLIED_${file%.diff}; then
	    echo >&2 "it looks like it has already been applied."
	elif test "$1" = "unpatch" -a ! -f debian/APPLIED_${file%.diff}; then
	    echo >&2 "it looks like it has already been backed out."
	else
	    echo >&2 "it does not apply cleanly."
	    exit 1
	fi
    
    fi

    # set or clear the mark.
    
    if test "$1" = "unpatch"; then
	rm -f debian/APPLIED_$name
	rmdir debian 2> /dev/null || true
    else
	test -d debian || mkdir debian
	echo "PATCHFILE=$dir/$file.bz2" > debian/APPLIED_$name
    fi

done

