#!/bin/bash

# script  : tools/mkpatch
# author  : willy tarreau
# function: creates the full patch between the base and patched kernels
# usage   : $0

# This script uses the variable BASEVER for the base kernel version, the
# variable KERNVER for the new kernel version, and the variable KERNDIR for
# the current kernel location.

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

ORIGDIR="$PWD"

find kernel/linux-$KERNVER -name '*~' -o -name '*.orig' -o -type f -a -size 0 | xargs rm -f

BV1=${BASEVER%%[^0-9]*} ; BV2=${BASEVER#$BV1[^0-9]}
BP1=${BV2%%[^0-9]*}     ; BP2=${BV2#$BP1[^0-9]}
BS1=${BP2%%[^0-9]*}     ; BS2=${BP2#$BS1}

KV1=${KERNVER%%[^0-9]*} ; KV2=${KERNVER#$KV1[^0-9]}
KP1=${KV2%%[^0-9]*}     ; KP2=${KV2#$KP1[^0-9]}
KS1=${KP2%%[^0-9]*}     ; KS2=${KP2#$KS1}

# The final patch will be named "<KERNVER>.diff" only if the base kernel is of
# the same version.

if [ "$BV1" = "$KV1" -a "$BP1" = "$KP1" -a "$BS1" = "$KS1" -a -z "$BS2" ]; then
    KNAME=$KERNVER
else
    KNAME=$BASEVER-$KERNVER
fi

rm -f merged 2>/dev/null
mkdir -p merged
rm -f merged/$KNAME.diff

( cd kernel ;
  find linux-$BASEVER linux-$KERNVER \
       -name '*.rej' -o -name '*.orig' -o -name '*~' -o -size 0 \
       | xargs rm -vf ;
  diff -urN --exclude=".copied" --exclude=".patched" \
        linux-$BASEVER linux-$KERNVER \
       | grep -v '^diff ' >$ORIGDIR/merged/$KNAME.diff )

rm -f merged/$KNAME.desc
cp CONTENTS merged/$KNAME.desc

if [ "$KNAME" != "$BASEVER-$KERNVER" ]; then
    ln -sf $KNAME.diff merged/$BASEVER-$KERNVER.diff
    ln -sf $KNAME.desc merged/$BASEVER-$KERNVER.desc
fi

echo "The final patches against kernel $BASEVER have been generated in directory 'merged'."

exit 0