#! /bin/sh -e

if [ $# -ne 3 ] || [ ! -f $3 ] || [ ! -d $1 ]; then
    echo Usage: $0 "<dir> <kernel version> <patch>" >&2
    exit 1
fi

# Find dependency $1 in dir $2.
find_dep()
{
    find_dep_file="$1"
    find_dep_dir="$2"

    # Absolute file path.
    case "$find_dep_file" in
	/*) echo "$find_dep_file"; return;;
    esac

    # For every dir in file, take one dir off directory.
    while [ "$(dirname $find_dep_file)" != . ]; do
	find_dep_dir="$(dirname $find_dep_dir)"
	find_dep_file="$(dirname $find_dep_file)"
    done

    # List all variants from most recent backwards.
    find_dep_wildcard=$(echo "$find_dep_dir"/"$1" | sed 's/gz//')
    ls -rt "$find_dep_wildcard"*gz
}

BASEDIR=$1/linux-$2.$$
# Clean up on exit
trap "rm -rf $BASEDIR*" 0

# Create base tree
cp -al $1/linux-$2 $BASEDIR

# Populate tree with all the dependent patches.
for dep in `zcat $3 | grep '^Depends:' | cut -d: -f2-`; do
    APPLIED=0
    for possible_dep in $(find_dep $dep $(dirname $3) ); do
	if isapplied $BASEDIR $possible_dep >/dev/null ||
	    lkpatch $BASEDIR $possible_dep > /dev/null; then
	    APPLIED=1
	    break
	fi
    done
    if [ $APPLIED -eq 0 ]; then
	echo Could not apply $dep >&2
	exit 1
    fi
done

cp -al $BASEDIR $BASEDIR.updated

# Apply this patch
if lkpatch --keep-broken $BASEDIR.updated $3; then
    echo lkpatch succeeded...
    exit 1
fi

emacs `find $BASEDIR.updated -name '*.rej'`

NEWPATCH=`echo $3 | sed 's/\.patch\..*$/.patch/'`.$2.gz

if [ -f $NEWPATCH ]; then
    echo -n "$NEWPATCH already exists: overwrite? [Y/n] "
    read REPLY
    case "$REPLY" in
	N*|n*) exit 1;;
    esac
fi

# Copy patch preample, and append diff.
(zcat $3 | grep '^\([^-+ ]\+:\|$\)'; cd $(dirname $BASEDIR); kerndiff $(basename $BASEDIR) $(basename $BASEDIR).updated) |
	gzip -9 > $NEWPATCH

echo Created $NEWPATCH.
