#! /bin/bash

# (c) Michael Goetze, 2010-2011, mgoetze@mgoetze.net
# (c) Thomas Lange, 2011, Uni Koeln

error=0; trap 'error=$(($?>$error?$?:$error))' ERR # save maximum error code

ainsl -v /etc/fstab "proc	/proc	proc	defaults	0 0"
ainsl -v /etc/fstab "sysfs	/sys	sysfs	auto		0 0"

version=`$ROOTCMD rpm -qv kernel | cut -d- -f2-`

use_mkinitrd() {

    # CentOS 5 uses mkinitrd
    $ROOTCMD kudzu -q -k $version
    # Unfortunately mkinitrd is horrible at guessing which modules to include,
    # especially when the running kernel is different than the kernel for which
    # we are creating an initrd...

    drivers=""
    for bus in pci virtio; do
	for dr in `$ROOTCMD kudzu -p -k $version -b $bus|grep driver:|cut -d' ' -f2|sort -u`; do
	    found=`find $target/lib/modules/$version/ -name $dr.ko 2>/dev/null`
	    if [ -n "$found" ]; then
		# add driver only if it's available as .ko module in the destination kernel
		drivers+=" --with=$dr"
	    fi
	done
    done

    $ROOTCMD mkinitrd -f -v $drivers /boot/initrd-$version.img $version

    if [ $? -eq 1 ]; then
	echo "WARNING: generating initrd with list of drivers failed. Trying without."
	$ROOTCMD mkinitrd -f -v /boot/initrd-$version.img $version
    fi
}

if [ -f $target/sbin/dracut ]; then
    # CentOS 6 uses dracut, but we do not need to call it
    #$ROOTCMD dracut -v "initramfs-$version.img" $version
    :  # this is a noop
else
    # CentOS 5 uses mkinitrd
    use_mkinitrd
fi


exit $error
