#!/bin/sh
# v3-kernel. Copy kernel from the host to the TARGET


echo "Setting up KERNEL to the TARGET"
vcmount $TARGET $DEVICE || exit 1

error_exit() {
    echo "ERROR: $1"
    exit 1
}

if [ -z "$KERNEL_BOOT" ] || \
   [ -z "$KERNEL_MODULES" ] || \
   [ -z $KERNEL_SOURCE ]; then
   echo "Kernel is not specified. Skipped."
   exit 0
fi

if [ ! -d "$KERNEL_BOOT" ] || \
   [ ! -d "$KERNEL_MODULES" ] || \
   [ ! -d $KERNEL_SOURCE ]; then
   error_exit "Missing kernel boot, modules or source"
fi

## Into a shell
(
echo Copying kernel to the TARGET
mkdir -p $TARGET/boot

# copy_kernel
cd $TARGET/boot
for ll in vmlinuz System.map config; do
    # remove old kernel on the target
    if [ -f $ll ]; then
	ff=`readlink $ll`
        rm -f $ff
    fi
    rm -f $ll
    echo Copying $ll-$KERNEL_VERSION
    cp -a $KERNEL_BOOT/$ll-$KERNEL_VERSION .
    ln -sf $ll-$KERNEL_VERSION $ll
done

#Leave initrd for optional bulks
#if [ -f $KERNEL_BOOT/initrd.gz ]; then
#    echo Copying initrd.gz
#    cp -au $KERNEL_BOOT/initrd.gz .
#fi

## Copy modules
echo Copying $KERNEL_MODULES
mname=`basename $KERNEL_MODULES`
cd $TARGET/lib
rm -rf modules
mkdir -p modules
cd modules
cp -a $KERNEL_MODULES .

## copy_source() {
echo Copying $KERNEL_SOURCE

cd $TARGET/usr/src
## Check old kernel source
if [ -h linux ]; then
    ff=`readlink linux`
    rm -rf $ff
    rm -f linux
fi

sname=`basename $KERNEL_SOURCE`
mkdir $sname
ln -sf $sname linux
mkdir -p $sname/include
cd $sname/include
cp -a $KERNEL_SOURCE/include/linux .
cp -a $KERNEL_SOURCE/include/asm-i386 .
ln -sf asm-i386 asm
cd ..
cat <<EOF > README-HEADERS
This is a kernel headers for compiling other programs.
It cannot be used to recompile the kernel itself.

EOF

## Fix build link
cd $TARGET/lib/modules/$mname
rm build
ln -sf /usr/src/$sname build

) ## exit shell
