#!/bin/sh
# Kernel Builder Script

# check that you're sane
if [ ! -h /usr/src/linux ]
then
  echo "ERROR: I'd rather you made /usr/src/linux a link." >&2
  exit 1
fi

# Check kernel version
kernel=`pwd`

# If we're simply in /usr/src/linux, figure out where that is.
if [ "$kernel" = "/usr/src/linux" ]
then
  kernel=`ls -l /usr/src/linux | sed 's/.*-> //'` 
fi

if echo "$kernel" | grep "^/usr/src/linux" >/dev/null 2>&1
then
  kernel=`basename $kernel | sed 's/linux-//'`
else
  echo "ERROR: You need to run this script from a linux source directory." >&2
  exit 1
fi

# Now get the hostname
hostname=`hostname -s`

echo "Building a $kernel kernel for $hostname"

# Fix the /usr/src/linux link
rm -f /usr/src/linux
ln -s /usr/src/linux-$kernel /usr/src/linux

# Make sure we've got a usable config
config=/usr/src/$hostname-$kernel.config
if [ ! -f .config ] 
then
  if [ ! -f $config ]
  then
	# Trigger a config build. We could try make oldconfig here if appropriate
	if [ -s "$DISPLAY" ]
	then
	  make xconfig || exit 1
	else
	  make menuconfig || exit 1
	fi
  else
    # copy the config file and propogate
    cp $config .config
    make oldconfig
  fi
else
  if [ -f $config ]
  then
    if diff .config $config > /dev/null 2>&1
    then
      # Config is good, no need to clean up
      echo "Skipping cleanup"
    else
      if [ .config -ot $config ]
      then
        # local config is older, discard it
        cp $config .config
        # Possibly overkill, but best to be safe.
        make mrproper
      fi
      # Propagate config
      make oldconfig
    fi
  else
    # being on the safe side and all.
    make oldconfig
  fi
fi

# Save the config, now that we know it's good.
cp .config $config


# LILO update
if grep "$kernel" /etc/lilo.conf >/dev/null 2>&1
then
  echo "lilo.conf is up to date, skipping that."
else
  # Laziness :)
  vi /etc/lilo.conf
fi

# includes should point the right way
rm -rf /usr/include/linux /usr/include/asm
ln -s /usr/src/linux-$kernel/include/linux /usr/include/linux
ln -s /usr/src/linux-$kernel/include/asm /usr/include/asm

# Do the actual build
make dep && make && make install && make modules && make modules_install

# Fix up the /usr/include directories
# Whatever you're at, these should really match the running kernel.
echo "fixing up your includes"
rm -rf /usr/include/linux /usr/include/asm
ln -s /usr/src/linux-`uname -r`/include/linux /usr/include/linux
ln -s /usr/src/linux-`uname -r`/include/asm /usr/include/asm
