#!/bin/sh

# geninitrd
#
#	by PLD Linux Team
#
# based on mkinitrd from RedHat Linux
#
# TODO:
# - make udev start before insmods
# - make proper use of USE_UDEV - don't copy fules if USE_UDEV is off no!
#

RCSID='$Id: geninitrd 8980 2007-11-03 14:34:33Z adamg $'
R=${RCSID#* * }; VERSION=${R%% *}
PROGRAM=${0##*/}

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

COMPRESS=yes
USERAIDSTART=yes
USEMDADMSTATIC=no
USEINSMODSTATIC=no
USE_SUSPEND=yes
USE_TUXONICE=no
# it should be safe to remove scsi_mod from here, but I'm not sure...
PRESCSIMODS="-scsi_mod unknown -sd_mod"
PREIDEMODS="-ide-core unknown -ide-detect -ide-disk"
PREIDEMODSOLD="-ide-probe -ide-probe-mod -ide-disk"
target=""
kernel=""
force=""
verbose=""
MODULES=""
img_vers=""
fstab=/etc/fstab
insmod=insmod
modext=.o
rootdev_nr=0
# device node for rootfs from fstab
rootdev=""
# default bootsplash is off, if it have to be on, install bootsplash package
BOOT_SPLASH=no
# default same as bootsplash, if on install splashutils and some splashutils theme
FB_SPLASH=no
# defualt we don't use udev to make nodes for static modules, as per default
# PLD loads the modules needed to mount and boot
PROBESTATICMODULES=no

# internal variables
# is /dev on tmpfs
dev_mounted=no
# is /proc mounted
proc_mounted=no
# is /sys mounted
sys_mounted=no
# is /tmp mounted on tmpfs
tmp_mounted=no

# are /dev nodes already created from /proc/devices info?
proc_partitions=no

# LVM devices that should not be included in vgscan on initrd
lvm_ignore_devices=''
# LVM volume that is used for rootfs
VGVOLUME=

# if we should init NFS at boot
have_nfs=no
# if we should init LVM at boot
have_lvm=no
# if we should init md (softraid) at boot
have_md=no
# if we should init dmraid at boot
have_dmraid=no
# if we should init dm-multipath at boot
have_multipath=no
# dm-multipath id which is used for rootfs
MULTIPATH_ID=

if [ -f /etc/udev/udev.conf -a -x /sbin/initrd-udevd ]; then
	USE_UDEV=yes
	. /etc/udev/udev.conf
fi

if [ -x /sbin/dmraid-initrd ]; then
	USE_DMRAID=yes
fi

if [ -x /sbin/multipath ]; then
	USE_MULTIPATH=yes
fi

usage() {
	uname_r=$(uname -r)
	echo "usage: $PROGRAM [--version] [-v] [-f] [--ifneeded] [--preload <module>]"
	echo "       [--with=<module>] [--image-version] [--fstab=<fstab>] [--nocompress]"
	echo "       [--initrdfs=rom|initramfs|ext2|cram] [--modules-conf=<modules.conf>]"
	echo "       [--with-raidstart] [--without-raidstart] [--with-insmod-static]"
	echo "       [--with-bootsplash] [--without-bootsplash]"
	echo "       [ --with-fbsplash] [--without-fbsplash]"
	echo "       [--lvmtoolsversion=1|2] [--with-udev] [--without-udev]"
	echo "       [--with-suspend] [--without-suspend]"
	echo "       [--with-tuxonice] [--without-tuxonice]"
	echo "       [--without-dmraid] [--without-multipath]"
	echo "       <initrd-image> <kernel-version>"
	echo ""
	echo "example:"
	echo "  $PROGRAM -f --initrdfs=rom /boot/initrd-$uname_r.gz $uname_r"
	exit 1
}

debug() {
	[ -n "$verbose" ] && echo >&2 "$*"
}

# aborts program abnormally
die() {
	local rc=${2:-1}
	echo >&2 "$PROGRAM: ERROR: $1"
	exit $rc
}

# append text to /linuxrc
# takes STDIN as input
add_linuxrc() {
	cat >> "$RCFILE"
}

# generate code to mount /dev on tmpfs and create initial nodes
# can be called multiple times. /dev is cleaned up (umounted) automatically at
# the end of script.
mount_dev() {
    if [ "$INITRDFS" = "initramfs" ]; then
		# initramfs is read-write filesystem, no need for tmpfs
		return
	fi

	# we already generated tmpfs code; return
	if is_yes "$dev_mounted"; then
		return
	fi

	dev_mounted=yes

	busybox_applet mount mknod mkdir
	add_linuxrc <<-EOF
		: 'Creating /dev'
		mount -o mode=0755 -t tmpfs none /dev
		mknod /dev/console c 5 1
		mknod /dev/null c 1 3
		mknod /dev/zero c 1 5
		mkdir /dev/pts
		mkdir /dev/shm
	EOF
}

# generate code to mount /proc on initrd
# can be called multiple times
mount_proc() {
	if is_yes "$proc_mounted"; then
		return
	fi

	proc_mounted=yes
	echo "mount -t proc none /proc" | add_linuxrc
}

# generate code to mount /sys on initrd
# can be called multiple times
mount_sys() {
	if is_yes "$sys_mounted"; then
		return
	fi

	sys_mounted=yes
	echo "mount -t sysfs none /sys" | add_linuxrc
}

# generate code to mount /tmp on initrd
# can be called multiple times
mount_tmp() {
    if [ "$INITRDFS" = "initramfs" ]; then
		# initramfs is read-write filesystem, no need for tmpfs
		return
	fi

	if is_yes "$tmp_mounted"; then
		return
	fi

	tmp_mounted=yes
	echo "mount -t tmpfs none /tmp" | add_linuxrc
}

# unmount all mountpoints mounted by geninitrd
umount_all() {

	add_linuxrc <<-'EOF'
	: Last shell before umounting all and giving control over to real init.
	debugshell
	EOF

	if is_yes "$dev_mounted"; then
		echo 'umount /dev' | add_linuxrc
		dev_mounted=no
	fi
	if is_yes "$proc_mounted"; then
		echo 'umount /proc' | add_linuxrc
		proc_mounted=no
	fi
	if is_yes "$sys_mounted"; then
		echo 'umount /sys' | add_linuxrc
		sys_mounted=no
	fi
	if is_yes "$tmp_mounted"; then
		echo 'umount /tmp' | add_linuxrc
		tmp_mounted=no
	fi
}


# Checks if busybox has support for APPLET(s)
# Exits from geninitrd if the support is not present.
#
# NB! XXX do not output to STDOUT, it will appear in initrd images in some cases!
busybox_applet() {
	local err=0

	if [ -z "$busybox_functions" ]; then
		local tmp=$(/bin/initrd-busybox 2>&1)

		# BusyBox v1.1.3 says applet not found if it's not called 'busybox'.
		if [[ "$tmp" = *applet\ not\ found* ]]; then
			local t=$(mktemp -d)
			ln -s /bin/initrd-busybox $t/busybox
			local tmp=$($t/busybox 2>&1)
			rm -rf $t
		fi

		busybox_functions=$(echo "$tmp" | \
			sed -ne '/Currently defined functions:/,$p' | \
		   	xargs | sed -e 's,.*Currently defined functions: ,,'
		)
	fi
	for applet in $*; do
		local have
		# try cache
		eval have='$'busybox_have_$applet
		if [ -z "$have" ]; then
			have=$(echo "$busybox_functions" | egrep -c "( |^)$applet(,|$)")
			if [ "$have" = 0 ]; then
				echo >&2 "This setup requires busybox-initrd compiled with applet '$applet' support"
				err=1
			fi
			eval busybox_have_$applet=$have
		fi
	done
	if [ $err = 1 ]; then
		die "Aborted"
	fi
}

find_depmod () {
	typeset mods module f level depfile first

	depfile=/lib/modules/$kernel/modules.dep

	if [ ! -f $depfile ]; then
		die "No $depfile! Run depmod and rerun $PROGRAM."
	fi

	# prepend / if no path given, append $modext.gz if not given,
	# quote /
	origmodule="$2"
	module=$(echo "$2" | \
		awk '/\// {print;next} {print "/" $0}' | \
		awk '/\./ {print;next} {print $0 "'$modext'.gz"}' |
		awk '{gsub("/","\\/");print}')
	mods=$(awk '
BEGIN { here = 0 }
/'"$module"':(.*)/ { gsub(/:/," "); gsub(/\\/," "); print; here = 1; next }
/:/ { here = 0 }
/(.*)/ { gsub(/\\/," "); if (here) print }
' $depfile | xargs)

	# fallback to $modext
	if [ "$mods" = "" ]; then
		module=$(echo "$module" | awk '{gsub("\'$modext'\.gz$","\'$modext'",$0);print}')
		# ") - vim
	fi

	mods=$(awk '
BEGIN { here = 0 }
/'"$module"':(.*)/ { gsub(/:/," "); gsub(/\\/," "); print; here = 1; next }
/:/ { here = 0 }
/(.*)/ { gsub(/\\/," "); if (here) print }
' $depfile | xargs)

	if [ "$mods" = "" ]; then
		if [ "$1" != silent ]; then
			echo >&2 "$origmodule: module not found in $depfile"
		fi
		if ! is_no "$EXIT_IF_MISSING"; then
			exit 1
		else
			echo >&2 "If $origmodule isn't compiled in kernel then this initrd may not start your system."
		fi
	fi

	level=$3
	if [ "$level" = "" ]; then
		level=0
	fi
	level=$((level + 1))
	if [ $level -gt 20 ]; then
		die "$origmodule: cycle in $depfile"
	fi

	first=
	for f in $mods; do
		if [ "$first" = "" ]; then
			first=$f
		else
			find_depmod $1 $f $level
		fi
	done

	echo $first
}

addmodule() {
	local fmPath=$1
	local skiperrors=$2

	if [ ! -f "/lib/modules/$kernel/$fmPath" ]; then
		if [ -n "$skiperrors" ]; then
			return
		fi

		die "module $fmPath present in modules.dep, but not in filesystem (kernel = $kernel)"
	fi

	# only need to add each module once
	# quote /
	local tmpFmPath=$(echo $fmPath | awk '{gsub(/\//,"\\/");print}')
	if echo "$MODULES" | awk '/'"$tmpFmPath"'/ {exit 1}'; then
		MODULES="$MODULES $fmPath"
	fi
}

findmodule() {
	local skiperrors=""
	local modName=$1

	if [ ${modName#-} != ${modName} ]; then
		skiperrors=1
		modName=${modName#-}
	fi

	# what's that?
	if [ "$modName" = "pluto" ]; then
		findmodule fc4
		findmodule soc
	fi
	if [ "$modName" = "fcal" ]; then
		findmodule fc4
		findmodule socal
	fi

	local mod allModulesToFind
	if [ -n "$skiperrors" ]; then
		allModulesToFind=$(find_depmod silent $modName)
	else
		allModulesToFind=$(find_depmod normal $modName)
		if [ $? != 0 ]; then
			exit 1
		fi
	fi

	for mod in $allModulesToFind; do
		mod=$(echo $mod | awk '{sub(/^\/lib\/modules\/[^\/]*\//, ""); print}')
		addmodule $mod "$skiperrors"
	done
}

# install a file to temporary mount image.
# it will operate recursively (copying directories)
# and will symlink destinations if source is symlink.
inst() {
	if [ $# -lt 2 ]; then
		die 'Usage: inst <file> [<file>] <destination>'
	fi

	local src i=0 c=$(($# - 1))
	while [ $i -lt $c ]; do
		src="$src $1"
		i=$((i + 1))
		shift
	done
	local dest=$1
	set -- $src

	debug "cp $* $MNTIMAGE$dest"
	cp -HR "$@" "$MNTIMAGE$dest"
}

inst_d() {
	if [ $# = 0 ]; then
		die 'Usage: inst_d <destination> <destination>'
	fi
	for dir in "$@"; do
		install -d "$MNTIMAGE$dir"
	done
}

# install executable and it's shared libraries
inst_exec() {
	if [ $# -lt 2 ]; then
		die 'Usage: inst_exec <file> [, <file>] $MNTIMAGE<destination>'
	fi
	local src i=0 c=$(($# - 1))
	while [ $i -lt $c ]; do
		src="$src $1"
		i=$((i + 1))
		shift
	done
	local dest=$1
	set -- $src

	inst "$@" $dest

	local lib libs=$(ldd "$@" | awk '/statically|linux-gate\.so/{next} NF == 2 {print $1} /=/{print $3}' | sort -u)
	for lib in $libs; do
		if [ ! -f "$MNTIMAGE/$_lib/${lib##*/}" ]; then
			inst_d /$_lib
			inst_exec $lib /$_lib
		fi
	done
}

# output modules.conf / modprobe.conf
modprobe_conf() {
	echo "$modprobe_conf_cache"
}

#
# defaults to modprobe -c if not told otherwise, this means include statements
# work from there.
cache_modprobe_conf() {
	if [ "$pack_version" -lt "002005" ]; then
		modulefile=/etc/modules.conf
		if [ ! -f "$modulefile" -a -f /etc/conf.modules ]; then
			modulefile=/etc/conf.modules
		fi
	fi

	if [ -n "$modulefile" ]; then
		debug "modprobe: using $modulefile"
		modprobe_conf_cache=$(cat $modulefile)
	else
		debug "modprobe: using modprobe -c"
		modprobe_conf_cache=$(modprobe -c)
	fi
}

find_modules_md() {
	local found raidlevel

	if [ -f /etc/mdadm.conf ]; then
		debug "Finding RAID details using mdadm for rootdev=$1"
		eval `/sbin/mdadm -v --examine --scan --config=/etc/mdadm.conf | awk -v rootdev="$1" '
		BEGIN {
			found = "no";
			dev_list = "";
			raidlevel = ""
			rootdev_devfs = rootdev;
			if (rootdev ~ /\/dev\/md\/[0-9]/) {
				gsub(/\/dev\/md\//,"/dev/md",rootdev_devfs);
			}
		}

		/^ARRAY/ {
			if (($2 == rootdev) || ($2 == rootdev_devfs)) {
				raidlevel=$3;
				gsub(/level=/,NUL,raidlevel);
				if (raidlevel ~ /^raid([0-6]|10)/) {
					gsub(/raid/,NUL,raidlevel);
				};
				found="yes";
				getline x;
				if (x ~ /devices=/) {
					dev_list = x;
					gsub(".*devices=", NUL, dev_list);
					gsub(",", " ", dev_list);
				}
			}
		}

		END {
			print "have_md=" found;
			print "raidlevel=" raidlevel;
			print "dev_list=\"" dev_list "\"";
		}'`
	fi

	if [ "$have_md" != "yes" -a -f /etc/raidtab ]; then
		die "raidtools are not longer supported. Please migrate to mdadm setup!"
	fi

	if is_yes "$have_md"; then
		case "$raidlevel" in
		[01]|10)
			findmodule "raid$raidlevel"
			;;
		[456])
			findmodule "-raid$raidlevel"
			findmodule "-raid456"
			;;
		linear)
			findmodule "linear"
			;;
		*)
			echo >&2 "raid level $number (in mdadm config) not recognized"
			;;
		esac
	else
		die "RAID devices not found for \"$1\", check your configuration!"
	fi

	rootdev_nr=$(( $rootdev_nr + 1 ))
	eval "rootdev${rootdev_nr}=\"$1\""
	eval "dev_list${rootdev_nr}=\"${dev_list}\""

	for device in $dev_list; do
		find_modules_for_device $device
	done
}

find_modules_scsi() {
	local n
	for n in $PRESCSIMODS; do
		if [ "X$n" = "Xunknown" ]; then
			debug "Finding SCSI modules using scsi_hostadapter"
			local mod scsimodules=$(modprobe_conf | awk '/scsi_hostadapter/ && ! /^[\t ]*#/ { print $3; }')
			for mod in $scsimodules; do
				# for now allow scsi modules to come from anywhere. There are some
				# RAID controllers with drivers in block
				findmodule "$mod"
			done
		else
			findmodule "$n"
		fi
	done
	findmodule "-scsi_wait_scan"
}

find_modules_ide() {
	local devpath=$1
	# remove partition, if any
	local disk=${devpath%[0-9]*}
	# set blockdev for rootfs (hda, sdc, ...)
	local rootblkdev=${disk#/dev/}

	local n
	if [ "$pack_version_long" -lt "002004021" ]; then
		debug "Finding IDE modules for kernels <= 2.4.20"
		for n in $PREIDEMODSOLD; do
			findmodule "$n"
		done
	else
		local tryauto=1
		for n in $PREIDEMODS; do
			if [ "X$n" = "Xunknown" ]; then
				debug "Finding IDE modules using ide_hostadapter"
				local mod idemodules=$(modprobe_conf | awk '/ide_hostadapter/ && ! /^[\t ]*#/ { print $3; }')
				for mod in $idemodules; do
					tryauto=0;
					findmodule "$mod"
				done

				if [ "$tryauto" -eq 1 ]; then
					# If tryauto {{{
					if [ -r /usr/share/pci-database/ide.pci -a -r /proc/bus/pci/devices ]; then
						debug "Finding IDE modules using PCI ID database"
						# Finding IDE modules using PCI ID database {{{
						if is_yes "${ide_only_root}"; then
							if [ -f /sys/block/${rootblkdev}/device/../../vendor -a -f /sys/block/${rootblkdev}/device/../../device ]; then
								vendorid="$(awk ' { gsub(/0x/,NUL); print $0 } ' /sys/block/${rootblkdev}/device/../../vendor)"
								deviceid="$(awk ' { gsub(/0x/,NUL); print $0 } ' /sys/block/${rootblkdev}/device/../../device)"
								searchpciid="${vendorid}${deviceid}"
							elif [ -f /proc/ide/${rootblkdev}/../config ]; then
								searchpciid="$(awk ' /pci bus/ { print $7$9 } ' /proc/ide/${rootblkdev}/../config)"
							fi
						fi

						if [ -z "${searchpciid}" ]; then
							searchpciid="$(awk ' { print $2 } ' /proc/bus/pci/devices)"
						fi

						idemodules=""

						for nb in $searchpciid; do
							eval `awk -v pciid="$nb" '{
								gsub("\t"," ");
								gsub("  +", " ");
								gsub("^ ","");
								if (/^[\t ]*#/)
									next;
								compmod = $1 "";	# make sure comparison type will be string
											# cause pci IDs are hexadecimal numeric
								if (compmod == pciid) {
									module=$2;
							#		min_kernel=$3;  # now in ide.pci $3,$4 = vendor and device name
							#		max_kernel=$4;  #
									exit 0;
								}
							}

							END {
								print "module=" module "\nmin_kernel=" min_kernel "\nmax_kernel=\"" max_kernel "\"\n";
							}' /usr/share/pci-database/ide.pci`
							[ -n "$module" ] && idemodules="$idemodules $module"
						done
						if is_yes "$(awk ' /ide=reverse/ { print "yes" } ' /proc/cmdline)"; then
							new_idemodules=""
							for nc in idemodules; do
								new_idemodules="$nc $new_idemodules"
							done
							idemodules="${new_idemodules}"
						fi

						if [ -z "$idemodules" ]; then
							echo "WARNING: rootfs on IDE device but no related modules found, loading ide-generic."
							idemodules="ide-generic"
						fi

						# }}}
						for nd in $idemodules; do
							findmodule "-$nd"
						done
					# }}}
					# else tryauto {{{
					else
						[ -r /usr/share/pci-database/ide.pci ] || echo "WARNING: /usr/share/pci-database/ide.pci missing."
						[ -r /proc/bus/pci/devices ] || echo "WARNING: /proc/bus/pci/devices missing."
						echo "Automatic IDE modules finding not available."
					fi
					# }}}
				fi
			else
				findmodule "$n"
			fi
		done
	fi
}

# return true if node is lvm node
_check_lvm() {
	local node="$1"
	if [ ! -e "$node" ]; then
		echo >&2 "WARNING: check_lvm(): node $node doesn't exist!"
		return 1
	fi

	# block-major-58 is lvm1
	ls -lL "$node" 2> /dev/null | awk '{if (/^b/) { if ($5 == "58,") { exit 0; } else { exit 1; } } else { exit 1; }}'
	rc=$?

	if [ $rc = 0 ]; then
		debug "$node is LVM1 node"
		# is lvm1
		return 0
	fi

	/sbin/lvm lvdisplay "$node" > /dev/null 2>&1
	rc=$?
	if [ $rc -gt 127 ]; then
		# lvdisplay terminated by signal! most likely it segfaulted.
		die "Unexpected exit from 'lvdisplay $node': $rc - are your lvm tools broken?"
	fi

	if [ $rc = 0 ]; then
		debug "$node is lvm2 node"
	else
		debug "$node is not any lvm node"
	fi
	return $rc
}

# find dm-multipath modules for $devpath
# returns false if $devpath is not dm-multipath
find_modules_multipath() {
	local devpath="$1"

	# remove partition, if any
	local disk=${devpath%p[0-9]*}
	# need only dm name
	MULTIPATH_ID=${disk#/dev/mapper/}

	local info=$(multipath -l $MULTIPATH_ID)
	if [ -z "$info" ]; then
		return 1
	fi

	debug "have multipath"
	have_multipath=yes
	local dev phydevs=$(echo "$info" | awk '$2 ~ /^[0-9]+:[0-9]+:[0-9]+:[0-9]+$/{printf("/dev/%s\n", $3)}')
	for dev in $phydevs; do
		find_modules_for_device $dev
		lvm_ignore_devices="$lvm_ignore_devices $dev"
	done

	local hw hwhandlers=$(echo "$info" | awk '/hwhandler=1/{sub(/.*hwhandler=1 /, ""); sub(/\]$/, ""); print}')
	for hw in $hwhandlers; do
		findmodule "dm-$hw"
	done

	local target targets=$(echo "$info" | awk '/prio=/{print $2}' | sort -u)
	for target in $targets; do
		findmodule "dm-$target"
	done

	findmodule "dm-mod"
	return 0
}

# find dmraid modules for $devpath
# returns false if $devpath is not on dmraid
find_modules_dmraid() {
	local devpath="$1"

	# get blockdev itself (without partition)
	# /dev/mapper/sil_ahbgadcbchfc3 -> /dev/mapper/sil_ahbgadcbchfc
	local blockdev=${devpath%%[0-9]*}
	local raidname=${blockdev#/dev/mapper/}
	local found=0

	local dev phydevs=$(dmraid -r -cdevpath,raidname | awk -F, -vv="$raidname" '{if ($2 == v) print $1}')
	for dev in $phydevs; do
		find_modules_for_device $dev
		lvm_ignore_devices="$lvm_ignore_devices $dev"
		found=1
	done

	if [ $found = 0 ]; then
		return 1
	fi

	findmodule "dm-mirror"
	have_dmraid=yes
	return 0
}

# find modules for $devpath
find_modules_for_device() {
	local devpath="$1"
	if [ -z "$devpath" ]; then
		die "No argument passed to find_modules_for_device() - is your /etc/fstab correct?"
	fi

	# /dev/dm-3 -> /dev/mapper/sil_ahbgadcbchfc3
	case "$devpath" in
	/dev/dm-*)
		devpath=$(dm_longname "$devpath")
		;;
	esac
	debug "find_modules_for_device($devpath)"

	if is_yes "`echo "$devpath" | awk '/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+:|\/dev\/nfs)/ { print "yes"; }'`"; then
		if [ ! -x /usr/bin/pcidev -a -z "$NFS_ETH_MODULES" ]; then
			die "root on NFS but /usr/bin/pcidev not found. Please install correct pci-database package and rerun $PROGRAM."
		fi
		local m
		[ -z "$NFS_ETH_MODULES" ] && NFS_ETH_MODULES=$(/usr/bin/pcidev /m net | xargs)
		for m in $NFS_ETH_MODULES; do
			findmodule "$m"
		done
		findmodule "-ipv4"
		findmodule "nfs"
		have_nfs=yes
		echo >&2 "Remember to use \`root=/dev/ram0 init=/linuxrc' when starting kernel"
		echo >&2 "or you will have problems like init(xx) being child process of swapper(1)."
		return
	fi

	if [[ "$devpath" == /dev/md/* ]]; then
		find_modules_md "$devpath"
		return
	fi

	if is_yes "$USE_MULTIPATH" && [[ "$devpath" == /dev/mapper/* ]]; then
		if find_modules_multipath "$devpath"; then
			return
		fi
		# fallback
	fi

	if is_yes "$USE_DMRAID" && is_yes "$(echo "$devpath" | awk '/^\/dev\/mapper\/(sil|hpt37x|hpt45x|isw|lsi|nvidia|pdc|sil|via|dos)_/ { print "yes"; }')"; then
		if find_modules_dmraid "$devpath"; then
			return
		fi
		# fallback
	fi

	if is_yes "$(echo "$devpath" | awk '/^\/dev\/(sd|scsi)/ { print "yes"; }')"; then
		find_modules_scsi
		return
	fi

	if is_yes "$(echo "$devpath" | awk '/^\/dev\/(hd|ide)/ { print "yes"; }')"; then
		find_modules_ide "$devpath"
		return
	fi

	if [[ "$devpath" == /dev/rd/* ]]; then
		findmodule "DAC960"
		return
	fi

	if [[ "$devpath" == /dev/ida/* ]]; then
		findmodule "cpqarray"
		return
	fi

	if [[ "$devpath" == /dev/ccis/* ]]; then
		findmodule "cciss"
		return
	fi

	if [[ "$devpath" == /dev/ataraid/* ]]; then
		find_modules_ide
		findmodule "ataraid"
		ataraidmodules=$(modprobe_conf | awk '/ataraid_hostadapter/ && ! /^[\t ]*#/ { print $3; }')
		if [ -n "$ataraidmodules" ]; then
			# FIXME: think about modules compiled in kernel
			die "ataraid_hostadapter alias not defined in modprobe.conf! Please set it and run $PROGRAM again."
		fi
		for n in $ataraidmodules; do
			findmodule "$n"
		done
		return
	fi

	# check to see if we need to set up a loopback filesystem
	if [[ "$devpath" == /dev/loop*  ]]; then
		die "Sorry, root on loop device isn't supported."
		# TODO: rewrite for bsp and make nfs ready
		if [ ! -x /sbin/losetup ]; then
			die "losetup is missing"
		fi
		key="^# $(echo $devpath | awk -F/ '{print($3);}' | tr '[a-z]' '[A-Z]'):"
		if ! is_yes "`awk '/'$key'/ { print( "yes"); }' $fstab`"; then
			die "The root filesystem is on a $devpath, but there is no magic entry in $fstab for this device. Consult the $PROGRAM man page for more information"
		fi

		line="`awk '/'$key'/ { print $0; }' $fstab`"
		loopDev="$(echo $line | awk '{print $3}')"
		loopFs="$(echo $line | awk '{print $4}')"
		loopFile="$(echo $line | awk '{print $5}')"

		BASICMODULES="$BASICMODULES -loop"
		findmodule "-$loopFs"
		BASICMODULES="$BASICMODULES -${loopFs}"
		return
	fi

	if _check_lvm "$devpath"; then
		node="$devpath"

		if [ ! -f /sbin/initrd-lvm -o ! -x /sbin/lvdisplay -o ! -x /sbin/pvdisplay ]; then
			die "root on LVM but /sbin/initrd-lvm, /sbin/lvdisplay and /sbin/pvdisplay not found. Please install lvm(2) and lvm(2)-initrd package and rerun $PROGRAM."
		fi
		if [ -z "$LVMTOOLSVERSION" ]; then
			LVMTOOLSVERSION=$(/sbin/initrd-lvm vgchange --version 2>/dev/null|head -n 1|awk '{gsub("vgchange: Logical Volume Manager ",NIL); gsub("LVM version:     ",NIL); gsub(/\..*/,NIL); print $1}')
			if [ -z "$LVMTOOLSVERSION" ]; then
				die "Can't determine LVM tools version. Please set LVMTOOLSVERSION and rerun $PROGRAM."
			fi
		fi
		if [ -z "$PVDEVICES" ]; then
			VGVOLUME=$(/sbin/lvdisplay -c "$node" 2> /dev/null | awk -F":" ' { print $2 } ')
			PVDEVICES=$(/sbin/pvdisplay -c 2>/dev/null | awk -F":" -v vg="$VGVOLUME" ' BEGIN { devices="" } { if ($2 == vg) { devices = devices " " $1 } } END { print devices } ')
		fi
		if [ -n "$PVDEVICES" ]; then
			for device in $PVDEVICES; do
				find_modules_for_device $device
			done
		else
			die "I wasn't able to find PV (via lvdisplay and pvdisplay). You can try to set PVDEVICES in /etc/sysconfig/geninitrd."
		fi
		if [ "$LVMTOOLSVERSION" = "2" ]; then
			findmodule "-dm-mod"
		elif [ "$LVMTOOLSVERSION" = "1" ]; then
			findmodule "-lvm"
			findmodule "-lvm-mod"
		else
			die "LVM version $LVMTOOLSVERSION is not supported yet."
		fi
		debug "LVM $LVMTOOLSVERSION enabled"
		have_lvm=yes
		return
	fi
}

firmware_install_module() {
	local module="$1"
	local firmware_files="$2"

	debug "Adding Firmwares ($firmware_files) to initrd for module $module"
	# firmware not yet installed
	if [ ! -f "$MNTIMAGE/lib/firmware/firmware.sh" ]; then
		inst_d /lib/firmware
cat << 'EOF' >> "$MNTIMAGE/lib/firmware/firmware.sh"
#!/bin/sh -e
echo 1 > /sys$DEVPATH/loading
cat "/lib/firmware/$FIRMWARE" > /sys$DEVPATH/data
echo 0 > /sys$DEVPATH/loading
exit 0
EOF
	 	chmod 755 "$MNTIMAGE/lib/firmware/firmware.sh"
	fi

	for firmware in $firmware_files; do
		inst /lib/firmware/$firmware /lib/firmware/$firmware
	done

	mount_sys
	echo "echo -n "/lib/firmware/firmware.sh" > /proc/sys/kernel/hotplug" | add_linuxrc
}

modules_install() {
	local modules="$1"
	local mod

	for mod in $modules; do
		MODULEDIR=$(dirname "$mod")
		inst_d "/lib/modules/$kernel/$MODULEDIR"
		cp -a "/lib/modules/$kernel/$mod" "$MNTIMAGE/lib/modules/$kernel/$mod"
		gunzip "$MNTIMAGE/lib/modules/$kernel/$mod" 2> /dev/null
	done
}

modules_add_linuxrc() {
	local modules="$1"
	local mod

	for mod in $modules; do
		MODULE2="`dirname "$mod"`"
		NAME2=`basename "$mod" .gz`
		MODULE2=$MODULE2/$NAME2
		module="`echo $mod | awk -F/ '{ $0=$NF } /'$modext'.*$/ { gsub(/'$modext'.*/, NIL, $0); } { print $0; }'`"
		options=$(modprobe_conf | awk -vmodule="$module" '{ if ($1 == "options" && $2 == module) { for(i=3;i<=NF;i++) printf("%s ",$i); }}')

		generic_module=$(echo "${module}" | awk ' { gsub("-", "_", $0) } { print $0; } ')
		sleep_var="$(eval echo \$MODULE_${generic_module}_USLEEP)"
		firmware_var="$(eval echo \$MODULE_${generic_module}_FIRMWARE)"

		if [ -n "$verbose" ]; then
			echo -n "Loading module [$module] "
			if [ -n "$options" ]; then
				echo -n "with options [$options]"
			else
				echo -n "without options"
			fi
			if [ -n "$sleep_var" ]; then
				echo " and $sleep_var usleep."
			else
				echo "."
			fi
		fi

		if [ -n "$firmware_var" ]; then
			firmware_install_module "$module" "$firmware_var"
		fi
		echo "$insmod /lib/modules/$kernel/$MODULE2 $options" | add_linuxrc
		if [ -n "${sleep_var}" ]; then
			echo "usleep $sleep_var" | add_linuxrc
		fi
	done
}

if [ -r /etc/sysconfig/geninitrd ]; then
	. /etc/sysconfig/geninitrd
fi

if [ -r /etc/sysconfig/bootsplash ]; then
	. /etc/sysconfig/bootsplash
fi

if [ -r /etc/sysconfig/fbsplash ]; then
	. /etc/sysconfig/fbsplash
fi

if [ ! -x /bin/initrd-busybox ]; then
	die "/bin/initrd-busybox is missing!"
fi

# backwards compatible
if [ "$USE_SUSPEND2" ]; then
	USE_TUXONICE=$USE_SUSPEND2
	echo >&2 "USE_SUSPEND2 is deprecated, use USE_TUXONICE now instead."
fi

while [ $# -gt 0 ]; do
	case $1 in
	--fstab=*)
		fstab=${1#--fstab=}
		;;
	--fstab)
		fstab=$2
		shift
		;;
	--modules-conf=*)
		modulefile=${1#--modules-conf=}
		;;
	--modules-conf)
		modulefile=$2
		shift
		;;
	--use-raidstart|--with-raidstart)
		USERAIDSTART=yes
		;;
	--without-raidstart)
		USERAIDSTART=no
		;;
	--use-insmod-static|--with-insmod-static)
		USEINSMODSTATIC=yes
		;;
	--without-insmod-static)
		USEINSMODSTATIC=no
		;;
	--with-bootsplash)
		BOOT_SPLASH=yes
		;;
	--without-bootsplash)
		BOOT_SPLASH=no
		;;
	--with-fbsplash)
		FB_SPLASH=yes
		;;
	--without-fbsplash)
		FB_SPLASH=no
		;;
	--with-suspend)
		USE_SUSPEND=yes
		;;
	--without-suspend)
		USE_SUSPEND=no
		;;
	--with-suspend2 | --with-tuxonice)
		USE_TUXONICE=yes
		;;
	--without-suspend2 | --without-tuxonice)
		USE_TUXONICE=no
		;;
	--lvmtoolsversion=|--lvmversion=)
		LVMTOOLSVERSION="`echo $1 | awk -F= '{print $2;}'`"
		;;
	--lvmtoolsversion|--lvmversion)
		LVMTOOLSVERSION=$2
		shift
		;;
	--without-udev)
		USE_UDEV=no
		;;
	--with-udev)
		USE_UDEV=yes
		;;
	--without-dmraid)
		USE_DMRAID=no
		;;
	--without-multipath)
		USE_MULTPATH=no
		;;
	--with=*)
		BASICMODULES="$BASICMODULES ${1#--with=}"
		;;
	--with)
		BASICMODULES="$BASICMODULES $2"
		shift
		;;
	--version)
		echo "$PROGRAM: version $VERSION"
		exit 0
		;;
	-v)
		verbose=-v
		;;
	--nocompress)
		COMPRESS=no
		;;
	--ifneeded)
		ifneeded=1
		;;
	-f)
		force=1
		;;
	--preload=*)
		PREMODS="$PREMODS ${1#--preload=}"
		;;
	--preload)
		PREMODS="$PREMODS $2"
		shift
		;;
	--fs=*)
		echo >&2 "Warning: --fs option is obsoleted. Use --initrdfs instead"
		INITRDFS=${1#--fs=}
		;;
	--fs)
		echo >&2 "Warning: --fs option is obsoleted. Use --initrdfs instead"
		INITRDFS=$2
		shift
		;;
	--initrdfs=*)
		INITRDFS=${1#--initrdfs=}
		;;
	--initrdfs)
		INITRDFS=$2
		shift
		;;
	--image-version)
		img_vers=yes
		;;
	--ide-only-root)
		ide_only_root="yes"
		;;
	*)
		if [ -z "$target" ]; then
			target="$1"
		elif [ -z "$kernel" ]; then
			kernel="$1"
		else
			usage
		fi
		;;
	esac

	shift
