#! /bin/sh -e
# Try to apply patch $1 to kernel $3 in directory $2

# Split name into parts
BASE=$(echo $1 | sed 's/.gz$//')

STATUSDIR=~/devel/kernel/www/status

# Do depends first (if not already applied).
WORKINGTREE=`dirname $2`/.$$-trypatch
TMPFILE=`mktemp /tmp/try_patch.XXXXXX`
trap "rm -rf $WORKINGTREE $TMPFILE" EXIT

# Try this patch $1 in this dir $2.
test_patch()
{
    # Avoid any depends.
    if lkpatch --dry-run --ignore-depends $2 $1 >/dev/null 2>&1; then
	echo :APPLIES:$1
	return 0;
    fi
    return 1
}

# If patch has dependencies, we need to apply them first
if zcat $1 | grep -q '^Depends:'; then
    cp -al $2 $WORKINGTREE
    lkpatch --depends-only $WORKINGTREE $1 >/dev/null 2>&1
else
    WORKINGTREE=$2
fi

# Already applied?
if isapplied -l $WORKINGTREE $1 >/dev/null; then
    echo :INCLUDED:
    exit 0
fi

for patch in $BASE.*gz; do
    if RESULT=$(test_patch $patch $WORKINGTREE); then
	echo $1"$RESULT"
	exit 0
    fi
done

# Everything failed...
echo No version of $1 worked for $3.
echo "$1":BROKEN:
exit 1
