#!/bin/sh

root_chk=`id | grep 'uid=0' | cut -d" " -f1`
echo $root_chk

if [ $root_chk".x" == ".x" ] ; then
  SUDO='/usr/bin/sudo'
else
  SUDO=''
fi

src_dir=`pwd`
source=linux-2.6.17.tar.bz2
patch1=patch-2.6.17.1.bz2
patch2=vd_unicon-kernel-20060618-2.6.17.patch
patch3=vd_unicon-kernel-fonts-20040205.patch.bz2
#config=config-2.6.17.1-plamoSMP
config=config-2.6.17.1-plamoUP
delflag=on

build_dir=$src_dir/Build

if [ ! $delflag".x" == ".x" ]; then

if [ -d $build_dir ]; then
  $SUDO rm -rf $build_dir
fi

mkdir -p $build_dir
cd $build_dir
tar xvjpf $src_dir/$source
pushd linux-2.6.17
  bzcat $src_dir/$patch1 | patch -p1
  patch -p1 < $src_dir/$patch2
  bzcat $src_dir/$patch3 | patch -p1
popd 
mv linux-2.6.17 linux-2.6.17.1
cd linux-2.6.17.1

cp $src_dir/$config ./.config
fi

cd $build_dir/linux-2.6.17.1

arch=i586
build=P1
pkgbase=kernel

if [ -f Makefile ]; then
  major=`grep "^VERSION" Makefile | cut -d" " -f3`
  minor=`grep "^PATCH" Makefile | cut -d" " -f3`
  rel=`grep "^SUBLEVEL" Makefile | cut -d" " -f3`
  patch=`grep "^EXTRAVERSION" Makefile | cut -d" " -f3`
fi

if [ -f .config ]; then
  local=`grep "^CONFIG_LOCALVERSION=" .config | cut -d"=" -f2 | sed 's/\"//g' `
fi

vers=${major}"."${minor}"."${rel}${patch}${local}
pkgvers=`echo $vers | sed 's/-/_/'`

pkg=${pkgbase}"-"${pkgvers}"-"${arch}"-"${build}".tgz"

H=`pwd`
T=`pwd`/../pkg

if [ -d $T ]; then
  $SUDO rm -rf $T
fi

make -j5
make modules_install INSTALL_MOD_PATH=$build_dir/modules
mkdir -p $T/lib/modules
cp -a $build_dir/modules/lib/modules/$vers $T/lib/modules

pushd $T/lib/modules/$vers
  rm build source
  ln -sf /usr/src/linux build
  ln -sf /usr/src/linux source
popd

mkdir -p $T/boot
pushd $T/boot
  cp $H/.config ./config-$vers
  cp $H/System.map ./System.map-$vers
  cp $H/arch/i386/boot/bzImage ./vmlinuz-$vers
  ln -sf config-$vers config
  ln -sf System.map-$vers System.map
  ln -sf vmlinuz-$vers vmlinuz
popd

$SUDO chown -R root.root $T
pushd $T
$SUDO /sbin/makepkg $pkg
mv $pkg ..
popd