done

if [ -z "$target" -o -z "$kernel" ]; then
	usage
fi

pack_version="`echo "$kernel"|awk -F. '{print sprintf("%03d%03d",$1,$2)}'`"
pack_version_long="`echo "$kernel"|awk -F. '{print sprintf("%03d%03d%03d",$1,$2,$3)}'`"

if [ -z "$INITRDFS" ]; then
	if [ -z = "$FS" ]; then
		# default value
		if [ "$pack_version" -ge "002005" ]; then
			INITRDFS="initramfs"
		else
			INITRDFS="rom"
		fi
	else
		echo >&2 "Warning: FS configuration options is obsoleted. Use INITRDFS instead"
		INITRDFS="$FS"
	fi
fi

if [ "$pack_version" -lt "002006" ]; then
	USE_UDEV=no
	USE_DMRAID=no
fi

if [ "$pack_version" -ge "002005" ]; then
	modext=".ko"
	insmod="insmod"
fi

if is_yes "$USEINSMODSTATIC"; then
	insmod="insmod.static"
	INSMOD="/sbin/insmod.static"
	if [ "$pack_version" -lt "002005" -a -f /sbin/insmod.static.modutils ]; then
		INSMOD="/sbin/insmod.static.modutils"
	fi
	if [ ! -f "$INSMOD" ]; then
		die "insmod.static requested but /sbin/insmod.static not found!"
	fi
