#!/bin/bash

# script  : tools/makes-copy
# author  : willy tarreau
# function: makes a smallest copy of the required kernel files
# 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.

kdir_error() {
    echo "'$KERNDIR' is not a valid kernel directory (variable KERNDIR)."
    echo "Usage: ${0##*/}"
    exit 1
}

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

KERNDIR=${KERNDIR:-/usr/src/linux-$BASEVER}
if [ ! -d "$KERNDIR/include/linux" ]; then
    kdir_error
fi

rm -rf kernel/linux-$BASEVER
mkdir -p kernel/linux-$BASEVER

FLIST=( $(grep -h '^---\|^+++' numbered/*|awk '{print $2}'|sed -e 's,^\.\./,,'|cut -f2- -d/|sort -u) )

for i in "${FLIST[@]}"; do
    if [ -e "$KERNDIR/$i" ]; then
        [ -z "${i##*/*}" ] && mkdir -p "kernel/linux-$BASEVER/${i%/*}"
        ln -s "$KERNDIR/$i" "kernel/linux-$BASEVER/$i"
    fi
done

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