#! /bin/sh
# Copyright (c) 2004 SuSE Linux AG, Nuernberg, Germany.
# All rights reserved.
# Author: Andreas Gruenbacher <agruen@suse.de>
#
# /etc/init.d/running-kernel
#   and its symbolic link
# /usr/sbin/rcrunning-kernel
#
### BEGIN INIT INFO
# Provides:          running-kernel
# Required-Start:    $remote_fs
# Required-Stop:
# Default-Start:     2 3 5
# Default-Stop:
# Short-Description: Kernel source configuration switch
# description:  Adapt the configuration of the standard kernel sources
#		to match the currently running kernel. This is achieved
#		by creating an include file in /var/adm. The kernel sources
#		include these files to choose between the predefined
#		configurations. (This mechanism allows to build external
#		kernel modules for the standard kernels without first having
#		to configure the kernel by hand.)
### END INIT INFO

. /etc/sysconfig/kernel

if [ -n "$SKIP_RUNNING_KERNEL" ]; then
    exit
fi

ARCHS_FLAVORS="x86_64/default x86_64/smp x86_64/xen"

contains() {
    local w=$1
    while [ $# -ge 2 ]; do
	[ "$w" = "$2" ] && return 0
	shift
    done
    return 1
}

reconfigure() {
    local uname="$(uname -r)"
    set -- $(IFS='-' ; echo $uname)
    shift $[$#-1]
    local flavor="$1"

    arch=$(uname -m)
    case $arch in
    i?86)	arch=i386 ;;
    sun4u)	arch=sparc64 ;;
    arm*|sa110)	arch=arm ;;
    s390x)	arch=s390 ;;
    parisc64)	arch=parisc ;;
    esac
    # FIXME: How to handle uml?

    if ! contains "$arch/$flavor" $ARCHS_FLAVORS ; then
	# Not a supported configuration.
	if contains $arch/default $ARCHS_FLAVORS ; then
	    # Use the default configuration instead.
	    set -- $arch/default
	else
	    # No default configuration: use any.
	    set -- $ARCHS_FLAVORS
	fi
	arch=${1%/*}
	flavor="${1#*/}"
    fi

    kdir=/usr/src/linux
    obj=$kdir-obj/$arch/$flavor

    if [ -e $kdir/.config ]; then
	# The kernel sources appear to be hand-configured -- don't
	# touch them!
	return 0
    fi

    for file in include/asm \
		include/linux/autoconf.h \
		include/linux/version.h \
		include/asm-$arch/offset{,s}.h; do
	if [ -e $obj/$file ]; then
	    if [ -f $kdir/$file -a -f $obj/$file ] &&
	       [ "$(cat $kdir/$file)" = "$(cat $obj/$file)" ]; then
		 continue
	    fi
	    rm -f $kdir/$file
	    cp --no-dereference $obj/$file $kdir/$file
	else
	    rm -f $kdir/$file
	fi
    done
}

# Status shell functions
test -s /etc/rc.status && \
    . /etc/rc.status

# Reset status of this service
rc_reset
case "$1" in
    start)
	reconfigure ;;
    stop)
	;;
    *)
	echo "Usage: $0 {start|stop}"
	exit 1 ;;
esac
rc_exit