fi

case "$INITRDFS" in
	ext2)
		if [ ! -x /sbin/mke2fs ]; then
			die "/sbin/mke2fs is missing"
		fi
		;;
	rom|romfs)
		if [ ! -x /sbin/genromfs ]; then
			die "/sbin/genromfs is missing"
		fi
		;;
	cram|cramfs)
		if [ ! -x /sbin/mkcramfs ]; then
			die "/sbin/mkcramfs is missing"
		fi
		;;
	initramfs)
		if [ ! -x /bin/cpio ]; then
			die "/bin/cpio is missing"
		fi
		if [ ! -x /usr/bin/find ]; then
			die "/usr/bin/find is missing"
		fi
		;;
	*)
		die "Filesystem $INITRDFS on initrd is not supported"
		;;
esac

if [ -n "$img_vers" ]; then
	target="$target-$kernel"
fi

if [ -z "$force" -a -f "$target" ]; then
	die "$target already exists."
fi

if [ ! -d "/lib/modules/$kernel" ]; then
	die "/lib/modules/$kernel is not a directory."
fi

if is_yes "$USE_SUSPEND" && is_yes "$USE_TUXONICE"; then
	die "Tuxonice shouldn't be used in parallel with mainline suspend!."
fi

if is_yes "$FB_SPLASH"; then
	if is_yes "$BOOT_SPLASH"; then
		die "You can't use both bootsplash and fbsplash! Please choose one."
	elif [ "$INITRDFS" != "initramfs" ]; then
		die "FB_SPLASH works only if INITRDFS is initramfs!."
	fi
