#!/bin/bash

# script  : tools/patch-copy
# author  : willy tarreau
# function: patches a copy of the kernel
# usage   : $0

# This script uses the variable BASEVER for the base kernel version, the
# variable KERNVER for the new kernel version.

[ -z "$BASEVER" ] &&set -- $(grep -ih -m 1 "^++.*Based" CONTENTS)  &&BASEVER=$5
[ -z "$KERNVER" ] &&set -- $(grep -ih -m 1 "^++.*Kernel" CONTENTS) &&KERNVER=$4

ORIGDIR="$PWD"

if [ -f "kernel/linux-$KERNVER/.patched" ]; then
    echo "Kernel tree is already patched. Remove it if you want to repatch."
    exit 0
fi

cp -al kernel/linux-$BASEVER kernel/linux-$KERNVER

(cd kernel/linux-$KERNVER ; $ORIGDIR/tools/apply $ORIGDIR/numbered/* | tee $ORIGDIR/kernel/patch-$KERNVER.log)

if grep -q 'rejects on [0-9]* file' CONTENTS; then
    expected_rej=$(sed -ne 's/\(^.*rejects on \)\([0-9]*\)\( file.*\)/\2/p' CONTENTS)
else
    expected_rej=0
fi

if [ $(find kernel/linux-$KERNVER -name '*.rej' |wc -l) != $expected_rej ]; then
    echo;echo "*** WARNING ***"
    echo "* The number of rejects is not as expected ($expected_rej). Aborting now."
    echo "* Please check them by hand in 'kernel' :"
    echo "*  - directory 'linux-$KERNVER' and file 'patch-$BASEVER-$KERNVER.log'"
    echo "* If all are normal, please fix the 'CONTENTS' file to reflect the number of"
    echo "* files expected to be affected by a reject."
    echo "* Then echo OK >'kernel/linux-$KERNVER/.patched', and run 'make' again."
    exit 2
fi

# must not be zero-sized or it will be removed
echo "$BASEVER -> $KERNVER" > kernel/linux-$KERNVER/.patched
exit 0