#!/bin/bash

# check variables, like all scripts herein do
WRS_SCRIPT_NAME=$(basename $0)
if [ -z "$WRS_BASE_DIR" ]; then
    echo "$0: Plesae set WRS_BASE_DIR" >& 2
    exit 1
fi
. ${WRS_BASE_DIR}/scripts/wrs_functions

wrs_check_vars WRS_OUTPUT_DIR WRS_DOWNLOAD_DIR CROSS_COMPILE

wrs_echo "--- Linux kernel for switch"
tarname="linux-2.6.39.tar.bz2"
patchdir="${WRS_BASE_DIR}/../patches/kernel/v2.6.39"
wrs_download $tarname

mkdir -p $WRS_OUTPUT_DIR/build || wrs_die "mkdir build"
mkdir -p $WRS_OUTPUT_DIR/images || wrs_die "mkdir images"

# go to the build dir and compile it, using our configuration
cd $WRS_OUTPUT_DIR/build
dirname="linux-2.6.39"
rm -rf $dirname
tar xjf ${WRS_DOWNLOAD_DIR}/$tarname || wrs_die "untar $tarname"

# apply patches
cd $dirname
for n in ${patchdir}/00*; do
    patch -p1 < $n || wrs_die "patch kernel"
done


# copy the config and replace "-j" level. First remove it in case it's left in
CFG="${patchdir}/linux-config-wrswitch"
if [ "x$WRS_KERNEL_CONFIG" != "x" ]; then
    if [ -f $WRS_KERNEL_CONFIG ]; then
	CFG=$WRS_KERNEL_CONFIG
    else
	wrs_warn "WRS_KERNEL_CONFIG does not refer to a regular file: ignoring it"
	sleep 3
    fi
fi

cp $CFG .config
export ARCH=arm
make oldconfig  || wrs_die "kernel config"

make $WRS_MAKE_J zImage modules  || wrs_die "kernel compilation"

mkdir -p $WRS_OUTPUT_DIR/images/lib/modules/2.6.39/kernel

cp $(find . -name '*.ko') $WRS_OUTPUT_DIR/images/lib/modules/2.6.39/kernel
cp arch/$ARCH/boot/zImage $WRS_OUTPUT_DIR/images