fi

if [ ! -f /proc/mounts ]; then
	echo >&2 "WARNING: /proc filesystem not mounted, may cause wrong results or failure."
fi

if [ -d /usr/lib64 ]; then
	_lib=lib64
else
	_lib=lib
fi
debug "_lib: $_lib"

cache_modprobe_conf

for n in $PREMODS; do
	findmodule "$n"
done

# allow forcing loading SCSI and/or IDE modules
if is_yes "$ADDSCSI"; then
	find_modules_scsi
fi

if is_yes "$ADDIDE"; then
	find_modules_ide
fi

find_root "$fstab" || exit
debug "Using $rootdev as device for rootfs"

find_modules_for_device "$rootdev"
[ -n "$rootdev_add" ] && find_modules_for_device "$rootdev_add"

findmodule "-$rootFs"

for n in $BASICMODULES; do
	findmodule "$n"
done

if is_yes "$USE_TUXONICE"; then
	findmodule "-lzf"
fi

if is_yes "$FB_SPLASH"; then
	findmodule "-evdev"
fi

if [ -n "$ifneeded" -a -z "$MODULES" ]; then
	debug "No modules are needed -- not building initrd image."
	exit 0
fi
debug "Using modules: $MODULES"

MNTIMAGE="`mktemp -d /tmp/initrd.XXXXXX`"
IMAGE="`mktemp -u /tmp/initrd.img-XXXXXX`"
MNTPOINT="`mktemp -d /tmp/initrd.mnt-XXXXXX`"
RCFILE="$MNTIMAGE/linuxrc"

