#!/bin/sh
# (c) MandrakeSoft, Pixel <pixel@mandrakesoft.com>
# 	$Id: kheader.pl,v 1.1 2004/11/12 09:43:41 prigaux Exp $	
#
# kheader: This shell script regenerate the /boot/kernel.h header for \
#	   /usr/src/linux/include/{autoconf,version}.h
#
# chkconfig: 235 95 20
# description: This shell script regenerate the /boot/kernel.h header for \
#	   /usr/src/linux/include/{autoconf,version}.h
#

. /etc/rc.d/init.d/functions

: ${KERNEL_H:=/boot/kernel.h}
: ${HEADERFILE:=${KERNEL_H}-`uname -r`}
[ -d $(dirname $HEADERFILE) ] || exit 0

table() {
    SMP=0;ENTERPRISE=0;SECURE=0;I686_UP_4GB=0;I686_UP_64GB=0;P3_SMP_64GB=0;I586_UP_1GB=0;UP=0
    k=$(uname -r|sed 's/.*mdk//')
    case $k in
	smp)
	    SMP=1;;
	enterprise)
	    ENTERPRISE=1;;
	secure)
	    SECURE=1;;
	-i686-up-4GB)
	    I686_UP_4GB=1;;
	-i686-up-64GB)
	    I686_UP_64GB=1;;
	-p3-smp-64GB)
	    P3_SMP_64GB=1;;
	-i586-up-1GB)
	    I586_UP_1GB=1;;
	*)
	    UP=1;;

    esac
}

generate () {
    table;
    # do not overwrite exsisting header, it confuses
    # kernel make and forces it to recompile everything
    cat > $HEADERFILE.tmp << EOF
/* This file is automatically generated at boot time. */
#ifndef __BOOT_KERNEL_H_
#define __BOOT_KERNEL_H_

#ifndef __BOOT_KERNEL_SMP
#define __BOOT_KERNEL_SMP $SMP
#endif

#ifndef __BOOT_KERNEL_ENTERPRISE
#define __BOOT_KERNEL_ENTERPRISE $ENTERPRISE
#endif

#ifndef __BOOT_KERNEL_SECURE
#define __BOOT_KERNEL_SECURE $SECURE
#endif

#ifndef __BOOT_KERNEL_I686_UP_4GB
#define __BOOT_KERNEL_I686_UP_4GB $I686_UP_4GB
#endif

#ifndef __BOOT_KERNEL_I686_UP_64GB
#define __BOOT_KERNEL_I686_UP_64GB $I686_UP_64GB
#endif

#ifndef __BOOT_KERNEL_P3_SMP_64GB
#define __BOOT_KERNEL_P3_SMP_64GB $P3_SMP_64GB
#endif

#ifndef __BOOT_KERNEL_I586_UP_1GB
#define __BOOT_KERNEL_I586_UP_1GB $I586_UP_1GB
#endif

#ifndef __BOOT_KERNEL_UP
#define __BOOT_KERNEL_UP $UP
#endif

#endif
EOF

cmp -s $HEADERFILE $HEADERFILE.tmp || mv -f $HEADERFILE.tmp $HEADERFILE
rm -f $HEADERFILE.tmp

if [ -f $KERNEL_H ] ; then
    rm -f $KERNEL_H
fi

ln -sf $HEADERFILE $KERNEL_H
}

function remove_orphaned {
    local version= i=
    for i in /boot/kernel.h-* /boot/System.map-* /boot/config-*; do
	version=${i#*-}
	[[ -f /boot/vmlinuz-${version} ]] || rm -f ${i}
    done
}

case $1 in 
    start)
    # We don't log this command, because most users don't want to hear this (c) Chmou
	generate
	touch /var/lock/subsys/kheader
	;;
    restart)
	;;
    reload)
	generate
	;;
    stop)
	remove_orphaned;
	rm -f /var/lock/subsys/kheader
	;;
    status)
	;;
    *)
    gprintf "Usage: %s\n" "$(basename $0) {start|stop|reload|restart}"
    exit 0
    ;;
esac