if [ -f "$MNTIMAGE" ]; then
	die "$MNTIMAGE already exists. Remove it and try again"
fi

if [ -f "$IMAGE" ]; then
	die "$IMAGE already exists. Remove it and try again"
fi

mkdir -p "$MNTPOINT"
# We don't need this directory, so let's save space
rm -rf "$MNTPOINT"/lost+found

> "$RCFILE"
chmod a+rx "$RCFILE"
ln -s linuxrc $MNTIMAGE/init

# create dirs that we really need
inst_d /{lib,bin,etc,dev{,/pts,/shm},loopfs,var,proc,sys}

modules_install "$MODULES"

# mknod'ing the devices instead of copying them works both with and
# without devfs...
mknod "$MNTIMAGE/dev/console" c 5 1
mknod "$MNTIMAGE/dev/null" c 1 3
mknod "$MNTIMAGE/dev/zero" c 1 5

inst /bin/initrd-busybox /bin/initrd-busybox
ln -s initrd-busybox $MNTIMAGE/bin/sh
ln -s initrd-busybox $MNTIMAGE/bin/busybox # for older busyboxes who had /bin/busybox as EXEPATH

if is_yes "$USEINSMODSTATIC"; then
	inst "$INSMOD" /bin/insmod.static
fi

add_linuxrc <<EOF
#!/bin/sh
# initrd generated by:
# $RCSID

EOF
mount_proc
add_linuxrc <<-'EOF'
	export CMDLINE="$(cat /proc/cmdline)"

	for arg in $CMDLINE; do
		if [ "${arg}" = "debuginitrd" ]; then
			DEBUGINITRD=yes
		fi
		if [ "${arg##debuginitrd=}" != "${arg}" ]; then
			DEBUGINITRD=${arg##debuginitrd=}
		fi
	done

	# make debugshell() invoke subshell if $DEBUGINITRD=sh
	if [ "$DEBUGINITRD" = "sh" ]; then
		debugshell() {
			sh
		}
	else
		debugshell() {
			:
		}
	fi

	if [ "$DEBUGINITRD" ]; then
		set -x
	fi
EOF

modules_add_linuxrc "$MODULES"

# TODO: rewrite for busybox
#if [ -n "$loopDev" ]; then
#	if [ ! -d /initrd ]; then
#		mkdir /initrd
#	fi
#
#	cp -a "$loopDev" "$MNTIMAGE/dev"
#	cp -a "$rootdev" "$MNTIMAGE/dev"
#	echo "echo Mounting device containing loopback root filesystem" >> "$RCFILE"
#	echo "mount -t $loopFs $loopDev /loopfs" >> "$RCFILE"
#	echo "echo Setting up loopback device $rootdev" >> $RCFILE
#	echo "losetup $rootdev /loopfs$loopFile" >> "$RCFILE"
#fi

initrd_gen_suspend() {
	if [ ! -x /usr/${_lib}/suspend/resume -a ! -x /usr/sbin/resume ]; then
		die "/usr/${_lib}/suspend/resume is missing!"
	fi
	resume_dev="$(awk '/^resume device =/ { print $4 } ' /etc/suspend.conf)"
	mknod $MNTIMAGE/dev/snapshot c 10 231
	inst $resume_dev /dev
	inst /etc/suspend.conf /etc/suspend.conf
	if [ -x /usr/${_lib}/suspend/resume ]; then
		inst /usr/${_lib}/suspend/resume /bin/resume
	else
		inst /usr/sbin/resume /bin/resume
	fi
	echo "resume" | add_linuxrc
}

initrd_gen_tuxonice() {
	mount_sys
	add_linuxrc <<-'EOF'
		if [ "$(echo "$CMDLINE" | awk ' /resume2=/  { print "yes"; } ' /proc/cmdline)" = "yes" ]; then
			[ -e /proc/suspend2/do_resume ] && echo > /proc/suspend2/do_resume
			[ -e /sys/power/suspend2/do_resume ] && echo > /sys/power/suspend2/do_resume
			[ -e /sys/power/tuxonice/do_resume ] && echo >  /sys/power/tuxonice/do_resume
		fi
	EOF
}

initrd_gen_udev() {
	debug "Setting up udev..."
	inst_d /sbin /etc/udev

	if [ ! -x /sbin/initrd-udevd ]; then
		die "/sbin/initrd-udevd not present"
	fi

	inst /sbin/initrd-udevd /sbin/udevd
	inst /etc/udev/udev.conf /etc/udev/udev.conf

	mount_dev
	mount_sys
	add_linuxrc <<-'EOF'
		: 'Starting udev'
		/sbin/udevd --daemon
	EOF
	if is_yes "$PROBESTATICMODS"; then
		inst /sbin/initrd-udevtrigger /sbin/udevtrigger
		inst /sbin/initrd-udevsettle /sbin/udevsettle
		add_linuxrc <<-'EOF'
			/sbin/udevtrigger
			/sbin/udevsettle
		EOF
	fi

	busybox_applet killall
	add_linuxrc	<<-'EOF'
		killall udevd
	EOF
}

initrd_gen_multipath() {
	inst_d /sbin /lib/udev
	inst_exec /sbin/kpartx /sbin
	inst_exec /sbin/multipath /sbin
	# for udev callouts
	inst_exec /sbin/scsi_id /lib/udev
	inst_exec /sbin/mpath* /sbin
	inst /etc/multipath.conf /etc
	if [ -f /var/lib/multipath/bindings ]; then
		inst_d /var/lib/multipath
		inst /var/lib/multipath/bindings /var/lib/multipath
	fi

	mount_dev
	initrd_gen_devices

	mount_sys
	echo "export multipath_id=$MULTIPATH_ID" | add_linuxrc
	add_linuxrc <<-'EOF'
		debugshell
		/sbin/multipath -v 0 $multipath_id

		for a in /dev/mapper/*; do
			[ $a = /dev/mapper/control ] && continue
			/sbin/kpartx -a $a
		done
		debugshell
	EOF
}

initrd_gen_dmraid() {
	if [ ! -x /sbin/dmraid-initrd ]; then
		die "/sbin/dmraid-initrd is missing!"
	fi

	inst_d /sbin
	inst /sbin/dmraid-initrd /sbin/dmraid

	mount_dev
	mount_sys
	initrd_gen_devices
	add_linuxrc <<-EOF
		# 2 secs was enough for my system to initialize. but really this is udev issue?
		usleep 2000000
		: 'Activating Device-Mapper RAID(s)'
		/sbin/dmraid -ay -i

		debugshell
	EOF
}

initrd_gen_bootsplash() {
	local target="$1"

	debug "generating bootsplash"
	if [ ! -x /bin/splash.bin ]; then
		echo >&2 "Failed to execute /bin/splash.bin. Is bootsplash package installed?"
	elif [ -z "$THEME" ]; then
		echo >&2 "Please configure your /etc/sysconfig/bootsplash first."
		echo >&2 "Generating bootsplashes skipped."
	else
		if [ -n "$BOOT_SPLASH_RESOLUTIONS" ]; then
			for res in $BOOT_SPLASH_RESOLUTIONS; do
				if [ -f "/etc/bootsplash/themes/$THEME/config/bootsplash-$res.cfg" ]; then
					/bin/splash.bin -s -f "/etc/bootsplash/themes/$THEME/config/bootsplash-$res.cfg" >> "$target" && \
					debug "Added $res $THEME theme to initrd."
				else
					echo >&2 "/etc/bootsplash/themes/$THEME/config/bootsplash-$res.cfg doesn't exist, skipped"
				fi
			done
		else
			echo >&2 "No BOOT_SPLASH_RESOLUTIONS specified in /etc/sysconfig/bootsplash."
			echo >&2 "Not adding bootsplash to initrd."
		fi
	fi
}

initrd_gen_fbsplash() {
	debug "generating fbsplash"

	if [ ! -x /usr/bin/splash_geninitramfs ]; then
		echo >&2 "Failed to execute /usr/bin/splash_geninitramfs. Is splashutils package installed?"
	elif [ -z "$SPLASH_THEME" ]; then
		echo >&2 "Please configure your /etc/sysconfig/fbsplash first."
		echo >&2 "Generating fbsplashes skipped."
	else
		if [ -n "$FB_SPLASH_RESOLUTIONS" ]; then
			for res in $FB_SPLASH_RESOLUTIONS; do
				if [ -f "/etc/splash/$SPLASH_THEME/$res.cfg" ]; then
					/usr/bin/splash_geninitramfs -c $MNTIMAGE -r $res $SPLASH_THEME && \
					debug "Added $res $SPLASH_THEME theme to initramfs."
				else
					echo >&2 "/etc/splash/$SPLASH_THEME/$res.cfg doesn't exist, skipped"
				fi
			done
		else
			echo >&2 "No FB_SPLASH_RESOLUTIONS specified in /etc/sysconfig/fbsplash."
			echo >&2 "Not adding fbsplash to initramfs."
		fi
	fi
}

# Generates /dev nodes based on /proc/partitions information.
# Needs /proc mounted.
# Can be called multiple times.
initrd_gen_devices() {
	if is_yes "$proc_partitions"; then
		return
	fi
	proc_partitions=yes

	mount_dev
	add_linuxrc <<-'EOF'
		: 'Making device nodes'
		cat /proc/partitions | (
			# ignore first two lines, header, empty line and process rest
			read b; read b

			while read major minor blocks dev rest; do
				node=/dev/$dev
				mkdir -p ${node%/*}
				mknod $node b $major $minor
			done
		)
	EOF
}

initrd_gen_md() {
	debug "Setting up mdadm..."

	if [ ! -x /sbin/mdadm -o ! -x /sbin/initrd-mdassemble ]; then
		die "/sbin/mdadm or /sbin/initrd-mdassemble is missing!"
	fi

	inst /sbin/initrd-mdassemble /bin/mdassemble

	# LVM on RAID case
	dev_list_extra=$(awk '/^DEVICE / { for (i=2; i<=NF; i++) { printf "%s ", $i; }; } ' /etc/mdadm.conf)
	for ex_dev in $dev_list_extra; do
		echo "DEVICE $ex_dev" >> "$MNTIMAGE/etc/mdadm.conf"
	done
	do_md0=1
	for nr in `seq 1 $rootdev_nr`; do
		eval cr_rootdev="\$rootdev${nr}"
		eval cr_dev_list="\$dev_list${nr}"
		debug echo "Setting up array ($cr_rootdev = $cr_dev_list)"

		[ "$cr_rootdev" = "/dev/md0" ] && do_md0=0

		echo "DEVICE $cr_dev_list" >> "$MNTIMAGE/etc/mdadm.conf"
		cr_dev_list_md="$(echo "$cr_dev_list" | xargs | awk ' { gsub(/ +/,",",$0); print $0; }')"
		cr_md_conf=$(/sbin/mdadm --detail --brief --config=/etc/mdadm.conf $cr_rootdev | awk ' { gsub(/spares=[0-9]+/, "", $0); print $0; }')
		if [ -n "$cr_md_conf" ]; then
			echo "$cr_md_conf" >> "$MNTIMAGE/etc/mdadm.conf"
		else
			echo "ARRAY $cr_rootdev devices=$cr_dev_list_md" >> "$MNTIMAGE/etc/mdadm.conf"
		fi

		for f in $cr_dev_list $cr_rootdev $dev_list_extra; do
			# mkdir in case of devfs name
			inst_d $(dirname $f)
			[ -e "$MNTIMAGE/$f" ] && continue
			# this works fine with and without devfs
			inst $f $f
		done
	done

	echo "mdassemble" | add_linuxrc

	# needed to determine md-version
	if [ "$do_md0" -eq 1 ]; then
		mknod $MNTIMAGE/dev/md0 b 9 0
	fi
}

initrd_gen_nfs() {
	# use root=/dev/ram0 init=/linuxrc when starting kernel or you will
	# have problems like init(XX) being child process of swapper(1).
	debug "Adding rootfs on NFS support to initrd (dhcp)"
	mknod "$MNTIMAGE/dev/urandom" c 1 9
	mkdir "$MNTIMAGE/newroot"
	mkdir "$MNTIMAGE/proc"
	echo "ifconfig lo 127.0.0.1 up" | add_linuxrc
	echo "route add -net 127.0.0.0 netmask 255.0.0.0 lo" | add_linuxrc
	echo "ifconfig eth0 0.0.0.0 up" | add_linuxrc
	echo "udhcpc -i eth0 -f -q -s /bin/setdhcp" | add_linuxrc

	cat <<-'EOF' > "$MNTIMAGE/bin/setdhcp"
		#!/bin/sh
		[ "$1" != "bound" ] && exit
		[ -n "$broadcast" ] && BROADCAST="broadcast $broadcast"
		[ -n "$subnet" ] && NETMASK="netmask $subnet"
		ifconfig $interface $ip $BROADCAST $NETMASK up
		if [ -n "$router" ]; then
			for r in $router; do
				route add default gw $r dev $interface
			done
		fi
	EOF

	cat <<-'EOF' > "$MNTIMAGE/bin/setdhcp"
		for o in $(cat /proc/cmdline); do
			case $o in
			nfsroot=*)
				rootpath=${o#nfsroot=}
				;;
			esac
		done

		if [ -n "$rootpath" ]; then
			mount -n -t nfs -o ro,nolock,posix,tcp,wsize=8192,rsize=8192 $rootpath /newroot
		else
			echo "Missing rootpath in what DHCP server sent to us. Failing..."
			echo "All seen variables are listed below:"
			set
		fi
	EOF

	chmod 755 "$MNTIMAGE/bin/setdhcp"
	add_linuxrc <<-'EOF'
		cd /newroot
		pivot_root . initrd
		[ -x /sbin/chroot ] && exec /sbin/chroot . /sbin/init -i < dev/console > dev/console 2>&1
		exec /usr/sbin/chroot . /sbin/init -i < dev/console > dev/console 2>&1
	EOF
}

initrd_gen_lvm() {
	debug "Adding LVM support to initrd"
	inst_d /tmp /newroot
	inst /sbin/initrd-lvm /bin/lvm.static

	# always make /dev on tmpfs for LVM2
	if [ "$LVMTOOLSVERSION" = "2" ]; then
		mount_dev
	fi

	if ! is_yes "$dev_mounted"; then
		inst_d /dev/mapper
		mknod $MNTIMAGE/dev/mapper/control c 10 63
		for device in $PVDEVICES; do
			# if LVM on RAID then device might be copied already in gen_md
			[ -e "$MNTIMAGE/dev/$(basename $device)" ] && continue
			inst $device /dev
		done
	fi

	mount_tmp
	if [ "$LVMTOOLSVERSION" = "1" ]; then
		add_linuxrc <<-EOF
			lvm vgscan -T
			lvm vgchange -T -a y $VGVOLUME
		EOF
	else
		echo "cat /etc/lvm.conf > /tmp/lvm.conf" | add_linuxrc
		echo "global {" > "$MNTIMAGE/etc/lvm.conf"
		echo "	locking_type = 0" >> "$MNTIMAGE/etc/lvm.conf"
		echo "	locking_dir = \"/tmp\"" >> "$MNTIMAGE/etc/lvm.conf"
		echo "}" >> "$MNTIMAGE/etc/lvm.conf"
		echo "devices {" >> "$MNTIMAGE/etc/lvm.conf"
		echo "	sysfs_scan=0" >> "$MNTIMAGE/etc/lvm.conf"
		if is_yes "$have_md"; then
			echo "	md_component_detection = 1" >> "$MNTIMAGE/etc/lvm.conf"
		fi
		if is_yes "$have_dmraid" || is_yes "$have_multipath"; then
			echo '	types = [ "device-mapper", 254 ]' >> "$MNTIMAGE/etc/lvm.conf"
		fi
		if [ "$lvm_ignore_devices" ]; then
			# TODO: think of merging with lvm dumpconfig output
			echo '	filter = [' >> "$MNTIMAGE/etc/lvm.conf"
			local dev
			for dev in $lvm_ignore_devices; do
				debug "LVM2: ignore device $dev"
				printf '  "r|^%s.*|",\n' $dev
			done >> "$MNTIMAGE/etc/lvm.conf"
			echo ']' >> "$MNTIMAGE/etc/lvm.conf"
		fi
		# XXX filter= must be on one line!
		lvm dumpconfig | awk '/filter=/' >> "$MNTIMAGE/etc/lvm.conf"
		echo "}" >> "$MNTIMAGE/etc/lvm.conf"

		initrd_gen_devices

		add_linuxrc <<-EOF
			export LVM_ROOTDEV=$rootdev
			export LVM_VGVOLUME=$VGVOLUME
		EOF
		add_linuxrc <<-'EOF'
			# disable noise from lvm accessing devices that aren't ready.
			printk=$(cat /proc/sys/kernel/printk)
			echo 0 > /proc/sys/kernel/printk

			export LVM_SYSTEM_DIR=/tmp
			: 'Scanning for Volume Groups'
			lvm.static vgscan --mknodes --ignorelockingfailure 2>/dev/null

			: 'Activating Volume Groups'
			lvm.static vgchange --ignorelockingfailure -a y $LVM_VGVOLUME 2>/dev/null

			echo "$printk" > /proc/sys/kernel/printk

			# Find out major/minor
			attrs="$(lvm.static lvdisplay --ignorelockingfailure -c $LVM_ROOTDEV 2>/dev/null)"
			if [ "$attrs" ]; then
				majmin="${attrs#*$LVM_ROOTDEV*:*:*:*:*:*:*:*:*:*:*:*}"
				if [ "$majmin" != "$attrs" ]; then
					major="${majmin%:*}"
					minor="${majmin#*:}"
				fi
			fi

			if [ "$major" -a "$minor" ]; then
				# Pass it to kernel
				echo $((256 * $major + $minor)) > /proc/sys/kernel/real-root-dev
			else
				echo 2>&1 "Error figuring out real root device for $LVM_ROOTDEV!"
				echo 2>&1 "System will not most likely boot up! So dropping you to a shell!"
				echo 2>&1 ""
				sh
			fi
		EOF
	fi
}

initrd_gen_procdata() {
	debug "Adding rootfs finding based on root= option support."
	add_linuxrc <<-'EOF'
		root="$(busybox awk ' /root=\/dev\// { gsub(/.*root=\/dev\//,NIL,$0); gsub(/ .*/,NIL,$0); print $0; } ' /proc/cmdline)"
		if [ -n "$root" ]; then
			rootnr="$(busybox awk -v root="$root" ' { if ($4 == root) { print 256*$1+$2; } } ' /proc/partitions)"
			if [ -n "$rootnr" ]; then
				echo "$rootnr" > /proc/sys/kernel/real-root-dev
			fi
		fi
	EOF
}

# main generation
if is_yes "$USE_UDEV"; then
	initrd_gen_udev
fi

if is_yes "$USE_SUSPEND"; then
	initrd_gen_suspend
fi

if is_yes "$USE_TUXONICE"; then
	initrd_gen_tuxonice
fi

if is_yes "$have_dmraid" ]; then
	initrd_gen_dmraid
fi

if is_yes "$have_multipath"; then
	initrd_gen_multipath
fi

if is_yes "$have_nfs"; then
	initrd_gen_nfs
elif is_yes "$USERAIDSTART" && is_yes "$have_md"; then
	initrd_gen_md
	if is_yes "$have_lvm"; then
		initrd_gen_lvm
	else
		initrd_gen_procdata
	fi
elif is_yes "$have_lvm"; then
	initrd_gen_lvm
else
	initrd_gen_procdata
fi

# additional devs always needed
[ ! -e "$MNTIMAGE/$rootdev_add" ] && inst $rootdev_add /dev

if [ "$INITRDFS" = "initramfs" ]; then
	inst_d /newroot
	[ ! -e "$MNTIMAGE/$rootdev" ] && inst $rootdev /dev
	# Parsing root parameter
	# We support passing root as hda3 /dev/hda3 0303 0x0303 and 303
	add_linuxrc <<-'EOF'
		eval "$(busybox awk -v c="$CMDLINE" '
		BEGIN {
			num_pattern_short = "[0-9a-f][0-9a-f][0-9a-f]";
			num_pattern = "[0-9a-f]" num_pattern_short;
			dev_pattern = "[hms][a-z][a-z]([0-9])+";
			partition = "no_partition_found";
			min = -1; maj = -1;

			gsub(/.*root=/,NIL,c);
			gsub(/ .*/,NIL,c);

			sub("^0x", "", c);
			if (c ~ "^" num_pattern_short "$") sub("^", "0", c);
			if (c ~ "^" num_pattern  "$") {
				maj = sprintf("%s",substr(c,1,2));
				min = sprintf("%s",substr(c,3));
			}
			if (c ~ "^\/dev\/" dev_pattern "$") sub("^/dev/","", c);
			if (c ~ "^" dev_pattern "$") partition = c;
		}

		$4 ~ partition { maj = $1; min = $2; }
		$1 ~ maj && $2 ~ min { partition = $4; }

		END {
			print sprintf("device=/dev/%s\nmaj=%s\nmin=%s",
				partition, maj, min);
		}
		' /proc/partitions)"
		if [ "$device" != '/dev/no_partition_found' -a ! -b $device ]; then
			mknod $device b $maj $min
		fi
	EOF

	add_linuxrc <<-EOF
		rootdev=$rootdev
		rootfs=$rootFs
	EOF

	add_linuxrc <<-'EOF'
		if [ "$device" = '/dev/no_partition_found' ]; then
			device=$rootdev
		fi

		mount -t $rootfs -r $device /newroot
		init="$(echo "$CMDLINE" | busybox awk '/init=\// { gsub(/.*init=/,NIL,$0); gsub(/ .*/,NIL,$0); print }')"
		if [ -z "$init" -o ! -x "/newroot$init" ]; then
			init=/sbin/init
		fi
	EOF

	umount_all
	busybox_applet switch_root
	add_linuxrc <<-'EOF'
		exec switch_root /newroot $init

		echo "Error! initramfs should not reach this place."
		echo "It probably means you've got old version of busybox, with broken"
		echo "initramfs support. Trying to boot anyway, but won't promise anything."

		exec chroot /newroot $init

		echo "Failed to chroot!"
	EOF
	# we need /init being real file, not symlink, otherwise the initramfs will
	# not be ran by pid 1 which is required for switch_root
	mv $MNTIMAGE/linuxrc $MNTIMAGE/init
else
	# other than initramfs
	umount_all
fi

if is_yes "$FB_SPLASH"; then
	initrd_gen_fbsplash
fi


(cd "$MNTIMAGE"; tar cf - .) | (cd "$MNTPOINT"; tar xf -)

case "$INITRDFS" in
	ext2)
		IMAGESIZE=$(du -ks $MNTPOINT | awk '{print int(($1+1023+512)/1024)*1024}')
		debug 	"ext2 image size: $IMAGESIZE ($MNTPOINT)"
		if [ "$IMAGESIZE" -gt 4096 ]; then
			echo >&2 "$PROGRAM: Your image size is larger than 4096, Be sure to boot kernel with ramdisk_size=$IMAGESIZE!"
		fi

		dd if=/dev/zero of="$IMAGE" bs=1k count="$IMAGESIZE" 2> /dev/null
		mke2fs -q -F -b 1024 -m 0 "$IMAGE" 2>/dev/null 1>&2
		tune2fs -i 0 "$IMAGE" >/dev/null 2>&1

		tmpmnt="`mktemp -d /tmp/initrd.mnte2-XXXXXX`"
		mount -o loop -t ext2 "$IMAGE" "$tmpmnt"

		(cd "$MNTPOINT"; tar cf - .) | (cd "$tmpmnt"; tar xf -)

		umount "$IMAGE"
		;;
	rom|romfs)
		genromfs -f "$IMAGE" -d "$MNTPOINT" -V "PLD initrd for kernel $kernel"
		IMAGESIZE=$(stat -c %s $IMAGE | awk '{print int((($1/1024)+1023)/1024)*1024}')
		debug 	"romfs image size: $IMAGESIZE ($IMAGE)"
		if [ "$IMAGESIZE" -gt 4096 ]; then
			echo >&2 "$PROGRAM: Your image size is larger than 4096, Be sure to boot kernel with ramdisk_size=$IMAGESIZE!"
		fi
		;;
	cram|cramfs)
		mkcramfs "$MNTPOINT" "$IMAGE"
		;;
	initramfs)
		(cd $MNTPOINT; find . | cpio --quiet -H newc -o > "$IMAGE")
		;;
	*)
		echo "Filesystem $INITRDFS not supported by $PROGRAM";
esac

if is_yes "$COMPRESS"; then
	gzip -9 < "$IMAGE" > "$target"
else
	cp -a "$IMAGE" "$target"
fi

if is_yes "$BOOT_SPLASH"; then
	initrd_gen_bootsplash "$target"
fi

rm -rf "$MNTIMAGE" "$MNTPOINT" "$IMAGE"

# vim:ts=4:sw=4:noet:fdm=marker
