#!/bin/bash

# $Id: mindi 1121 2007-02-09 17:49:33Z bruno $
#
#-----------------------------------------------------------------------------
# mindi - mini-Linux distro based on the user's filesystem & distribution
#
# Mindi can create a multi-floppy boot/root kit. The first floppy is the boot
# disk: it contains a kernel, a ramdisk etc. The second disk is data disk #1;
# the third disk is data disk #2; and so it goes.
#
# See http://www.mondorescue.org for details.
#-----------------------------------------------------------------------------

### Which arch are we on (useful for ia64 port)
ARCH=`/bin/arch`

#RUN_AFTER_INITIAL_BOOT_PHASE="echo \"Who lives in a pineapple under the sea?\" > /tmp/spongebob.squarepants.txt"
	# after booting from floppy/CD image but before
	# accessing auxiliary data disks (or the rest of
	# the CD), the initscript will run the above command.

RUN_AFTER_BOOT_PHASE_COMPLETE="ide-opt"
	# after the emergency boot process is complete but
	# before the init script runs mondorestore, it will
	# run this command.

MINDI_REV=RRR
MINDI_VER=VVV

MINDI_VERSION=${MINDI_VER}-r$MINDI_REV
MINDI_PREFIX=XXX
MINDI_CONF=YYY
MINDI_SBIN=${MINDI_PREFIX}/sbin
MINDI_LIB=LLL

MINDI_CONFIG_DIST="$MINDI_CONF/mindi.conf.dist"
if [ ! -f $MINDI_CONFIG_DIST ]; then
	echo "Unable to find $MINDI_CONFIG_DIST. Please reinstall mindi"
	exit -1
fi
md5sum --status -c "$MINDI_CONF/mindi.conf.dist.md5"
if [ $? -ne 0 ]; then
	echo "$MINDI_CONF/mindi.conf.dist md5 checksum incorrect. Please reinstall mindi"
	exit -1
fi
. $MINDI_CONFIG_DIST

MINDI_CONFIG="$MINDI_CONF/mindi.conf"
if [ ! -f $MINDI_CONFIG ]  && [ "_$1" = "_" ]; then
	echo "No $MINDI_CONFIG file found using sensible values from $MINDI_CONFIG_DIST"
else
	if [ "_$1" = "_" ]; then
		echo "Using $MINDI_CONFIG as additional config file to $MINDI_CONFIG_DIST"
	fi
	. $MINDI_CONFIG
fi	

#
# Manages defaults coming from conf files
#
INTERACTIVE="$mindi_interactive"

if [ $INTERACTIVE == "yes" ]; then
	# do you want to be prompted to write
	# floppy images out to floppy disks?
	# if 'no', images will not be written to floppies
	PROMPT_WRITE_BOOT_FLOPPIES="yes"

	# Ask if you want to make a CD Image to be written?
	# if this is set to 'no', then the image will be created automatically
	PROMPT_MAKE_CD_IMAGE="yes"

	# Ask if you want to make a USB Image to be written?
	# if this is set to 'no', then the image will be created automatically
	PROMPT_MAKE_USB_IMAGE="yes"

	# If set to "no", you will be prompted for whether or not
	# you want to use your own kernel, or the supplied default.
	# If "yes" mindi will automatically use your own kernel.
	USE_OWN_KERNEL="no"
fi

EXTRA_SPACE=$mindi_extra_space
IA64_BOOT_SIZE=$mindi_ia64_boot_size
DEPLIST_DIR="$MINDI_CONF/deplist.d"
DEPLIST_FILE="$MINDI_CONF/$mindi_deplist_file"
WRITE_BOOT_FLOPPIES="$mindi_write_boot_floppy"
PROMPT_MAKE_CD_IMAGE="$mindi_write_cd"
PROMPT_MAKE_USB_IMAGE="$mindi_write_usb"
PROMPT_MAKE_TAPE_IMAGE="$mindi_write_tape"
USE_OWN_KERNEL="$mindi_use_own_kernel"
MINDI_CACHE="$mindi_cache_dir"
FORCE_DUAL_FLOPPIES="$mindi_dual_floppies"
TMPDIR="$mindi_tmp_dir"
FDDEVICE="$mindi_fd_device"
USBDEVICE="$mindi_usb_device"
TAPEDEV="$mindi_tape_device"
ADDITIONAL_BOOT_PARAMS="$mindi_boot_params"
MY_FSTAB="$mindi_etc_fstab"
LOGFILE="$mindi_log_file"
FLOPPY_MODS="$mindi_floppy_mods"
TAPE_MODS="$mindi_tape_mods"
SCSI_MODS="$mindi_scsi_mods"
IDE_MODS="$mindi_ide_mods"
PCMCIA_MODS="$mindi_pcmcia_mods"
USB_MODS="$mindi_usb_mods"
CDROM_MODS="$TAPE_MODS $FLOPPY_MODS $IDE_MODS $mindi_cdrom_mods $USB_MODS $PCMCIA_MODS"
NET_MODS="$mindi_net_mods"
EXTRA_MODS="$CDROM_MODS $mindi_extra_mods $mindi_additional_mods"

BOOT_MEDIA_MESSAGE="$mindi_boot_msg"
FDISK=$MINDI_SBIN/parted2fdisk
MINDI_TMP=`mktemp -d $TMPDIR/mindi.XXXXXXXXXX`

# ----------------------------------------------------------------------------


AbortHere() {
	[ "$mountpoint" ] && umount $mountpoint 2>> $LOGFILE
	Die "Program is terminating in response to signal received from OS/user"
}


HackSyslinuxFile() {
	local incoming
	incoming=`ReadLine`
	while [ "$incoming" ] ; do
		echo -en "$incoming" | sed s/24000/$1/
		if [ "`echo "$incoming" | grep append`" ] ; then
		    echo -en " $ADDITIONAL_BOOT_PARAMS"
		fi
		echo -en "\n"
		incoming=`ReadLine`
	done
	if [ -e "$MINDI_LIB/memtest.img" ] ; then
		echo -en "label memtest\n  kernel memdisk\n  append initrd=memtest.img\n\n"
	fi
}


Aborted() {
	trap SIGHUP SIGTERM SIGTRAP SIGINT
	[ "$MINDI_CACHE" != "" ] && rm -f $MINDI_CACHE/mindi*img $MINDI_CACHE/*gz $MINDI_CACHE/mindi.iso
	[ "$minidir_root" != "" ] && rm -Rf $minidir_root/*
	Die "User abort."
}


AddFileToDir() {
	local filename minidir_root noof_disks diskno res filesize disksize would_occupy zipsize complevel cutoff compressed_fname siz
	filename=$1
	minidir_root=$2
	noof_disks=$3

	diskno=$noof_disks
	mkdir -p $minidir_root/$diskno
	[ "$LAST_COMPRESSED_SIZE" = "" ] && LAST_COMPRESSED_SIZE=0
	if [ ! -e "$filename" ] ; then
		if [ -h "$filename" ] ; then
			cp --parents -pRdf $filename $minidir_root/$diskno 2>> $LOGFILE
			return $noof_disks
		else
			Die "AddFileToDir asked me to add $filename, which does not exist. Oops! Did you run out of disk space or is your Linux distro severely broken?"
		fi
	fi

	# move to the disk that has room on it (or end up using the last, if all full)
	while [ "$diskno" -lt "40" ] ; do
		mkdir -p $minidir_root/$diskno
		filesize=`du -sk $filename | cut -f1`
		cp --parents -Rdf $filename $minidir_root/$diskno 2>> $LOGFILE
		if [ "$filesize" -le "4" ] ; then
		    siz=$filesize
		elif [ ! -f "$filename" ] ; then
		    siz=0
		else
		    siz=`grep -m 1 "$filename.gz$" $minidir_root/compressed/compressed.txt | cut -f1`
		    [ "$siz" = "" ] && Die "FIXME - can't find $filename's size."
		    siz=$(($siz-2));# to allow for sectors & the fact that they round up
		fi
		[ ! "$siz" ] && siz=4
		[ "$siz" -lt "0" ] && siz=0
		LAST_COMPRESSED_SIZE=$(($LAST_COMPRESSED_SIZE+$siz))
		[ "$LAST_COMPRESSED_SIZE" -le "$MAX_COMPRESSED_SIZE" ] &&return $diskno
		echo "disk=$diskno siz=$LAST_COMPRESSED_SIZE" >> $LOGFILE
		LAST_COMPRESSED_SIZE=0
		rm -f $minidir_root/$diskno/$filename
		diskno=$(($diskno+1))
	done
	return 0 ; # failed
}


AddKeyboardMappingFile() {
	local mappath r included_list included_item i res ii sss
	mappath=$1
	KBDEPTH=$(($KBDEPTH+1))
	[ "$KBDEPTH" -gt "128" ] && Die "Edit $MINDI_SBIN/mindi and disable FindAndAddUserKeyboardMappingFile (line 2160, approx.)"
	if [ -e "$bigdir/$mappath" ] ; then
		echo "$mappath already added" >> $LOGFILE
		return
	elif [ -d "$bigdir/$mappath" ] ; then
		echo "Cannot add $mappath: it's a directory. Sorry."
		return
	fi
	echo "Added kbd map $mappath" >> $LOGFILE
	if [ ! -e "$mappath" ] ; then
			mappath=`grep "i[3-8]86" $MINDI_TMP/keymaps.find | grep "$locale[^r][^/]" | grep -vx " *#.*"`
		if [ ! -e "$mappath" ] ; then
		    LogIt "Cannot add $mappath: kbd map file not found"
		    return
		fi
	else
		echo -en "`basename $mappath | tr '.' '#' | sed s/#kmap#gz// | sed s/#inc#gz//` " | tr '#' '.'
	fi

	mkdir -p $bigdir/etc
	cp --parents -pRdf $mappath $bigdir 2>> $LOGFILE || LogIt "AKMF -- Could not copy $mappath to $bigdir"
	if [ "`echo $mappath | grep -F ".gz"`" ] ; then
		included_list=`gzip -dc $mappath | grep -Fi include | sed s/'"'// | sed s/'"'// | cut -d' ' -f2`
	else
		included_list=`grep -Fi include $mappath | sed s/'"'// | sed s/'"'// | cut -d' ' -f2`
	fi
	for included_item in $included_list ; do
		if [ ! -e "$included_item" ] ; then
				sss=`grep -F "${included_item}.inc" $MINDI_TMP/keymaps.find`
			[ "$sss" = "" ] && sss=`grep -F "$included_item" $MINDI_TMP/keymaps.find`
			for ii in $sss ; do
		        [ -e "$ii" ] && AddKeyboardMappingFile $ii
			done
		else
			AddKeyboardMappingFile $included_item
		fi
	done
}


ChopUpAndCopyFile() {
	local filename slicesize outdir res biggienumber filesize sliceno noof_slices testfile scratchfile
	filename=$1
	outdir=$2
	slicesize=$3
	biggienumber=$4

	[ -d "$filename" ] && Die "Cannot chop up $filename: it's a directory. Please amend $DEPLIST_FILE accordingly."
	mkdir -p $outdir

	sliceno=0
	scratchfile=$MINDI_TMP/blah.$$.dat
	cp -f $filename $scratchfile 2>> $LOGFILE || Die "CUACF -- cannot copy $filename to $scratchfile - did you run out of disk space?"
	[ "`head $scratchfile -n1 | grep -F "bin/sh"`" != "" ] && StripComments $scratchfile "-$filename-"
	[ "`echo "$filename" | grep -F "etc/termcap"`" != "" ] && StripComments $scratchfile "-$filename-"
	if [ "`echo "$filename" | grep -F "lib/modules/" | grep "\.*o\.gz"`" != "" ] ; then
		mv $scratchfile $scratchfile.gz
		gunzip -f $scratchfile || LogIt "Cannot gunzip $scratchfile.gz"
		filename=`echo "$filename" | tr '.' '#' | sed s/#o#gz/#o/ | sed s/#ko#gz/#ko/ | tr '#' '.'`
	fi
	filesize=`du -sk $scratchfile | cut -f1`
	noof_slices=$(($filesize/$slicesize))
	echo "$filename" > $outdir/slice-$biggienumber.name
	echo "$filesize" > $outdir/slice-$biggienumber.size
	[ -x "$scratchfile" ] && StripExecutable $scratchfile "-$filename-"
	while [ "$sliceno" -le "$noof_slices" ] ; do
		dd if=$scratchfile skip=$(($sliceno*$slicesize)) of=$outdir/slice-$biggienumber.`printf "%03d" $sliceno` bs=1k count=$slicesize &> /dev/null
		sliceno=$(($sliceno+1))
	done
	rm -f $scratchfile
}


CopyBootBFile() {
	local copy_to copy_from possible_locations liloc
	copy_to=$1
	copy_from=/boot/boot.b
	liloc=`which lilo.real 2>/dev/null`
	[ $liloc ] || liloc=`which lilo 2>/dev/null`
	if [ $liloc ]; then
		if ! [ `strings $liloc | grep "boot\.b"` ]; then
		    LogIt "boot.b files built into lilo; I'll create a dummy."
		    > $copy_to
		    return 0
		fi
	fi
	if [ ! -f "$copy_from" ] ; then
		LogIt "OK, you don't have a /boot/boot.b file, which is odd because\n most _good_ Linux distributions come with one, even if it's only a softlink"
		copy_from=`grep install= /etc/lilo.conf | grep "\.b" | cut -d'=' -f2`
		if [ ! -f "$copy_from" ] ; then
		    LogIt "Nor can I find it from your /etc/lilo.conf file. This is very odd."
		    copy_from=`FindSensibleBootBFile`
		    LogIt "I'm going to use '$copy_from'"
		fi
	fi
	cp -f $copy_from $copy_to 2>> $LOGFILE || LogIt "CBBF -- warning -- cannot find your boot.b file. That's it, I quit... (j/k)"
}


CopyDependenciesToDirectory() {
	local outdir incoming fname filesize counter
	outdir=$1
	mkdir -p $outdir
	incoming=`ReadLine`
	counter=0
	while [ "$incoming" != "" ] ; do
		if [ -d "$incoming" ] ; then
		    find $incoming/* -maxdepth 0 2> /dev/null | CopyDependenciesToDirectory $outdir
		elif [ -e "$incoming" ] ; then
		    filesize=`du -sk $incoming | cut -f1`
		    if [ "$filesize" -gt "$(($CHOPSIZE*2))" ] && [ ! -h "$incoming" ] ; then
		        ChopUpAndCopyFile $incoming $outdir $CHOPSIZE $BIGNO
		        BIGNO=$(($BIGNO+1))
		    else
		        cp --parents -Rdf $incoming $outdir 2> /dev/null || Die "Cannot copy $incoming to $outdir - did you run out of disk space?"
				if [ "`echo "$incoming" | grep "lib/modules/.*\..*o\.gz"`" != "" ] ; then
		    		gunzip -f $outdir/$incoming || LogIt "Cannot gunzip $outdir/$incoming"
				fi
				[ -x "$outdir" ] && StripExecutable $outdir "-$filename-"
			fi
			counter=$(($counter+1))
			if [ "$counter" -ge "5" ] ; then
				counter=0
		    	echo -en "."
			fi
		fi
		incoming=`ReadLine`
	done
}


CopyImageToDisk() {
	local image dev procno res comment
	image=$1
	dev=$2
	comment=$3
	[ ! -f "$image" ] && [ ! -b "$image" ] && Die "Image $image does not exist. Did you run out of disk space?"
	Prompt "About to write $comment. Please press ENTER."
	echo -en "Formatting disk..."
	if which fdformat > /dev/null ; then
		fdformat -n $dev > /dev/null 2> /dev/null || Die "Cannot format $dev - is your Linux distro broken?"
	elif which superformat > /dev/null ; then
		superformat $dev > /dev/null 2> /dev/null || Die "Cannot format $dev - is your Linux distro broken?"
	else
		Die "Please install either fdformat or superformat."
	fi
	echo -en "\rWriting $comment"
	if echo $image | grep "mindi-[r|b]oot\.1440" &> /dev/null ; then
		cat $image > $dev &
	else
		dd if=$image of=$dev &> /dev/null &
	fi
	procno=$!
	ps $procno > /dev/null 2> /dev/null
	while [ "$?" -eq "0" ] ; do
		sleep 3
		echo -en "."
		ps $procno > /dev/null 2> /dev/null
	done
	echo -e "$DONE"
	LogIt "$comment has been written."
}


CountItemsIn() {
	local r
	r=0
	for q in $1 ; do
		r=$(($r+1))
	done
	echo $r
}


CreateDataDiskImagesFromTarballs() {
	local tardir outdir diskno noof_disks kp
	tardir=$1
	outdir=$2
	noof_disks=$3

	mkdir -p $outdir
	diskno=1
	echo -en "Creating data disk "
	while [ "$diskno" -le "$noof_disks" ] ; do
		echo -en "#$diskno..."
		cp -f $tardir/$diskno.tar.gz $outdir 2>> $LOGFILE || LogIt "[line 424] Cannot copy $tardir/$diskno.tar.gz to $outdir"
		CreateOneDataDiskImage $tardir/$diskno.tar.gz $outdir/mindi-data-$diskno.img $diskno $noof_disks
		diskno=$(($diskno+1))
	done
	mv -f $tardir/all.tar.gz $outdir
	du -sk $outdir/*gz >> $LOGFILE
	echo -e "$DONE"
}



CreateOneDataDiskImage() {
	local tarball imagefile dev diskno noof_disks mountpoint
	tarball=$1
	imagefile=$2
	diskno=$3
	noof_disks=$4

	mountpoint=$MINDI_TMP/mountpoint.$$
	mkdir -p $mountpoint
	dd if=/dev/zero of=$imagefile bs=1k count=1440 &> /dev/null || LogIt "Cannot dd (CODI)"
	echo "Creating ext2 filesystem on $imagefile" >> $LOGFILE
	mke2fs -N 12 -F $imagefile >> $LOGFILE 2>> $LOGFILE
	mount -t ext2 -o loop $imagefile $mountpoint || Die "Can't loopmount $imagefile to $mountpoint! The reason may be missing support for loopfs or ext2 (or both) in the running kernel."
	mv $tarball $mountpoint/
	if [ "$?" -ne "0" ] ; then
		umount $mountpoint
		rmdir $mountpoint
		Die "Tarball $tarball is too big for disk! (CODI)\nAdjust mindi_max_compressed_size in your $MINDI_CONFIG"
	fi
	[ "$diskno" -eq "$noof_disks" ] && echo "This is the last disk ($diskno=$noof_disks)" >> $mountpoint/LAST-DISK
	umount $mountpoint || LogIt "Cannot umount (CODI)"
	rmdir $mountpoint || LogIt "Cannot rmdir (CODI)"
}

# Last function called before exiting
# Parameter is exit code value
MindiExit() {
	local my_partitions

	echo "Mindi $MINDI_VERSION is exiting" >> $LOGFILE
	echo "End date : `date`" >> $LOGFILE

	sync
	cd /

	# Unmount whtat could remain mounted
	my_partitions=`mount | grep -F $$ | cut -f1 -d' '`
	[ "$my_partitions" != "" ] && umount $my_partitions
	# Clean temporary files only when standalone mindi
	if [ _"$MINDI_TMP" != _"$MONDO_TMP" ]; then
		rm -Rf $MINDI_TMP
	fi
	exit $1
}

Die() {
	local i
	if [ "$1" = "" ] ; then
		LogIt "FATAL ERROR"
	else
		LogIt "FATAL ERROR. $1"
	fi

	# Creates a tar file containing all required files
	for i in $MY_FSTAB /etc/lilo.conf /etc/raidtab $LOGFILE /var/log/mondo-archive.log ; do
		[ -e "$i" ] && cp -f $i $MINDI_TMP 2>> $LOGFILE
	done
	rm -f $TMPDIR/mindi.err.*.tgz
	tar -cf - $MINDI_TMP | gzip -9 > $TMPDIR/mindi.err.$$.tgz
	LogIt "Please e-mail a copy of $TMPDIR/mindi.err.$$.tgz to the mailing list."
	LogIt "See http://www.mondorescue.org for more information."
	LogIt "WE CANNOT HELP unless you enclose that file.\n"
	MindiExit -1
}


DropOptimizedLibraries() {
	local outdir filelist list_of_optimized_libraries optimized_lib_name vanilla_lib_name reason msg resolved res
	filelist=$1
	outdir=$2

	list_of_optimized_libraries=`grep "lib/i[5-7]86/" $filelist`
	if [ "$list_of_optimized_libraries" = "" ] ; then
		return 0
	fi
	echo -en "Dropping i686-optimized libraries if appropriate"
	for optimized_lib_name in $list_of_optimized_libraries ; do
		echo -en "."
		reason=""
		vanilla_lib_name=`echo "$optimized_lib_name" | sed s/i[5-7]86// | tr -s '/' '/'`
		echo "$vanilla_lib_name" >> $filelist
		resolved=$vanilla_lib_name
		echo "Adding $resolved to filelist" >> $LOGFILE
		resolved=`ReadAllLink $resolved`
		echo "Adding $resolved to filelist" >> $LOGFILE
		mkdir -p $outdir$optimized_lib_name > /dev/null 2> /dev/null
		rmdir $outdir$optimized_lib_name > /dev/null 2> /dev/null
		ln -sf $vanilla_lib_name $outdir$optimized_lib_name
		echo "Excluding $optimized_lib_name" >> $LOGFILE
		grep -Fvx "$optimized_lib_name" "$filelist" > $filelist.tmp
		echo "Replacing it with $vanilla_lib_name" >> $LOGFILE
		echo "$vanilla_lib_name" >> $filelist.tmp
		mv -f $filelist.tmp $filelist
	done
	$AWK '{ print $1; }' $filelist | sort -u > $filelist.tmp
	mv -f $filelist.tmp $filelist
	echo -e "$DONE"
}


FindAndAddUserKeyboardMappingFile() {
	local r res mapfile mappath included_item included_list keyfile mp locale
	LogIt "Analyzing your keyboard's configuration."
	KEYDIR=/lib/kbd
	[ ! -e "$KEYDIR" ] && KEYDIR=/usr/share/kbd		# Slackware
	[ ! -e "$KEYDIR" ] && KEYDIR=/usr/lib/kbd
	[ ! -e "$KEYDIR" ] && KEYDIR=/usr/share
	if [ ! -e "$KEYDIR" ] ; then
		LogIt "Keyboard mapping directory not found. I shall use default map at boot-time."
		return 0
	fi
	if [ -e "/etc/sysconfig/keyboard" ] ; then
		echo "Red Hat-style config detected." >> $LOGFILE
		keyfile=/etc/sysconfig/keyboard
	elif [ -e "/etc/rc.d/rc.keymap" ] ; then
 		echo "Slackware-style config detected." >> $LOGFILE
 		keyfile=/etc/rc.d/rc.keymap
	elif [ -e "/etc/rc.config" ] ; then
		echo "Debian-style config detected." >> $LOGFILE
		keyfile=/etc/rc.config
	elif [ -e "/etc/console/boottime.kmap.gz" ] ; then
		echo "Debian-style config detected." >> $LOGFILE
		echo -en "Adding the following keyboard mapping tables: "
		mkdir -p $bigdir/tmp
		echo "keymap-lives-here /etc/console/boottime.kmap.gz" > $MINDI_TMP/mondo-restore.cfg
		KBDEPTH=0
		mkdir -p $bigdir/etc/console
		cp /etc/console/boottime.kmap.gz $bigdir/etc/console 2>> $LOGFILE
		echo -e "$DONE"
		return 0
	else
		echo -en "Searching for rc.config ..."
		keyfile=`find /etc -name rc.config | head -n1`
		if [ "$keyfile" = "" ] || [ ! -e "$keyfile" ] ; then
			LogIt "Unknown config detected. Default keyboard map will be used."
			return
		else
			echo "Found $keyfile" >> $LOGFILE
		fi
	fi
	if [ ! -e "$KEYDIR/keymaps" ] ; then
		LogIt "Keyboard mapping directory not found. Default keyboard map will be used."
		return
	fi
	echo "keyfile=$keyfile" >> $LOGFILE
	locale=`grep -F KEYTABLE "$keyfile" | tr -d '"' |cut -d'=' -f2`
	[ ! "$locale" ] && locale=`grep '.map$' "$keyfile" | sed 's/^.* //'`		# Slackware
	echo "locale=$locale" >> $LOGFILE
	#
	# Process the keymaps dir once for all
	# AddKeyboardMappingFile will use it recursively
	#
	find $KEYDIR/keymaps > $MINDI_TMP/keymaps.find
	mp=`grep "i[3-8]86" $MINDI_TMP/keymaps.find | grep -F "/${locale}." | grep -vx " *#.*"`
	[ ! "$mp" ] && mp=`grep "i[3-8]86" $MINDI_TMP/keymaps.find | grep "$locale[^r][^/]" | grep -vx " *#.*"`
	# If we have multiple keymaps then log it !!
	echo "$mp" | grep -q " "
	if [ $? -eq 0 ]; then
		echo "WARNING: Multiple keymaps found: $mp" | tee -a $LOGFILE
		echo "The following one will be used" >> $LOGFILE
	fi
	for i in $mp ; do
		mappath=$i
		[ -e "$i" ] && [ ! -d "$i" ] && break
	done
	if [ ! -e "$mappath" ] || [ -d "$mappath" ] ; then
	   mappath=$(locate */kbd/keymaps/*/$locale)
	fi
	echo "mappath = $mappath" >> $LOGFILE
	if [ ! -e "$mappath" ] || [ -d "$mappath" ] ; then
		LogIt "Keyboard mapping file not found. Default keyboard map will be used."
		return
	fi
	echo -en "Adding the following keyboard mapping tables: "
	mkdir -p $bigdir/tmp
	echo "keymap-lives-here $mappath" > $MINDI_TMP/mondo-restore.cfg
	KBDEPTH=0
	AddKeyboardMappingFile $mappath
	echo -e "$DONE"
	rm -f $MINDI_TMP/keymaps.find
	return 0
}


FindIsolinuxBinary() {
	ISOLINUX=/usr/lib/isolinux.bin
	[ ! -e "$ISOLINUX" ] && ISOLINUX=/usr/lib/syslinux/isolinux.bin
	[ ! -e "$ISOLINUX" ] && ISOLINUX=/usr/share/syslinux/isolinux.bin
	[ ! -e "$ISOLINUX" ] && ISOLINUX=/usr/share/lib/syslinux/isolinux.bin
	[ ! -e "$ISOLINUX" ] && ISOLINUX=`locate isolinux.bin | grep -x "/.*/isolinux.bin"`
	[ ! -e "$ISOLINUX" ] && Die "Please install isolinux first. If your syslinux RPM doesn't include isolinux, you may download an isolinux RPM from Mondo's website - go to http://www.mondorescue.com and click on 'Download'"
	echo "Found isolinux.bin at $ISOLINUX" >> $LOGFILE
}


FindLiloBinary() {
	if which lilo &> /dev/null ; then
		if which lilo.real > /dev/null 2> /dev/null ; then
			LILO_EXE=lilo.real
			LogIt "lilo.real found; will be used instead of lilo (*grumble* *mutter*)"
		else
			LILO_EXE=lilo
		fi
		$LILO_EXE -V | grep -F "21.6" > /dev/null && Die "Please upgrade LILO. Your version has a serious bug. If you're not _using_ LILO, fine, uninstall it. :)"
	else
		LILO_EXE=`which false`
	fi
}


FindSensibleBootBFile() {
	local i out last
	out=""
	last=""
	for i in `find /boot -type f | grep -v chain | grep -v os2 | sort -u` ; do
	if [ "`strings $i 2> /dev/null | head -n1`" = "LILO" ] ; then
		out="$out $i"
	    last="$i"
	fi
	done
	echo "$last"
}


FindSpecificModuleInPath() {
	local modpaths pwd line
	pwd=`pwd`
	if [ "$YOUR_KERNEL_SUCKS" ] ; then
		cd $MINDI_TMP
	else
		cd /
	fi
	if [ ! -e "$1" ] ; then
		LogIt "WARNING - cannot search specific path '$1'"
		return 1
	fi
	modpaths=`find $1 -name $2.*o -type f`
	[ "$?" -ne "0" ] && Die "find $1 -name $2.o -type f --- failed"
	[ "$modpaths" = "" ] && modpaths=`find $1 -name $2.o.gz -type f`
	[ "$modpaths" = "" ] && modpaths=`find $1 -name $2.ko.gz -type f`
	[ "$modpaths" = "" ] && modpaths=`find $1 -name $2 -type f`
	echo "$modpaths"
	cd $pwd
}


GenerateGiantDependencyList() {
	local incoming loc fname list_of_files i tempfile outfile progress filelist res r mapfile mappath included_list included_item old_pwd tempdepfile modres noof_lines lvmversion lvmresolved

	echo -en "Analyzing dependency requirements"
	outfile=$1
	tempfile=$MINDI_TMP/$$.txt
	incoming=`ReadLine`

	> $tempfile
	progress=0
	res=0
	noof_lines=$2
	while [ "$incoming" != "" ] ; do
		if echo "$incoming" | grep -x " *#.*" &> /dev/null ; then
			incoming=`ReadLine`
			continue
		fi
		if [ "$incoming" = "LVMFILES:" ] ; then
			break
		fi
		filelist=`GenerateListForFile "$incoming"`
		r=$?
		[ "$r" -ne "0" ] && LogIt "$incoming not found"
		res=$(($res+$r))
#		echo "'$incoming' generates filelist '$filelist'" >> $LOGFILE
		for fname in $filelist ; do
	    	[ "$fname" != "" ] && echo "$fname" >> $tempfile
		done
		progress=$(($progress+1))
		echo -en "\r\t\t\t\t\t\t\t\t"
		i=$(($progress*100))
		i=$(($i/$noof_lines))
		echo -en "$i"
		echo -en "%"
		modres=$(($progress%4))
		[ "$modres" -eq "0" ] && echo -en "\t/"
		[ "$modres" -eq "1" ] && echo -en "\t-"
		[ "$modres" -eq "2" ] && echo -en "\t\\"
		[ "$modres" -eq "3" ] && echo -en "\t|"
		incoming=`ReadLine`
	done
	if  [ "$incoming" = "LVMFILES:" ] ; then
		incoming=`ReadLine`
		lvmversion=""
		while [ "$incoming" != "" ] ; do
			if echo "$incoming" | grep -x " *#.*" &> /dev/null ; then
				incoming=`ReadLine`
				continue
			fi
			filelist=`GenerateListForFile "$incoming"`
			for tool in $filelist ; do
		    	lvmresolved=`readlink -f $tool`
		    	if [ "$tool" == "$lvmresolved" ]; then
					echo "$tool" >> $tempfile
		    	elif echo "$lvmresolved" | grep "lvmiopversion" &> /dev/null ; then
		    		if [ "$lvmversion" = "" ] ; then
						lvmversion=`$lvmresolved`
						echo "$lvmresolved" >> $tempfile
		    		fi
		    		toolstripped=`echo $tool | $AWK -F / '{print $NF;}'`
		    		if [ "$lvmversion" == "200" ]; then
						# pvdata and lvmcreate_initrd don't exist in LVM2
						case "$toolstripped" in
			    		"pvdata")
							continue
							;;
			    		"lvmcreate_initrd")
							continue
							;;
						esac
		    		fi
		    		toolpath="/sbin/lvm-"$lvmversion"/"$toolstripped
		    		if [ -e "$toolpath" ] ; then
						echo "$toolpath" >> $tempfile
						echo "$tool" >> $tempfile
		    		else
						toolpath="/lib/lvm-"$lvmversion"/"$toolstripped
		    		fi
		    		if [ -e "$toolpath" ] ; then
						echo "$toolpath" >> $tempfile
						echo "$tool" >> $tempfile
		    		else
						echo "Where are your LVM-Tools? Couldn't find $tool"
		    		fi
				else
		    		echo "$tool" >> $tempfile
				fi
			done
			progress=$(($progress+1))
			echo -en "\r\t\t\t\t\t\t\t\t"
			i=$(($progress*100))
			i=$(($i/$noof_lines))
			echo -en "$i"
			echo -en "%"
			modres=$(($progress%4))
			[ "$modres" -eq "0" ] && echo -en "\t/"
			[ "$modres" -eq "1" ] && echo -en "\t-"
			[ "$modres" -eq "2" ] && echo -en "\t\\"
			[ "$modres" -eq "3" ] && echo -en "\t|"
			incoming=`ReadLine`
		done
	fi
	echo -en "$DONE\nMaking complete dependency list"

	tr -s '/' '/' < $tempfile | sort -u > $tempfile.new
	mv -f $tempfile.new $tempfile
	> $outfile.pre
	progress=0
	noof_lines=`cat $tempfile | wc -l`
	for fname in `cat $tempfile` ; do
		echo "$fname" >> $outfile.pre
		LocateDeps $fname >> $outfile.pre
		progress=$(($progress+1))
		echo -en "\r\t\t\t\t\t\t\t\t"
		i=$(($progress*100))
		i=$(($i/$noof_lines))
		echo -en "$i"
		echo -en "%"
 		modres=$(($progress%4))
		[ "$modres" -eq "0" ] && echo -en "\t/"
		[ "$modres" -eq "1" ] && echo -en "\t-"
		[ "$modres" -eq "2" ] && echo -en "\t\\"
		[ "$modres" -eq "3" ] && echo -en "\t|"
	done
	if [ _"$MONDO_SHARE" != _"" ]; then
		mkdir -p $bigdir/tmp
		mkdir -p $bigdir/sbin
		mkdir -p $bigdir/bin
		if [ -e "$MINDI_TMP/post-nuke.tgz" ] ; then
			LogIt "\nIncorporating post-nuke tarball"
			old_pwd=`pwd`
			cd $bigdir
			tar -zxf $MINDI_TMP/post-nuke.tgz || LogIt "Error occurred when untarring post-nuke tarball"
			cd $old_pwd
		fi
 		if cp -f $MINDI_TMP/mondo*restore $bigdir/usr/bin 2>> $LOGFILE ; then
	    	LocateDeps $bigdir/usr/bin/mondo*restore >> $outfile.pre
		else
			LogIt "Cannot find mondo*restore in mondo's tempdir, $MINDI_TMP"
			LogIt "I bet you've got a spare copy of Mondo or Mindi floating around on your system."
	    	LogIt "If Mindi was called by Mondo then send me a bug report.\n It not, type 'ps ax' to see which Mondo-related process is still running;\n then kill it. :-)\n Finally, run Mindi again."
	    	Die "Odd."
		fi
	fi
	tr ' ' '\n' < $outfile.pre | tr -s '/' '/' | grep -Fvx "" | sort -u | grep -Ev "/libX11|/libXext|/libXi|/libgtk|/libgdk" > $outfile
	rm -f $tempfile $outfile.pre
	[ "$res" -eq "0" ] && echo -e "\r\t\t\t\t\t\t\t\t$DONE" || echo "\nFailed."
	return $res
}


GenerateListForFile() {
	local files_found loc fname incoming i res
	incoming="$1"
	files_found=""
	res=0

	for fname in $incoming ; do
		files_found="$files_found `LocateFile $fname`"
	done

	echo "$files_found" | tr ' ' '\n' | sort -u | tr '\n' ' '
}


# Returns all disk devices which are part of a raid array
GetAllRaidMembers() {
	$AWK "/^[[:space:]]*#/ {next} /^[[:space:]]*device/ if(\$2) {print \$2}" < /etc/raidtab
}


GetFileSizeList() {
	local i
	for i in `find $1 -type d -o -print` ; do
		du -sk $i
	done
}


GetHomeDir() {
	local res loc
	loc=`which $1 2>/dev/null`
	res=`file $loc | $AWK '{print $NF;}'`
	dirname $res
}


# Check kernel filesystem capabilites for accessing initrd image
#
# Interface definition:
# param #1: absolute path to kernel image
GetInitrdFilesystemToUse() {

	# interface test: make sure we have one parameter
	if [ $# -ne 1 ]; then
		Die "GetInitrdFilesystemToUse(): Expected 1 parameter, got $#."
	fi

	# interface parameters
	local lvKernelImage=$1

	# local constants (filesystem magic strings)
	local lcMagicCramfs="<3>cramfs: wrong magic"
	local lcMagicExt2fs="<3>EXT2-fs: blocksize too small for device."
	local lcMagicInitfs="<6>checking if image is initramfs..."

	# local variables
	local lvOffset
	local lvScanRes
	local lvUseFilesystem

	# say where we are.
	LogIt "  GetInitrdFilesystemToUse(): called with parameter: $lvKernelImage.\n"

	# verify that file exists
	[ ! -f $lvKernelImage ] && Die "File $lvKernelImage not found. Terminating."

	# get offet of gzip magic "1f8b0800" in file
	lvOffset=`od -vA n -t x1 $lvKernelImage | tr -d '[:space:]' | awk '{ print match($0, "1f8b0800")}'`
	[ $lvOffset -eq 0 ] && Die "gzip magic not found in file $lvKernelImage. Terminating."
	lvOffset=`expr $lvOffset / 2`
	LogIt "  GetInitrdFilesystemToUse(): gzip magic found at lvOffset $lvOffset.\n"

	# scan kernel image for initrd filessystem support
	lvScanRes=`dd ibs=1 skip=$lvOffset if=$lvKernelImage obs=1M 2>/dev/null | gunzip -c | strings | grep -e "$lcMagicCramfs" -e "$lcMagicExt2fs" -e "$lcMagicInitfs"`

	# determine which filesystem to use for initrd image: ext2fs, gzip'ed cpio (initramfs ) or cramfs
	if [ `echo $lvScanRes | grep -c "$lcMagicExt2fs"` -eq 1 ]; then
		lvUseFilesystem="ext2fs"
	elif [ `echo $lvScanRes | grep -c "$lcMagicInitfs"` -eq 1 ]; then
		lvUseFilesystem="initramfs"
	elif [ `echo $lvScanRes | grep -c "$lcMagicCramfs"` -eq 1 ]; then
		lvUseFilesystem="cramfs"
	else
		lvUseFilesystem="UNSUPPORTED"
	fi

	# say what we are using
	LogIt "  GetInitrdFilesystemToUse(): Filesytem to use for initrd is $lvUseFilesystem.\n"

	# return file system to use
	echo "$lvUseFilesystem"

}

# Searches parent raid device of given disk device
# $1: disk device (i.e. /dev/hda1)
GetParentRaidDev() {
	$AWK "/^[[:space:]]*#/ {next} /^[[:space:]]*raiddev/ {dev=\$2} /^[[:space:]]*device/ {if(\$2==\"$1\") {print dev; exit}}" < /etc/raidtab
}


# Searches members of raid device
# $1: raid device (/dev/md...)
GetRaidDevMembers() {
	$AWK "/^[[:space:]]*#/ {next} /^[[:space:]]*raiddev/ {if(dev) exit; if(\$2 == \"$1\") dev=\$2} /^[[:space:]]*device/ {if(dev) {print \$2}}" < /etc/raidtab
}


HackPathsToFailsafe() {
	local incoming newpath kver stub i pwd
	kver=`uname -r`
	incoming=`ReadLine`
	pwd=`pwd`
	cd $MINDI_TMP
	while [ "$incoming" != "" ] ; do
		stub=`basename $incoming`
		newpath=`FindSpecificModuleInPath lib/modules/$FAILSAFE_KVER $stub`
		for i in $newpath ; do
			echo "$i"
		done
		read incoming
	done
	cd $pwd
}


ListAllPartitions() {
	local res currline partition all_partitions ap_orig remaining i j

	grep -vx " *#.*" $MY_FSTAB | grep -vx " *none.*" | $AWK '/^\/dev\/[imhs]d||^LABEL\=\/|^UUID=/ && !/fdd|cdr|zip|floppy/ {print $1}'
	[ -e "/etc/raidtab" ] && $AWK '/^ *device/ {print $2}' /etc/raidtab
	return
}


ListImagesForUser() {
	local path fname
	path=$1
	echo -en "In the directory '$path' you will find the images:-\n"
	for fname in `ls $path | grep -F mindi-` ; do
		printf "%19s " $fname
	done
	echo " "
}


ListKernelModulePaths() {
	local module_list module fname oss r kern
	oss="/root/oss/modules"
	module_list="`lsmod | sed -n '2,$s/ .*//p'`"
###
### Sq-Modification ... Use kernelname for module search path if specified
###
	# kern="`uname -r`"
	if [ "${kernelname}" != "" -a "${kernelname}" != "FAILSAFE" ]
	then
		kern=${kernelname}
	else
		kern="`uname -r`"
	fi
###
### Sq-Mod End
###
	for module in $module_list $EXTRA_MODS ; do
		r=`find /lib/modules/$kern -type f | grep "/${module}\..*o" | tail -n1`
		echo "module $module --> $r" >> $LOGFILE
		[ "$r" ] && echo "$r"
		[ -f "$oss" ] && find $oss | grep -F $module
	done
	find /lib/modules/$kern/modules.* -type f 2> /dev/null
	[ -f "$oss" ] && find $oss.* 2> /dev/null
}


LocateDeps() {
	local incoming fname deps
	incoming="$1"
	for fname in $incoming ; do
		if [ ! -e "$fname" ] ; then
		    echo "WARNING - $fname does not exist; cannot be LDD'd." >> $LOGFILE
			if echo $fname | grep lvm &> /dev/null ; then
				echo "This warning only affects you if you are using LVM." >> $LOGFILE
				if lsmod | grep lvm &> /dev/null ; then
		    		echo "I think you are, so please take heed!" >> $LOGFILE
#				    LogIt "Where is liblvm? You need it."
				else
		    		echo "I don't think you are, so don't worry about it." >> $LOGFILE
				fi
			fi
		elif [ -h "$fname" ] && [ -x "$fname" ] ; then
			echo "$fname is softlink" >> $LOGFILE
		else
		    ldd $fname 2> /dev/null | ProcessLDD $fname
		fi
	done
}


# Give all symlinks recursively of a full path name
ReadAllLink() {
	file="$1"

	if [ ! -h $file ]; then
		echo "$file"
		return 0
	fi

	link=`readlink -f $file`
	d=`dirname $file`
	if [ ! -e "$link" -a ! -e "$d/$link" ]; then
		echo "Problem with dead link on $file -> $link" >> $LOGFILE
	fi
	if [ -h "$d" ]; then
		echo "$link $d"
	else
		echo "$link"
	fi
}


LocateFile() {
	local i path fname_to_find location output resolved tmp stub cache_id loclist
	fname_to_find="$1"
	if echo "$fname_to_find" | grep -x "/.*" ; then
		output="$fname_to_find"
		if [ -h "$output" ] ; then
			output="`ReadAllLink $output` $output"
		fi
		echo "$output"
		return 0
	fi
	output=""
	for path in /etc /usr /usr/bin /usr/sbin /bin /usr/X11R6/bin /sbin /usr/local/bin /usr/local/sbin /usr/lib /usr/lib64 /usr/lib64/* /lib /lib64 /lib64/* /usr/local/lib /usr/local/lib64 /usr/local/lib64/* /usr/X11R6/lib /usr/X11R6/lib64 /usr/X11R6/lib64/* ; do
		[ ! -d "$path" ] && continue
		for location in "$path/$fname_to_find" ; do
			[ ! -e "$location" ] && continue
			output="$location $output"
			if [ -h "$location" ] ; then
		       	output="`ReadAllLink $location` $output"
			fi
		done
	done
	if [ "$output" = "" ] ; then
		return 1
	fi
	echo "$output"
	return 0
}


LogIt() {
	if [ -e /dev/stderr ] ; then
		echo -e "$1" >> /dev/stderr
	elif [ -e /usr/bin/logger ] ; then
		/usr/bin/logger -s $1
	fi
	echo -e "$1" >> $LOGFILE
}


MakeModuleLoadingScript() {
	local module fname params modpath kver outerloop i modpaths kver searchpath list_to_echo j
	tmpmodprobe_flag=$1
	outfile=$2
	> $outfile || Die "Cannot create empty $outfile"
	echo -en "#\041/bin/sh\n\n" >> $outfile
	echo "echo -en \"Loading your modules...\"" >> $outfile
	if [ "$YOUR_KERNEL_SUCKS" ] ; then
		kver=$FAILSAFE_KVER
		cd $MINDI_TMP
		searchpath=lib/modules/$kver
	else
###
### Sq-Modification ... Use kernelname for module search path if specified
###
		#kver=`uname -r`
		if [ "${kernelname}" != "" ]
		then
			kver=${kernelname}
		else
			kver=`uname -r`
		fi
###
### Sq-Modification end
###
		searchpath=/lib/modules/$kver
	fi
	
	echo -en "for outerloop in 1 2 3 4 5 ; do\necho -en \".\"\n" >> $outfile
	list_to_echo="`lsmod | sed -n '2,$s/ .*//p'`"

	# Make temporary modprobe.conf file if we are told so
	if [ $tmpmodprobe_flag == "Y" ] ; then
		infile="$MINDI_TMP/modprobe.conf.mindi"
		find /etc/modprobe.d -maxdepth 1 -name "*" -xtype f -print0 | xargs -0 cat > $infile
	else
		infile="/etc/modules.conf"
	fi
	for module in $list_to_echo $EXTRA_MODS ; do
		params=`sed -n "s/^options \\+$module \\+//p" $infile`
		modpaths=`FindSpecificModuleInPath $searchpath $module`
		for i in $modpaths ; do
			echo "MyInsmod $i $params > /dev/null 2> /dev/null" \
		    	| tr '.' '#' \
		    	| sed s/#o#gz/#o/ \
		    	| sed s/#o#gz/#o/ \
		    	| sed s/#ko#gz/#ko/ \
		    	| sed s/#ko#gz/#ko/ \
		        | tr '#' '.' >> $outfile
			echo -en "$i added to module list.\n" >> $LOGFILE
		done
	done
	echo -en "done\n" >> $outfile
	echo "echo \"Done.\"" >> $outfile
	chmod +x $outfile
	cd /
	# Remove temporary modprobe.conf file if we have created one
	if [ $tmpmodprobe_flag == "Y" ] ; then
		rm -f $infile
	fi
}


MakeMountlist() {
	local scratchdir mountlist all_partitions current_partition \
partition_size partition_format outstring partition_number \
partition_mountpt c_p lwm_info psz lvm_dev unofficial_outstring \
absolute_partition old_partition_fmt current_lvolume

	echo "Your raw fstab file looks like this:" >> $LOGFILE
	echo "------------------------------------" >> $LOGFILE
	cat $MY_FSTAB >> $LOGFILE
	echo "Your mountlist will look like this:" | tee -a $LOGFILE
	echo "-----------------------------------" >> $LOGFILE

# scratchdir, mountlist(OUT)
	scratchdir=$MINDI_TMP
	mountlist=$1

# NB: partition = device
# NB: mountpt = where the device is mounted

	[ -e "$MY_FSTAB" ] || Die "Cannot find your fstab file ($MY_FSTAB)"

	[ "$mountlist" != "" ] && rm -Rf $mountlist
	> $mountlist
	echo -en "\rHang on...\r"
	all_partitions=""
	
	if [ $LVM != "false" ]; then
		echo -en "\rAnalyzing LVM...\r"
		$MINDI_LIB/analyze-my-lvm > $MINDI_TMP/lvm.res
		if [ $? -ne 0 ]; then
			LVM="false"
		fi
		all_partitions=`cat $MINDI_TMP/lvm.res | grep -F ">>>" | cut -d' ' -f2-32`
	fi
	all_partitions="$all_partitions `ListAllPartitions 2> /dev/null`"
#    echo "all partitions = $all_partitions" > /dev/stderr
	for i in $IMAGE_DEVS ; do
		mount | grep -F "$i " > /dev/null 2> /dev/null && Die "Sorry, $i is already mounted! CANNOT DO IMAGEDEV on it if it's mounted."
	done
	[ "$IMAGE_DEVS" != "" ] && all_partitions="`echo "$all_partitions $IMAGE_DEVS" | tr ' ' '\n' | sort -u | tr '\n ' ' '`"
	printf "        %-15s %-15s %-15s %-15s %-15s %-15s\n" DEVICE MOUNTPOINT FORMAT "SIZE (MB)" LABEL UUID | tee -a $LOGFILE
	useless_dev="/dev/floppy /dev/fd0h1440 /dev/fd0H1440 /dev/cdrom /dev/cdrom/cdrom /dev/cdrom/cdrom1 /dev/cdrom/cdrom2 /dev/cdrom0 /dev/cdrom1 /dev/cdrom2 /dev/cdrom3 /dev/cdrw /dev/scd /dev/ram :/ /dev/sr0 /dev/sr1 /dev/cdrom1"
	for c_p in $all_partitions ; do
		[ "`echo "$useless_dev" | grep -F "$c_p"`" != "" ] || [ "`echo "$c_p" | grep ":"`" != "" ] && continue
		[ "`echo "$c_p" | grep -x "/dev/cdroms.*"`" ] && continue
		if [ -h "$c_p" ] && [ "`echo "$c_p" | grep -F "/dev/hd"`" = "" ] && [ "`echo "$c_p" | grep -F "/dev/sd"`" = "" ] && [ "`echo "$c_p" | grep -F "/dev/md"`" = "" ] ; then
			current_partition=`readlink -f $c_p`
			[ "`echo "$current_partition" | grep -F "/dev/mapper"`" != "" ] && current_partition="$c_p"
			[ "`echo "$useless_dev" | grep -F "$current_partition"`" ] && continue
		else
			current_partition="$c_p"
		fi
		[ "$c_p" = "none" ] && continue
		redhat_label=""
		uuid=""
		absolute_partition=`readlink -f $c_p`
		partition_mountpt=`tr -s '\t' ' ' < $MY_FSTAB | /bin/grep -w "$current_partition" | /bin/grep -vx " *#.*" | $AWK '{print $2}' | head -n1`

		# Detects noauto partitions not mounted and exclude them
		partition_option=`tr -s '\t' ' ' < $MY_FSTAB | /bin/grep -w "$current_partition" | /bin/grep -vx " *#.*" | $AWK '{print $4}' | head -n1`
		if [ "`echo "$partition_option" | grep -i noauto`" != "" ] && [ "`mount | grep -w "$partition_mountpt"`" =  "" ] ; then
			continue
		fi

		# This part tries to retrieve the correct device from a LABEL line in /etc/fstab
		# current_partition contains only first column of /etc/fstab
		if [ "`echo "$current_partition" | /bin/grep -i "LABEL="`" != "" ]; then
			str_to_find_fmt_with=$current_partition
			redhat_label=`echo "$current_partition" | cut -d'=' -f2`
			actual_dev=""

			# 1st try, findfs - the RHEL way of finding labels and their partitions
			if [ -x "/sbin/findfs" ]; then
				actual_dev=`/sbin/findfs LABEL=${redhat_label} 2> /dev/null`
			fi
	
			# 2nd try : blkid, the good way for all LABEL except swap
			if [ "x$actual_dev" = "x" -a -x "/sbin/blkid" ]; then
				actual_dev=`/sbin/blkid | /bin/grep "$redhat_label" | grep LABEL= | cut -d':' -f1`
				# For LVM FS it will give a /dev/dm-# which should then be converted
				if [ $LVM = "v2" ] && [ "`echo $actual_dev | grep '/dev/dm'`" ]; then
					major=`/bin/ls -l $actual_dev | $AWK '{print $5}'`
					minor=`/bin/ls -l $actual_dev | $AWK '{print $6}'`
					for dev in `ls /dev/mapper/*`; do
						major1=`/bin/ls -l $dev | $AWK '{print $5}'`
						minor1=`/bin/ls -l $dev | $AWK '{print $6}'`
						if [ $major1 = $major ] && [ $minor1 = $minor ]; then
							actual_dev=`/bin/ls -l $dev | $AWK '{print $10}'`
							break
						fi
					done
				fi
			fi
	
			# 3rd try, which works on a standard partition (ext2/3), but not on swap
			# For LVM gives a /dev/mapper entry 
			if [ "x$actual_dev" = "x" ]; then
				actual_dev=`/bin/mount -l | /bin/grep "\[$redhat_label\]" | cut -d' ' -f1`
			fi
	
			# 4th try, with vol_id 
			# SWAP only
			if [ "x$actual_dev" = "x" -a -x "/sbin/vol_id" ]; then
				list_swaps=`cat /proc/swaps | /bin/grep "/dev/" | $AWK '{ print $1 }' `
				for dev_swap in $list_swaps ; do
					dev_exists=`/sbin/vol_id $dev_swap | /bin/grep "$redhat_label"`
					if [ "x$dev_exists" != "x" ]; then
						actual_dev=$dev_swap
						break;
					fi
				done
			fi

			# 5th try : pre-formated LABEL. Format is : LABEL=SWAP-mydevice or SW-mydevice. e.g. : LABEL=SWAP-hda5
			# LABEL=SW-cciss/c0d0p3 (RDP)
			# or could be a string that isn't a complete device name (eg. LABEL =SWAP-cciss/c0d0p)
			# SWAP only
			if [ "x$actual_dev" = "x" -a  _"`echo $current_partition | /bin/grep -iE 'LABEL=SWAP|LABEL=SW-'`" != _"" ]; then
					for try_dev in `tail +2 /proc/swaps | cut -d' ' -f1`
					do
						# Location of the swap label for kernel 2.6
						try_dev_label=`dd bs=1 count=16 skip=1052 if=$try_dev 2> /dev/null`
						if [ "x$try_dev_label" = "x$redhat_label" ]; then
							actual_dev=$try_dev
						fi
					done
			fi

			# Check if one of all those tries has known success
			if [ "x$actual_dev" != "x" ]; then
				current_partition=$actual_dev
			else
				Die "Your system uses a LABEL partition ($current_partition), but you lack the tool to support it.\nPlease replace labels with their correct devices in $MY_FSTAB or install findfs|blkid|vol_id"
			fi
		# This part tries to retrieve the correct device from a UUID line in /etc/fstab
		# current_partition contains only first column of /etc/fstab
		elif [ "`echo "$current_partition" | /bin/grep -i "UUID="`" != "" ]; then
			str_to_find_fmt_with=$current_partition
			uuid=`echo "$current_partition" | cut -d'=' -f2`
			actual_dev=""

			# 1st try, findfs - the RHEL way of finding labels and their partitions
			if [ -x "/sbin/findfs" ]; then
				actual_dev=`/sbin/findfs UUID=${uuid} 2> /dev/null`
			fi
	
			# 2nd try : blkid, the good way for all LABEL except swap
			if [ "x$actual_dev" = "x" -a -x "/sbin/blkid" ]; then
				actual_dev=`/sbin/blkid | /bin/grep "$uuid" | grep UUID= | cut -d':' -f1`
				# For LVM FS it will give a /dev/dm-# which should then be converted
				if [ $LVM = "v2" ] && [ "`echo $actual_dev | grep '/dev/dm'`" ]; then
					major=`/bin/ls -l $actual_dev | $AWK '{print $5}'`
					minor=`/bin/ls -l $actual_dev | $AWK '{print $6}'`
					for dev in `ls /dev/mapper/*`; do
						major1=`/bin/ls -l $dev | $AWK '{print $5}'`
						minor1=`/bin/ls -l $dev | $AWK '{print $6}'`
						if [ $major1 = $major ] && [ $minor1 = $minor ]; then
							actual_dev=`/bin/ls -l $dev | $AWK '{print $10}'`
							break
						fi
					done
				fi
			fi
	
			# 3th try, with vol_id 
			if [ "x$actual_dev" = "x" -a -x "/sbin/vol_id" ]; then
				list_dev=`mount | /bin/grep -E '^/' | $AWK '{ print $1 }' `
				for dev in $list_dev ; do
					dev_exists=`/sbin/vol_id $dev | /bin/grep "$uuid"`
					if [ "x$dev_exists" != "x" ]; then
						actual_dev=$dev
						break;
					fi
				done
			fi

			# Check if one of all those tries has known success
			if [ "x$actual_dev" != "x" ]; then
				current_partition=$actual_dev
			else
				Die "Your system uses a UUID partition ($current_partition), but you lack the tool to support it.\nPlease replace labels with their correct devices in $MY_FSTAB or install findfs|blkid|vol_id"
			fi
		else
			str_to_find_fmt_with=$current_partition
		fi

		partition_format=`$AWK '$1 == "'"$str_to_find_fmt_with"'" {print $3}' $MY_FSTAB`
		# Some distributions such as Debian do not put /dev/<VG>/<LV> in fstab
		# for LVM partitions but use /dev/mapper/<VG>-<LV> instead. Fortunately,
		# the former is then a link to the latter, so we test whether
		# $current_partition is actually such a link or not and set
		# $current_lvolume accordingly. On Debian you may find more than one answer 
		# so we remove the one corresponding to /dev/.static
		# On RedHat even if the device name is different (/dev/mapper/<VG><LV>), the
		# principle is the same and we need to find the link to it as well.
		# Note that $current_lvolume may well be an
		# ordinary device. It is just to make sure that we feed the right value
		# into any of the LVM tools if possible.

	    current_lvolume="$current_partition"
		if [ $LVM = "v2" ] && [ "`echo $current_partition | grep -E '^/dev/mapper/'`" ]; then
			# .static dir are a Debian specificity
			current_lvolume="`find /dev -lname "$current_partition" | grep -Ev '^/dev/\.static/'`"
			echo $current_lvolume | grep -q ' '
			if [ $? -eq 0 ]; then
				echo "WARNING: Multiple Logical Volumes found. Report to dev team" >> $LOGFILE	
			fi
		fi
		# 
		# End of LVM device style variation code (other than $current_lvolume).

		if [ $LVM != "false" ] && [ "`$LVMCMD lvdisplay $current_lvolume 2> /dev/null`" ]; then
			# Size computed via LVM not directly
			partition_size="lvm"
		else
			partition_size=`SizeOfPartition $current_partition`
			[ "`echo "$current_partition" | grep "[0-9]"`" = "" ] && continue
			[ "`echo "$current_partition" | grep -c "^/"`" -ne "1" ] && continue
			if [ "$partition_format" = "swap" ] || [ "$partition_mountpt" = "swap" ] ; then
				partition_size=`grep -Fv "Priority" /proc/swaps | tr -s '\t' ' ' | grep -F "$current_partition" | $AWK '{print $3}'`
				[ "$partition_mountpt" != "swap" ] && partition_mountpt="swap"
		        [ "$partition_format" != "swap" ] && partition_format="swap"
				if [ "$partition_size" = "" ] ; then
		    		totalsize=0
		    		items=0
		    		for i in `tr -s ' ' '\t' < /proc/swaps | grep -Fv "Filename" | cut -f3` ; do
						totalsize=$(($totalsize+$i))
						items=$(($items+1))
		    		done
            		[ "$items" -gt "0" ] && partition_size=$(($totalsize/$items)) || partition_size=0
		    		[ "$partition_size" -lt "125000" ] && partition_size=125000
		    		echo "I'm guessing $c_p is $(($partition_size/1024))MB" >> $LOGFILE
				fi
			fi
		fi
		[ "$partition_mountpt" = "swap" ] && partition_format="swap"
		[ "$partition_format" = "swap" ] && partition_mountpt="swap"
		if [ "$partition_mountpt" = "" ] ; then
			if [ "`$LVMCMD pvdisplay $current_lvolume 2> /dev/null`" != "" ] ; then
				if  [ "`grep -F device /etc/raidtab 2> /dev/null | grep -w $current_partition`" ] ; then
		    		partition_mountpt="raid"
		    		partition_format="raid"
				else
		    		partition_mountpt="lvm"
		    		partition_format="lvm"
				fi
			fi
		fi
		psz=$partition_size
		echo "Examining $current_partition (mount=$partition_mountpt fmt=$partition_format psz=$psz)" >> $LOGFILE
		[ "$psz" != "lvm" ] && psz=$(($psz/1024))
		if [ "`echo " $IMAGE_DEVS " | grep -F " $current_partition "`" != "" ] ; then
			partition_mountpt="image"
	    	old_partition_fmt=$partition_format
			partition_format="`$FDISK -l 2>> $LOGFILE | tr '*' ' ' | tr '+' ' ' | tr -s ' ' '\t' | grep -w "$absolute_partition" | cut -f5`"
			partition_size=$(($partition_size+1)); # just in case
	    	if [ "$partition_format" = "Linux" ] ; then
	        	echo "Are you imaging a mounted swap partition? Silly..." >> $LOGFILE
	        	echo "Reverting format from $old_partition_fmt to $partition_format" >> $LOGFILE
	        	partition_format=$old_partition_fmt
	    	fi
		fi
		if [ "$EXCLUDE_DEVS" ] && [ "`echo " $EXCLUDE_DEVS " | grep -F " $current_partition "`" ] || [ "`echo " $EXCLUDE_DEVS " | grep " $current_partition "`" ] ; then
	    	echo "Excluding $current_partition from mountlist" >> $LOGFILE
	    	continue
		fi
		if [ ! "$partition_mountpt" ] ; then
	        echo "------- $FDISK -l $qq log ------------" >> $LOGFILE
			for qq in "" `find /dev/ida/c*d* ! -name '*p*'` ; do
				partition_format=`$FDISK -l $qq 2>> $LOGFILE | grep -w "$c_p" | sed 's/12/|/' | tr -s '\t' ' ' | cut -d'|' -f2 | cut -d' ' -f2-9`
				[ "$partition_format" ] && break
			done
	        echo "------- $FDISK log end ------------" >> $LOGFILE
			if [ "$partition_format" = "Compaq diagnostics" ] ; then
				partition_format="compaq"
			elif [ ! "`grep -F device /etc/raidtab 2> /dev/null | grep -w $current_partition`" ] ; then
				LogIt "Unable to find mountpoint of $current_partition - ignoring"
				continue
			fi
		fi
		partition_format="`echo "$partition_format" | cut -d',' -f1`"; # in case user has ext3,ext2 or something dumb like that
		[ "$partition_format" = "auto" ] && partition_format="`mount | grep -w $current_partition | $AWK '{print$5;}'`"; # in case user uses 'auto' (dumb!)
		unofficial_outstring=`printf "\t%-15s %-15s %-15s %7s %-15s %-15s\n" $current_partition $partition_mountpt $partition_format $psz "$redhat_label" $uuid`
		if [ "$current_partition" = "" ] ; then
			echo "Unknown partition (outstring = $unofficial_outstring)" >> $LOGFILE
		elif [ "$partition_mountpt" = "" ] && [ -f "/etc/raidtab" ] ; then
			if [ "`grep -F device /etc/raidtab 2>/dev/null | grep -F $current_partition`" ] ; then
				partition_mountpt=raid
				partition_format=raid
		    	printf "\t%-15s %-15s %-15s %7s %-15s %-15s\n" $current_partition $partition_mountpt $partition_format $psz "$redhat_label" $uuid | tee -a $LOGFILE
				printf "%s %s %s %s %s %s\n" $current_partition $partition_mountpt $partition_format $partition_size "$redhat_label" $uuid >> $mountlist
			else
				echo "Unknown mountpoint (outstring = $unofficial_outstring)" >> $LOGFILE
			fi
		elif [ "$partition_format" = "" ] ; then
			echo "Unknown format (outstring = $unofficial_outstring)" >> $LOGFILE
		elif [ "$partition_size" = "" ] ; then
			echo "Unknown partition size (outstring = $unofficial_outstring)" >> $LOGFILE
		elif [ "$partition_mountpt" = "/proc" ] || [ "$partition_mountpt" = "/dev/pts" ] ; then
			continue
		else
	    	if [ "$partition_format" = "dos" ] || [ "$partition_format" = "msdos" ] ; then
	        	echo "Stupid bastard..." >> $LOGFILE
	        	partition_format="vfat"
	    	fi
			printf "\t%-15s %-15s %-15s %7s %-15s %-15s\n" $current_partition $partition_mountpt $partition_format $psz "$redhat_label" $uuid | tee -a $LOGFILE
			printf "%s %s %s %s %s %s\n" $current_partition $partition_mountpt $partition_format $partition_size "$redhat_label" $uuid >> $mountlist
		fi
	done
}


MakeSureNumberIsInteger() {
	res=`echo "$1" | tr -s '\-[0-9]' ' '`
	if [ "$res" != " " ] && [ "$res" != "" ] ; then
	echo "result = '$res'"
		Die "$1 should be an integer"
	fi
}


MakeSyslinuxMessageFile() {
	mkdir -p $1
	rmdir $1
	echo -en "  " > $1
	if [ "`grep -Fi "debian" /etc/issue.net 2> /dev/null`" ] ; then
		sed s/ZZZZZ/$MINDI_VERSION/ $MINDI_LIB/msg-txt | sed s/YYYYY/"Mondo Rescue"/ | sed s/XXXXX/"a cousin of"/ | sed s%DDDDD%"Debian GNU\/`uname -s` `cut -d ' ' -f 3 /etc/issue.net` `hostname`"% | sed s/KKKKK/"Kernel `uname  -r` on a `uname -m`"/ | sed s/TTTTT/"`LC_TIME=C date`"/ >> $1.tmp
	else
		sed s/ZZZZZ/$MINDI_VERSION/ $MINDI_LIB/msg-txt | sed s/YYYYY/"Mondo Rescue"/ | sed s/XXXXX/"a cousin of"/ | sed s/DDDDD/"`grep -i "linux" /etc/issue.net | head -n1 | tr -s ' ' ' '`"/ | sed s/KKKKK/"`grep -i "kernel" /etc/issue.net | head -n1 | tr -s ' ' ' '`"/ | sed s/TTTTT/"`LC_TIME=C date`"/ | sed s/' '\\r' 'on' 'an' '\/' '`uname -r`' 'on' 'an' '`uname -m`/ >> $1.tmp
	fi
	sed s/%r/"`uname -r`"/ $1.tmp | sed s/%t/"`hostname`"/ > $1
	rm -f $1.tmp
	if [ "$CDRECOVERY" != "yes" ] ; then
		if [ "$NFS_DEV" != "" ] ; then
		    echo -en "Press <enter> to continue.\n" >> $1
		elif [ ! "$MINDI_TMP" ] ; then
		    echo -en "FYI, this is _not_ a Mondo Rescue CD.\n" >> $1
		    if [ -e "$MINDI_LIB/memtest.img" ] ; then
		        echo -en "Type 'memtest' <Enter> to test your PC's memory intensively.\nJust press <Enter> to go to the main test menu.\n" >> $1
		    fi
		else
		    echo -en "$BOOT_MEDIA_MESSAGE" >> $1
		fi
	else
		echo -en " \
To restore your disk to factory defaults, type 'RESTORE' <enter>.\n\
CAUTION: THIS WILL ERASE YOUR WHOLE DISK !!!\n" >> $1
	fi
}


MoveHyperlinkSensibly() {
	local filename minidir_root resides_on_diskno noof_disks old_diskno d old_pwd
	filename=$1
	minidir_root=$2
	resides_on_diskno=$3
	noof_disks=$4

	[ -h "$minidir_root/$resides_on_diskno/$filename" ] || Die "$filename isn't a softlink (or doesn't exist): how can I move it sensibly?"

	old_diskno=$resides_on_diskno
	d=1
	while [ "$d" -le "$noof_disks" ] ; do
		if [ "$d" -ne "$old_diskno" ] ; then
		    old_pwd=`pwd`
		    cd $minidir_root/$old_diskno
		    cp --parents -Rdf $filename $minidir_root/$d/ 2>> $LOGFILE || Die "Can't move $filename (sensibly) from $old_diskno to $d"
		    rm -f $filename
		    cd $old_pwd
		fi
# when the softlink is resolvable, our work here is done
		[ -e "$minidir_root/$d/$filename" ] && return 0
		old_diskno=$d
		d=$(($d+1))
	done
	return 1
}


OfferToCopyImagesToDisks() {
	local imagesdir i imagename dev count boot_dev data_dev
	imagesdir=$1
	boot_dev=$2
	data_dev=$3

	echo -en "Would you like to create boot+data floppy disks now (y/[n]) ?"
	read i
	[ "$i" != "y" ] && [ "$i" != "Y" ] && return
	mount | grep -F /dev/fd > /dev/null && Die "Please unmount your floppies first."
	echo "WARNING! THIS WILL ERASE YOUR FLOPPY DISKS."
	[ ! -e "$boot_dev" ] && Die "Cannot find $boot_dev - is your Linux distro broken?"
	[ ! -e "$data_dev" ] && Die "Cannot find $data_dev - is your Linux distro broken?"
	find $imagesdir -type f > $MINDI_TMP/imagesdir.files
	i=`grep -F "/mindi-root.1" $MINDI_TMP/imagesdir.files 2> /dev/null`
	j=`grep -F "/mindi-boot" $MINDI_TMP/imagesdir.files | grep -Ev '2880|5760'`
	if [ "$i" ] ; then
		CopyImageToDisk $j $data_dev "boot disk"
		CopyImageToDisk $i $data_dev "root disk"
	else
		CopyImageToDisk $j $boot_dev "boot/root disk"
	fi
	count=1
	for i in `grep -F mindi-data $MINDI_TMP/imagesdir.files` ; do
		CopyImageToDisk $i $data_dev "data disk #$count"
		count=$(($count+1))
	done
	rm -f $MINDI_TMP/imagesdir.files
}


OfferToMakeBootableISO() {
	local i old_pwd
	if [ "$PROMPT_MAKE_CD_IMAGE" = "yes" ] && [ _"$MONDO_SHARE" = _"" ]; then
		echo -en "Shall I make a bootable CD image? (y/[n]) "
		read i
		[ "$i" != "y" ] && [ "$i" != "Y" ] && return 0
	fi
	if [ _"$MINDI_TMP" = _"" ]; then
		Die "MINDI_TMP undefined"
	fi
	rm -Rf $MINDI_TMP/iso
	mkdir -p $MINDI_TMP/iso/{images,archives,isolinux}
	cp -f $1/*.img $1/*.gz $MINDI_TMP/iso/images 2>> $LOGFILE || LogIt "OfferToMakeBootableISO: Cannot copy $i to $MINDI_TMP/iso/images"
	old_pwd=`pwd`
	cd $MINDI_TMP/iso
	echo "mindi_lib = $MINDI_LIB" >> $LOGFILE
	for i in memdisk memtest.bin memtest.img ; do
		j=$MINDI_LIB/$i
		k=$MINDI_TMP/iso/isolinux
		if [ -e "$j" ] ; then
			LogIt "Copying $j to $k"
			cp -f $j $k 2> /dev/null || Die "Failed to copy $j to $k"
			cp -f $j $MINDI_TMP 2> /dev/null || Die "Failed to copy $j to $MINDI_TMP"
			if [ _"$MONDO_SHARE" != _"" ]; then 
				cp -f $j $MONDO_ROOT 2>> $LOGFILE || Die "Failed to copy $j to $MONDO_ROOT"
			fi
		fi
	done
	MakeSyslinuxMessageFile $MINDI_TMP/iso/isolinux/message.txt
	cp $kernelpath $MINDI_TMP/iso/isolinux/vmlinuz 2> /dev/null || Die "Cannot copy vmlinuz ($kernelpath) to mindi tmp ($MINDI_TMP/iso/isolinux/vmlinuz). Did you run out of disk space?"
	cp $MINDI_TMP/mindi.rdz $MINDI_TMP/iso/isolinux/initrd.img 2>> $LOGFILE
	if [ _"$MONDO_SHARE" != _"" ]; then 
		cp $kernelpath $MONDO_ROOT/vmlinuz 2> /dev/null || Die "Cannot copy vmlinuz ($kernelpath) to mondo root ($MONDO_ROOT/vmlinuz). Did you run out of disk space?"
		cp $MINDI_TMP/mindi.rdz $MONDO_ROOT/initrd.img 2> /dev/null || Die "Cannot copy mindi.rdz ($MINDI_TMP/mindi.rdz) to mondo root ($MONDO_ROOT/vmlinuz). Did you run out of disk space?"

	fi
	[ -e "$iso_cfg_file" ] || Die "FIXME - unable to find $iso_cfg_file - this should never occur"
	cd $MINDI_TMP/iso/isolinux
	cat $iso_cfg_file | HackSyslinuxFile $ramdisk_size $MINDI_TMP/iso > isolinux.cfg || Die "Cannot copy isolinux.cfg to $MINDI_TMP/iso/isolinux - did you run out of disk space?"
	if [ "$NFS_DEV" != "" ] ; then
		perl -pi -e 's/interactive/iso/' isolinux.cfg
	fi
	if [ "$ARCH" != "ia64" ] ; then
		cp $ISOLINUX isolinux.bin 2> /dev/null || Die "Cannot copy isolinux.bin ($ISOLINUX) to $MINDI_TMP/iso/isolinux - did you run out of disk space?"
		cp $ISOLINUX ../ 2>> $LOGFILE
	fi
	cd $MINDI_TMP/iso
	if [ "$ARCH" != "ia64" ] ; then
		if [ _"$MONDO_SHARE" != _"" ]; then 
			cp -f $MINDI_TMP/iso/isolinux/{isolinux.cfg,initrd.img,vmlinuz,isolinux.bin,message.txt} $MONDO_ROOT 2> /dev/null || Die "Cannot copy core files to ramdisk for boot disk (under $MONDO_ROOT). Did you run out of disk space?"
			cp -f $MONDO_SHARE/autorun . 2>> $LOGFILE
		fi
		mkisofs -U -J -r -o $MINDI_CACHE/mindi.iso -b isolinux/isolinux.bin -c isolinux/boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table . > /dev/null 2> $MINDI_TMP/mkisofs.log
	else
		mkisofs -J -r -o $MINDI_CACHE/mindi.iso -b images/mindi-bootroot.$IA64_BOOT_SIZE.img -c isolinux/boot.cat -no-emul-boot . > /dev/null 2> $MINDI_TMP/mkisofs.log
	fi
	if [ "$?" -ne "0" ] ; then
		echo "----------- mkisofs's errors --------------" >> $LOGFILE
		cat $MINDI_TMP/mkisofs.log >> $LOGFILE
		echo "mkisofs returned the following errors:-"
		cat $MINDI_TMP/mkisofs.log
		LogIt "Failed to create ISO image."
	else
		echo "Created bootable ISO image at $MINDI_CACHE/mindi.iso" >> $LOGFILE
	fi
	rm -f $MINDI_TMP/mkisofs.log
	cd $old_pwd
}


OfferToMakeBootableUSB() {
	local i old_pwd
	if [ "$PROMPT_MAKE_USB_IMAGE" = "yes" ] && [ _"$MONDO_SHARE" = _"" ]; then
		echo "Shall I make a bootable USB image ?"
		echo -en "WARNING: This will erase all content on $USBDEVICE (y/[n]) "
		read i
		[ "$i" != "y" ] && [ "$i" != "Y" ] && return 0
	fi
	if [ _"$MINDI_TMP" = _"" ]; then
		Die "MINDI_TMP undefined"
	fi
	rm -Rf $MINDI_TMP/usb
	mkdir -p $MINDI_TMP/usb
	USBPART="${USBDEVICE}1"

	echo -en "Transforming $USBDEVICE in a Bootable device " 
	echo -en "."
	echo "Transforming $USBDEVICE in a Bootable device"  >> $LOGFILE
	echo "Checking $USBDEVICE" >> $LOGFILE
	$FDISK -l $USBDEVICE 2>&1 >> $LOGFILE
	if [ $? -ne 0 ]; then
		echo "Unable to access $USBDEVICE" | tee -a $LOGFILE
		echo "Make sure your USB device is pluged in" | tee -a $LOGFILE
		MindiExit -1
	fi
	echo -en "."
	echo "Erasing $USBDEVICE" >> $LOGFILE
	$FDISK $USBDEVICE 2>&1 >> $LOGFILE << EOF
d
d
d
d
n
p
1


t
b
a
1
w
EOF
	if [ $? -ne 0 ]; then
		echo "Unable to create a vfat Filesystem on $USBDEVICE" | tee -a $LOGFILE
		echo "Make sure your USB device is pluged in" | tee -a $LOGFILE
		$FDISK -l $USBDEVICE 2>&1 | tee -a $LOGFILE
		MindiExit -1
	fi
	echo -en "."
	echo "Creating a vfat filesystem on $USBPART" >> $LOGFILE
	mkfs -t vfat $USBPART 2>&1 >> $LOGFILE
	if [ $? -ne 0 ]; then
		echo "Unable to create a vfat filesystem on $USBPART" | tee -a $LOGFILE
		echo "Make sure your USB device is pluged in and partitioned ($USBPART must exist on it)" | tee -a $LOGFILE
		$FDISK -l $USBDEVICE 2>&1 | tee -a $LOGFILE
		MindiExit -1
	fi
	echo -en "."
	echo "Mounting $USBPART on $MINDI_TMP/usb" >> $LOGFILE
	mount $USBPART $MINDI_TMP/usb 2>> $LOGFILE
	if [ $? -ne 0 ]; then
		echo "Unable to mount $USBPART on $MINDI_TMP/usb" | tee -a $LOGFILE
		echo "Make sure your USB device is pluged in, partitioned and formated ($USBPART must exist on it)" | tee -a $LOGFILE
		$FDISK -l $USBDEVICE 2>&1 | tee -a $LOGFILE
		MindiExit -1
	fi
	echo -en "."
	mkdir -p $MINDI_TMP/usb/{images,archives}
	cp -f $1/*.img $1/*.gz $MINDI_TMP/usb/images 2>> $LOGFILE || LogIt "OfferToMakeBootableUSB: Cannot copy $i to $MINDI_TMP/iso/images"
	echo -en "."
	old_pwd=`pwd`
	cd $MINDI_TMP/usb
	echo "mindi_lib = $MINDI_LIB" >> $LOGFILE
	for i in memdisk memtest.bin memtest.img ; do
		j=$MINDI_LIB/$i
		k=$MINDI_TMP/usb
		if [ -e "$j" ] ; then
			LogIt "Copying $j to $k"
			cp -f $j $k 2> /dev/null || Die "Failed to copy $j to $k"
			cp -f $j $MINDI_TMP 2> /dev/null || Die "Failed to copy $j to $MINDI_TMP"
			if [ _"$MONDO_SHARE" != _"" ]; then
				cp -f $j $MONDO_ROOT 2>> $LOGFILE || Die "Failed to copy $j to $MONDO_ROOT"
			fi
		fi
	done
	echo -en "."
	MakeSyslinuxMessageFile $MINDI_TMP/usb/message.txt
	echo -en "."
	cp $kernelpath $MINDI_TMP/usb/vmlinuz 2> /dev/null || Die "Cannot copy vmlinuz ($kernelpath) to mindi tmp ($MINDI_TMP/usb/syslinux/vmlinuz). Did you run out of disk space?"
	echo -en "."
	cp $MINDI_TMP/mindi.rdz $MINDI_TMP/usb/initrd.img 2>> $LOGFILE
	echo -en "."
	if [ _"$MONDO_SHARE" != _"" ]; then
		cp $kernelpath $MONDO_ROOT/vmlinuz 2> /dev/null || Die "Cannot copy vmlinuz ($kernelpath) to mondo root ($MONDO_ROOT/vmlinuz). Did you run out of disk space?"
		cp $MINDI_TMP/mindi.rdz $MONDO_ROOT/initrd.img 2> /dev/null || Die "Cannot copy mindi.rdz ($MINDI_TMP) to mondo root ($MONDO_ROOT/initrd.img). Did you run out of disk space?"

	fi
	echo -en "."
	[ -e "$iso_cfg_file" ] || Die "FIXME - unable to find $iso_cfg_file - this should never occur"
	cat $sys_cfg_file | HackSyslinuxFile $ramdisk_size $MINDI_TMP/usb > syslinux.cfg || Die "Cannot copy syslinux.cfg from mindi_home to $MINDI_TMP/usb - did you run out of disk space?"
	echo -en "."
	if [ "$NFS_DEV" != "" ] ; then
		perl -pi -e 's/interactive/iso/' syslinux.cfg
	fi
	cd $old_pwd
	echo -en "."
	if [ "$ARCH" != "ia64" ] ; then
		if [ _"$MONDO_SHARE" != _"" ]; then
			cp -f $MINDI_TMP/usb/{syslinux.cfg,initrd.img,vmlinuz,message.txt} $MONDO_ROOT 2>> $LOGFILE || Die "Cannot copy core files to ramdisk for boot disk (under $MONDO_ROOT). Did you run out of disk space?"
			cp -f $MONDO_SHARE/autorun $MONDO_ROOT 2>> $LOGFILE
		fi
		umount $MINDI_TMP/usb
		syslinux $USBPART 2>> $MINDI_TMP/syslinux.log
	else
		echo "No USB boot support for ia64" | tee -a $LOGFILE
		umount $MINDI_TMP/usb
		MindiExit -1
	fi
	echo -en "."
	if [ "$?" -ne "0" ] ; then
		echo "----------- syslinux's errors --------------" |tee -a $LOGFILE
		cat $MINDI_TMP/syslinux.log |tee -a $LOGFILE
		LogIt "Failed to create USB image."
	else
		echo -e "$DONE"
		echo "Created bootable USB image on $USBDEVICE" >> $LOGFILE
	fi
	rm -f $MINDI_TMP/syslinux.log
	#
	# If mondoarchive, then tranfer $MINDI_CACHE content to the USB device 
	# and mount that device under that mountpoint instead 
	# Has to be done at the end here.
	#
	if [ _"$MONDO_SHARE" != _"" ]; then
		mount $USBPART $MINDI_TMP/usb 2>> $LOGFILE
		mv $MINDI_CACHE/* $MINDI_TMP/usb
		umount $MINDI_TMP/usb
		mount $USBPART $MINDI_CACHE
	fi
}


PluralOrNot() {
	[ "$1" -gt "1" ] && echo -en "s"
}


MakeMessageFile() {
	local disksize
	disksize=$1
	if [ "`grep -Fi "debian" /etc/issue.net 2> /dev/null`" ] ; then
		sed s/ZZZZZ/$MINDI_VERSION/ $MINDI_LIB/msg-txt | sed s/YYYYY/"Mondo Rescue"/ | sed s/XXXXX/"a cousin of"/ | sed s%DDDDD%"Debian GNU\/`uname -s` `cut -d ' ' -f 3 /etc/issue.net` `hostname`"% | sed s/KKKKK/"Kernel `uname  -r` on a `uname -m`"/ | sed s/TTTTT/"`LC_TIME=C date`"/
	else
		sed s/ZZZZZ/$MINDI_VERSION/ $MINDI_LIB/msg-txt | sed s/YYYYY/"Mondo Rescue"/ | sed s/XXXXX/"a cousin of"/ | sed s/DDDDD/"`grep -i "linux" /etc/issue.net | head -n1 | tr -s ' ' ' '`"/ | sed s/KKKKK/"`grep -i "kernel" /etc/issue.net | head -n1 | tr -s ' ' ' '`"/ | sed s/TTTTT/"`LC_TIME=C date`"/ | sed s/' 'r' 'on' 'an' 'm/' '`uname -r`' 'on' 'an' '`uname -m`/
	fi
	if [ "$disksize" -gt "2880" ] ; then
		if [ _"$MONDO_SHARE" != _"" ]; then
			if [ "$CDRECOVERY" != "yes" ] ; then
				if [ "$NFS_DEV" != "" ] ; then
					echo -en "Press <enter> to continue.\n"
				elif [ ! "$MINDI_TMP" ] ; then
					echo -en "FYI, this is _not_ a Mondo Rescue CD.\n"
				else
					echo -en "$BOOT_MEDIA_MESSAGE"
				fi
			fi
		fi
	fi
	if [ "$CDRECOVERY" = "yes" ] ; then
		echo -en "\
To restore your disk to factory defaults, type 'RESTORE' <enter>.\n\
CAUTION: THIS WILL ERASE YOUR WHOLE DISK !!!\n"
	fi
	echo -en "\n\n\n"
}


write_full_floppy_of_kernel() {
	local mtpt image old_pwd res disksize

	res=0
	old_pwd=`pwd`
	KERN_DISK_MADE=1
	disksize=$3
	rand1=$RANDOM
	rand2=$RANDOM
	image=$MINDI_TMP/$rand1.$rand2.img
	mtpt=$MINDI_TMP/$rand1.$rand2.mtpt
	dd if=/dev/zero of=$image bs=1k count=$disksize &> /dev/null
	echo "Creating ext2 filesystem on $image" >> $LOGFILE
	mke2fs -N 26 -F $image &> /dev/null
	mkdir -p $mtpt
	mount -o loop $image $mtpt
	cd $mtpt
	mkdir -p {dev,tmp,boot}
	cp -f $1 vmlinuz 2>> $LOGFILE
	if [ "$?" -ne "0" ] ; then
		LogIt "Failed to copy $1 to ramdisk"
		cd $old_pwd
		umount $mtpt
		rmdir $mtpt
		rm $image
		return 1
	fi

	rdev vmlinuz 2,0
	rdev -R vmlinuz 0
	rdev -r vmlinuz 49152

	tar -zxf $MINDI_LIB/dev.tgz || LogIt "Cannot untar dev.tgz"
	losetup /dev/loop0 > /dev/null 2> /dev/null
	[ "$?" -eq "0" ] || losetup /dev/loop0 -d || Die "Please free up /dev/loop0 by typing 'losetup /dev/loop0 -d'.\nReboot if necessary."
	CopyBootBFile $mtpt/boot.b

	MakeLiloConfFile $disksize >> bdlilo.conf

	chmod 644 bdlilo.conf
	MakeMessageFile $disksize > message
	lilo -v -C bdlilo.conf -r $mtpt
	res=$?

	cd $old_pwd
	umount $mtpt
	mv -f $image $2
	rmdir $mtpt

	return $res
}


MakeLiloConfFile() {
	local disksize options i ooo
	disksize=$1
	options=""

	if [ "$ARCH" != "ia64" ] ; then
		echo -en "boot=/dev/loop0\ndisk=/dev/loop0\n"
	fi
	if [ "$disksize" -eq "2880" ] ; then
		echo -en "bios=0x00\nsectors=36\nheads=2\ncylinders=80\n"
	elif [ "$disksize" -gt "2880" ] ; then
	    /bin/true
	else
		echo -en "bios=0x00\nsectors=18\nheads=2\ncylinders=80\n"
	fi
	if [ "$ARCH" != "ia64" ] ; then
	    echo -en "install=/boot.b\nmap=/boot.map\n"
	fi
	if [ "$CDRECOVERY" = "yes" ] ; then
		echo -en "default=RESTORE\n"
	elif [ "$disksize" -gt "2880" ] && [ _"$MONDO_SHARE" != _"" ]; then
		if [ "$NFS_DEV" != "" ] ; then
			echo -en "default=iso\n"
		else
			echo -en "default=interactive\n"
		fi
	else
		echo -en "default=expert\n"
	fi

	echo -en "prompt\n"
	if [ "$ARCH" != "ia64" ] ; then
		echo -en "vga=normal\nbackup=/dev/null\nmessage=/message\n"
	fi
	if [ "$CDRECOVERY" != "yes" ] ; then
		echo -en "timeout=300\n"
	fi
	echo -en "\n"
	if [ "$CDRECOVERY" = "yes" ] ; then
		options="RESTORE expert"
	elif [ "$disksize" -gt "2880" ] ; then
		if [ _"$MONDO_SHARE" != _"" ]; then
		    if [ "$NFS_DEV" != "" ] ; then
		        options="iso"
		    else
		        options="interactive expert compare iso nuke isonuke"
# hda hdb hdc hdd"
		    fi
		else
		    options="expert"
		fi
	else
		options="expert"
	fi
	for i in $options ; do
		ooo=$i
		[ "$ooo" = "RESTORE" ] && ooo="nuke"
		if [ "$ARCH" = "ia64" ] ; then
			rootpart="root=/dev/ram0\n\t"
		else
			rootpart=""
		fi
		outstr="image=/vmlinuz\n\tlabel=$i\n\tinitrd=/mindi.rdz\n\t${rootpart}append=\" rw ramdisk=$ramdisksize ramdisk_size=$ramdisksize maxcpus=1 $ooo_mode $ADDITIONAL_BOOT_PARAMS"
	
		outstr=$outstr" $ooo_mode"
		outstr=$outstr"\"\n"
		if [ "$disksize" = "1440" ] ; then
			echo -en "$outstr" | sed s/initrd=.*// | grep -v root=
		else
			echo -en "$outstr"
		fi
	done
}


PrepareBootDiskImage_LILO() {
	local disksize imagesdir dev imagefile mountpoint fname i kernelpath ramdisksize cfg_file testpath options retval outstr old_pwd ooo max_kernel_size liloconf
	imagesdir=$1
	disksize=$2
	kernelpath=$3
	ramdisksize=$4

	retval=0
	[ ! -e "$kernelpath" ] && Die "PBDI - cannot find $kernelpath kernel"
	echo -en "Making "$disksize"KB boot disk..."
	TurnTgzIntoRdz $MINDI_LIB/rootfs $MINDI_TMP/mindi.rdz $ramdisksize $disksize `du -sk $kernelpath | cut -f1` || Die "Could not turn rootfs into mindi.rdz; are you SURE your kernel supports loopfs?"
	if [ "$ARCH" != "ia64" ] ; then
		[ "$disksize" != "2880" ] && [ "$disksize" != "5760" ] && Die "PDBI - disksize is $disksize - bad size"
	fi
	echo -en "..."
	imagefile=$imagesdir/mindi-bootroot.$disksize.img
	mountpoint=$MINDI_TMP/mountpoint.$$
	mkdir -p $mountpoint
	dd if=/dev/zero of=$imagefile bs=1k count=$disksize &> /dev/null || Die "Cannot dd blank file"
	if [ "$ARCH" = "ia64" ] ; then
		mkdosfs $imagefile >> $LOGFILE 2>> $LOGFILE
		t=vfat
	else
		echo "Creating ext2 filesystem on $imagefile" >> $LOGFILE
		mke2fs -N 26 -m 0 -F $imagefile >> $LOGFILE 2>> $LOGFILE
		t=ext2
	fi
	mount -t $t -o loop $imagefile $mountpoint || LogIt "Cannot mount (PBDI)"
	# copy Mindi's skeleton fs & lilo/syslinux/whatever stuff into it
	mkdir -p $mountpoint/etc
	if [ "$ARCH" != "ia64" ] ; then
		liloconf=$mountpoint/etc/lilo.conf
	else
		liloconf=$mountpoint/elilo.conf
	fi
	old_pwd=`pwd`
	cd $mountpoint
	if [ "$ARCH" != "ia64" ] ; then
		tar -zxf $MINDI_LIB/dev.tgz || LogIt "Cannot untar dev.tgz"
	fi
	cd $old_pwd
	losetup /dev/loop0 > /dev/null 2> /dev/null
	[ "$?" -eq "0" ] || losetup /dev/loop0 -d || Die "Please free up /dev/loop0 by typing   'losetup /dev/loop0 -d'.\nReboot if necessary."
	CopyBootBFile $mountpoint/boot.b

	MakeLiloConfFile $disksize > $liloconf

	# Copy it so that CD-ROM menu entry is satisfied
	if [ "$ARCH" = "ia64" ] ; then
		mountefi=0
		df -T | grep /boot/efi | grep -q vfat
		if [ $? -ne 0 ]; then
			mount /boot/efi
			if [ $? -ne 0 ]; then
				echo "You have to mount your EFI partition when using mindi"
				MindiExit -1
			fi
			mountefi=1
		fi
		cp /boot/efi/elilo.efi $mountpoint
		cp $liloconf $mountpoint/elilo.efi $mountpoint/efi/boot
		if [ $mountefi -eq 1 ]; then
			umount /boot/efi 2>&1 > /dev/null
		fi
	fi

	echo "Copying $MINDI_TMP/mindi.rdz to $mountpoint..." >> $LOGFILE
	cp -f $MINDI_TMP/mindi.rdz $mountpoint 2>> $LOGFILE
	if [ "$?" -ne "0" ] ; then
		LogIt "Failed to copy $MINDI_TMP/mindi.rdz to $mountpoint"
		cat $MINDI_TMP/mtpt.$$ >> $LOGFILE
		LogIt "Please unload some of your modules and try again."
		rm -f $MINDI_TMP/mtpt.$$
		LogIt "Cannot incorporate mindi.rdz in bootdisk (kernel / modules too big?)"
		retval=$(($retval+1))
	fi
	MakeMessageFile $disksize > $mountpoint/message

	mkdir -p $mountpoint/tmp
	cp -f $MINDI_TMP/mondo-restore.cfg $mountpoint/tmp &> /dev/null
	if [ -e "$MINDI_LIB/memtest.img" ] ; then
		echo -en "image=/memtest.bin\nlabel=memtest\nn" >> $liloconf
		echo -en "image=/memdisk\nlabel=memtest\nappend=\"initrd=memtest.img\"\n" >> $liloconf
#        echo "Yep, this is a multi-function CD" > $mountpoint/MULTIFUNC
	fi

	# copy the kernel across
	[ "$mountpoint" != "" ] && rm -Rf $mountpoint/lost+found
	dd if=/dev/zero of=$mountpoint/zero bs=1k count=16 &> /dev/null
	free_space=`df -k -P $mountpoint | tail -n1 | tr -s ' ' '\t' | cut -f4`
	cp -f $kernelpath $mountpoint/vmlinuz > /dev/null 2> /dev/null
	if [ "$?" -ne "0" ] || [ "$FORCE_DUAL_FLOPPIES" = "yes" ] ; then
		echo "Files at mountpoint ($mountpoint) :-" >> $LOGFILE
		du -sk $mountpoint/* >> $LOGFILE
		echo "--- end of list of files ---" >> $LOGFILE
		echo -en "Kernel size = `du -sk $kernelpath | cut -f1` K\nRamdisk free = $free_space K\n\
Sorry, your kernel is too big for a boot/root floppy.\nI'll try the new boot/root two-disk thingy.\n" >> $LOGFILE
		rm -f $mountpoint/vmlinuz
		cd $old_pwd
		umount $mountpoint || Die "Cannot unmount mountpoint ($mountpoint)"
		rmdir $mountpoint || LogIt "Cannot rmdir (PBDI)"
	#	losetup /dev/loop0 -d
		res=0
		write_full_floppy_of_kernel $kernelpath $imagesdir/mindi-boot.1440.img 1440
		res=$(($res+$?))
		cp -f $MINDI_TMP/mindi.rdz $imagesdir/mindi-root.1440.img 2>> $LOGFILE
		res=$(($res+$?))
		rm -f $imagefile
		if [ "$res" -ne "0" ]; then
			LogIt "WARNING - failed to create 1.44MB boot/root floppies"
			rm -f $imagesdir/mindi-*.1440.img
		fi
		return $res
	fi
	free_space=`df -k -P $mountpoint | tail -n1 | tr -s ' ' '\t' | cut -f4`
	max_kernel_size=$(($free_space+`du -sk $kernelpath | cut -f1`))
	echo "Free space left on floppy = $free_space KB" >> $LOGFILE
	echo "Max kernel size on $disksize KB floppy (est'd) = $max_kernel_size K" >> $LOGFILE
# make it bootable
	rm -f $mountpoint/zero
	[ -e "$MINDI_LIB/memdisk" ] && cp -f $MINDI_LIB/memdisk $mountpoint 2>> $LOGFILE
	if [ "$disksize" -gt "2880" ] && [ ! "$KERN_DISK_MADE" ] ; then
		if [ "$ARCH" != "ia64" ] ; then
		$LILO_EXE -r $mountpoint >> $LOGFILE 2>> $LOGFILE
		else
		    /bin/true
		fi
	elif [ ! "$KERN_DISK_MADE" ] ; then
# 12/28/2001 - if 1.72MB floppy then don't use LILO's optimizations at all
		$LILO_EXE -r $mountpoint >> $LOGFILE 2>> $LOGFILE
	else
		echo "Not running LILO. It's not that kind of disk." >> $LOGFILE
	fi

	# BERLIOS  does not test necessarily what it expects
	if [ $? -ne "0" ] ; then
		if [ "`grep -F "/tmp/dev.0" $LOGFILE`" ] ; then
			LogIt "The '/tmp/dev.0' error is NOT Mindi's fault. It is LILO's."
			LogIt "Please reboot your PC as a workaround."
			Die "LILO sneezed and Mindi caught a cold. Please read the README / FAQ."
		fi
		echo "$LILO_EXE -r $mountpoint ...failed."
		echo -en "Press ENTER to continue."; read line
		LogIt "Cannot run lilo on $mountpoint\nPlease upgrade/downgrade your version of LILO. It has a bug."
		retval=$(($retval+1))
	fi
	cp -f $liloconf $MINDI_TMP/lilo.conf 2>> $LOGFILE
	if [ "$ARCH" = "ia64" ] ; then
		cp `dirname $kernelpath`/*.efi $mountpoint 2>> $LOGFILE
	fi
	umount $mountpoint || Die "Cannot unmount mountpoint ($mountpoint)"
	echo -en "..."
	rmdir $mountpoint || LogIt "Cannot rmdir (PBDI)"
	if [ "$retval" -eq "0" ] ; then
		echo -en "...$DONE\r"
		if [ "$KERN_DISK_MADE" ] ; then
			LogIt "... $disksize KB boot disks were created OK\r"
		fi
	else
		echo -en "...failed\r"
		LogIt $disksize"KB boot disk was NOT created\r"
		rm -f $imagefile
	fi
	[ "$retval" -ne "0" ] && LogIt "PrepareBootDiskImage() is returning nonzero"
	return $retval
}


PrepareBootDiskImage_SYSLINUX() {
	local disksize imagesdir dev imagefile mountpoint fname i kernelpath ramdisksize cfg_file testpath options retval outstr old_pwd ooo max_kernel_size bootimage
	imagesdir=$1
	disksize=$2
	kernelpath=$3
	ramdisksize=$4
	do_boot_root_thingy=""
	local retval old_pwd
	retval=0

	[ ! -e "$kernelpath" ] && Die "PBDI - cannot find $kernelpath kernel"
	echo -en "Making "$disksize"KB boot disk..."
	TurnTgzIntoRdz $MINDI_LIB/rootfs $MINDI_TMP/mindi.rdz $ramdisksize $disksize `du -sk $kernelpath | cut -f1` || Die "Could not turn rootfs into mindi.rdz; are you SURE your kernel supports loopfs?"
	[ "$disksize" != "2880" ] && [ "$disksize" != "5760" ] && Die "PDBI - disksize is $disksize - bad size"
	echo -en "..."
	imagefile=$imagesdir/mindi-bootroot.$disksize.img
	mountpoint=$MINDI_TMP/mountpoint.$$
	mkdir -p $mountpoint
	dd if=/dev/zero of=$imagefile bs=1k count=$disksize &> /dev/null || Die "Cannot dd blank file"
	echo "Creating vfat filesystem on $imagefile" >> $LOGFILE
	mkfs.vfat $imagefile >> $LOGFILE 2>> $LOGFILE
	syslinux $imagefile >> $LOGFILE 2>> $LOGFILE

	mount -t vfat -o loop $imagefile $mountpoint || LogIt "Cannot mount (PBDI)"

	# copy Mindi's skeleton fs & lilo/syslinux/whatever stuff into it
	old_pwd=`pwd`
	MakeSyslinuxMessageFile $mountpoint/message.txt
	cd $mountpoint
	[ -e "$sys_cfg_file" ] || Die "Obi Wan, word up?"
	cat $sys_cfg_file | HackSyslinuxFile $ramdisk_size $mountpoint > syslinux.cfg || Die "Cannot copy syslinux.cfg from mindi_home to tmp_root"
	if [ "$NFS_DEV" != "" ] ; then
		perl -pi -e 's/interactive/iso/' syslinux.cfg
	fi
	cd $old_pwd
	echo "Copying $MINDI_TMP/mindi.rdz to $mountpoint/initrd.img..." >> $LOGFILE
	cp -f $MINDI_TMP/mindi.rdz $mountpoint/initrd.img 2>> $LOGFILE
	if [ "$?" -ne "0" ] ; then
		LogIt "Failed to copy $MINDI_TMP/mindi.rdz to $mountpoint"
		cat $MINDI_TMP/mtpt.$$ >> $LOGFILE
		LogIt "Please unload some of your modules and try again."
		rm -f $MINDI_TMP/mtpt.$$
		LogIt "Cannot incorporate mindi.rdz in bootdisk (kernel / modules too big?)"
		retval=$(($retval+1))
	fi

	mkdir -p $mountpoint/tmp
	cp -f $MINDI_TMP/mondo-restore.cfg $mountpoint/tmp &> /dev/null

	# copy the kernel across
	[ "$mountpoint" != "" ] && rm -Rf $mountpoint/lost+found
	dd if=/dev/zero of=$mountpoint/zero bs=1k count=16 &> /dev/null
	free_space=`df -k -P $mountpoint | tail -n1 | tr -s ' ' '\t' | cut -f4`
	cp -f $kernelpath $mountpoint/vmlinuz &> /dev/null
	if [ "$?" -ne "0" ] || [ "$FORCE_DUAL_FLOPPIES" = "yes" ] ; then
		echo "Files at mountpoint ($mountpoint) :-" >> $LOGFILE
		du -sk $mountpoint/* >> $LOGFILE
		echo "--- end of list of files ---" >> $LOGFILE
		echo -en "Kernel size = `du -sk $kernelpath | cut -f1` K\nRamdisk free = $free_space K\n\
Sorry, your kernel is too big for a boot/root floppy.\nI'll try the new boot/root two-disk thingy.\n" >> $LOGFILE
		rm -f $mountpoint/vmlinuz
		cd $old_pwd
		umount $mountpoint || Die "Cannot unmount mountpoint ($mountpoint)"
		rmdir $mountpoint || LogIt "Cannot rmdir (PBDI)"

		res=0
		write_full_floppy_of_kernel $kernelpath $imagesdir/mindi-boot.1440.img 1440
		res=$(($res+$?))
		cp -f $MINDI_TMP/mindi.rdz $imagesdir/mindi-root.1440.img 2>> $LOGFILE
		res=$(($res+$?))
		rm -f $imagefile
		if [ "$res" -ne "0" ]; then
			LogIt "WARNING - failed to create 1.44MB boot/root floppies"
			rm -f $imagesdir/mindi-*.1440.img
		fi
		return $res
	fi
	free_space=`df -k -P $mountpoint | tail -n1 | tr -s ' ' '\t' | cut -f4`
	max_kernel_size=$(($free_space+`du -sk $kernelpath | cut -f1`))
	echo "Free space left on floppy = $free_space KB" >> $LOGFILE
	echo "Max kernel size on $disksize KB floppy (est'd) = $max_kernel_size K" >> $LOGFILE

	# make it bootable
	rm -f $mountpoint/zero
	mkdir -p $mountpoint/etc
	[ -e "$MINDI_LIB/memdisk" ] && cp -f $MINDI_LIB/memdisk $mountpoint 2>> $LOGFILE
	umount $mountpoint || Die "Cannot unmount mountpoint ($mountpoint)"
	echo -en "..."
	rmdir $mountpoint || LogIt "Cannot rmdir (PBDI)"

	if [ "$retval" -eq "0" ] ; then
		echo -en "...$DONE\r"
		if [ "$KERN_DISK_MADE" ] ; then
		    rm -f $imagefile
		    LogIt "... $disksize KB boot disks were created OK\r"
		fi
	else
		echo -en "...failed\r"
		LogIt $disksize"KB boot disk was NOT created\r"
		rm -f $imagefile
	fi
	[ "$retval" -ne "0" ] && LogIt "PrepareBootDiskImage() is returning nonzero"
	return $retval
}


PrepareDataDiskImages() {
	local needlist bigdir minidir_root tardir diskdir imagesdir res i j k old_pwd lines lfiles

	imagesdir=$1
	rm -f $imagesdir/mindi-*.img $imagesdir/[0-9]*.tar.gz $imagesdir/mindi.iso
	needlist=$MINDI_TMP/what-we-need.txt
	bigdir=$MINDI_TMP/bigdir
	minidir_root=$MINDI_TMP/minidir
	mkdir -p $minidir_root
	mkdir -p $bigdir/usr/bin
	tardir=$MINDI_TMP/tardir

	if [ -e "$DEPLIST_FILE" ]; then
		lfiles="$DEPLIST_FILE $DEPLIST_DIR/*"
	else
		lfiles="$DEPLIST_DIR/*"
	fi
	lines=`grep -vx " *#.*" $lfiles | grep -vx "" | wc -l`
	cat $lfiles | GenerateGiantDependencyList $needlist $lines
	res=$?
	if [ "$YOUR_KERNEL_SUCKS" ]; then
		pwd=`pwd`
		cd $MINDI_TMP
		for i in `ListKernelModulePaths | HackPathsToFailsafe` ; do
			cp --parents -pRdf ./$i $bigdir 2>> $LOGFILE || Die "PDDI can't cp $i->$bigdir"
			if [ "`du -sk $i | cut -f1`" -lt "$(($CHOPSIZE*2))" ] ; then
				cp --parents -pRdf $i $bigdir 2>> $LOGFILE
			else
				ChopUpAndCopyFile $i $bigdir $CHOPSIZE $BIGNO
				BIGNO=$(($BIGNO+1))
			fi
		done
		for i in $EXTRA_MODS ; do
			j=`find lib/modules/$FAILSAFE_KVER -name $i.*o 2> /dev/null`
			[ ! "$j" ] && echo "WARNING - cannot find failsafe module $i.o" >> $LOGFILE
			for k in $j ; do
				if [ "`du -sk $k | cut -f1`" -lt "$CHOPSIZE" ] ; then
		    		cp --parents -pRdf $k $bigdir 2>> $LOGFILE
				else
		    		ChopUpAndCopyFile $k $bigdir $CHOPSIZE $BIGNO
		    		BIGNO=$(($BIGNO+1))
				fi
				echo "Added failsafe module $k to ramdisk" >> $LOGFILE
			done
		done
		cd $pwd
	else
		ListKernelModulePaths >> $needlist
	fi
	if [ "$res" -ne "0" ] ; then
		Die "You have $res file`PluralOrNot $res` present in dependency list\nbut absent from filesystem."
	fi
	FindAndAddUserKeyboardMappingFile
	mkdir -p $bigdir/tmp
	if [ _"$MONDO_SHARE" != _"" ]; then
		cp -f $MONDO_CACHE/mondo-restore.cfg $bigdir/tmp &> /dev/null
	fi
	[ -d "/mnt/.boot.d" ] && echo "Oh Jebus" > $bigdir/tmp/DUMBASS-GENTOO
	DropOptimizedLibraries $needlist $bigdir
	echo -en "Assembling dependency files"
	CopyDependenciesToDirectory < $needlist $bigdir

	# also copy io.sys and msdos.sys, if we can find them
	for i in `mount | cut -d' ' -f3` ; do
		for j in io.sys msdos.sys ; do
			[ -e "$i/$j" ] && cp -f $i/$j $bigdir 2>> $LOGFILE
		done
	done

	# master boot record, too
	i=`grep bootloader.device $MONDORESTORECFG | cut -d' ' -f2 2> /dev/null`
	if [ "$i" ] ; then
		LogIt "Backing up $i's MBR"
		dd if=$i of=$bigdir/BOOTLOADER.MBR bs=446 count=1 >> $LOGFILE 2>> $LOGFILE
		sleep 1
		sync
		j=$i
		[ -h "$j" ] && j=`readlink -f $j`
		LogIt "Creating /dev/boot_device ($j)"
		mkdir -p $bigdir/dev
		cp -pRdf $j $bigdir/dev/boot_device 2> /dev/null || Die "Unable to create /dev/boot_device on ramdisk"
	fi

	old_pwd=`pwd`
	cd $bigdir

	[ -e "$MINDI_LIB/aux-tools" ] || Die "aux-tools not found in Mindi's home dir. Do you have multiple copies of Mindi lying around? Please delete them. No, don't e-mail me and ask how. ;) Use 'rm'."
	cp -Rdf $MINDI_LIB/aux-tools/* . 2>> $LOGFILE || LogIt "WARNING - error occurred while unzipping aux-tools"
	if [ -e "$MINDI_LIB/x11-tools.tgz" ] ; then
		tar -zxf $MINDI_LIB/x11-tools.tgz 2>> $LOGFILE || LogIt "WARNING - error occurred while unzipping x11-tools.tgz"
	fi
	if [ -e "$MONDO_SHARE/restore-scripts" ]; then
		cp -Rdf $MONDO_SHARE/restore-scripts/* . 2>> $LOGFILE
		[ "$?" -ne "0" ] && Die "Cannot find/install $MONDO_SHARE/restore-scripts"
	fi
	[ -d "/lib/dev-state" ] && cp --parents -pRdf /lib/dev-state . 2>> $LOGFILE
	cd $old_pwd
	echo -e "$DONE"
	TOTAL_BIGDIR_SIZE=`du -sk $bigdir | cut -f1`
	SplitDirectoryIntoMinidirs $bigdir $minidir_root
	noof_disks=$?
	[ "$noof_disks" -eq "0" ] && Die "Too much stuff!"
	MakeMountlist $MINDI_TMP/mountlist.txt
	mkdir -p $minidir_root/$noof_disks/tmp
	cp -f $MINDI_TMP/mountlist.txt $minidir_root/$noof_disks/tmp/mountlist.txt 2> /dev/null || Die "Cannot copy mountlist.txt from $MINDI_TMP to data disk"
	if [ _"$MONDO_SHARE" != _"" ]; then
		cp -f $minidir_root/$noof_disks/tmp/mountlist.txt $MINDI_TMP/. 2>> $LOGFILE
	fi
	[ $LVM != "false" ] && $MINDI_LIB/analyze-my-lvm > $minidir_root/$noof_disks/tmp/i-want-my-lvm || LVM="false"
	cat $minidir_root/$noof_disks/tmp/mountlist.txt >> $LOGFILE
	ZipMinidirsIntoTarballs $minidir_root $tardir $noof_disks
	CreateDataDiskImagesFromTarballs $tardir $imagesdir $noof_disks
	FRIENDLY_OUTSTRING="Boot and data disk images were created."
	# One 1.72MB boot disk, one 2.88MB boot disk and $noof_disks data disk images
	rmdir $tardir $bigdir
	rm -f $needlist
	return $noof_disks
}


ProcessLDD() {
	local main_fname incoming j i fname f newf
	main_fname=$1
	read incoming
	while [ "$incoming" != "" ] ; do
		# We take the full path name of the dyn. lib. we want
		incoming=`echo "$incoming" | sed '/[[:blank:]]*.*[[:blank:]]*=>[[:blank:]]*(.*/d ; s/[[:blank:]]*.*[[:blank:]]*=>[[:blank:]]*\(\/.*\)/\1/ ; s/[[:blank:]]*\(\/.*\)[[:blank:]]*(.*/\1/'`
		for f in `echo "$incoming"` ; do
			echo "$f `ReadAllLink $f`"
		done
		read incoming
	done
}


Prompt() {
	echo -en "$1"
	read line
}


ReadLine() {
	local i incoming
	read incoming
	i=0
	while [ "$i" -le "32" ] && [ "$incoming" = "" ] ; do
		i=$(($i+1))
		read incoming
	done
	echo "$incoming"
}


RejigHyperlinks() {
	local minidir_root noof_disks fname path diskno old_pwd awk_loc gawk_loc dir i
	minidir_root=$1
	noof_disks=$2

	old_pwd=`pwd`
	diskno=1
	while [ "$diskno" -le "$noof_disks" ] ; do
		mkdir -p $minidir_root/$diskno
		cd $minidir_root/$diskno
		for fname in `find -type d -o -print` ; do
		    [ -h "$minidir_root/$diskno/$fname" ] && MoveHyperlinkSensibly $fname $minidir_root $diskno $noof_disks
		done
		diskno=$(($diskno+1))
	done

	cd $old_pwd
	return
}


ReplaceIndividualLine() {
	local orig_file new_file lino newstring lines_total lines_remaining

	orig_file=$1.orig
	mv -f $1 $orig_file || Die "Cannot move $1 to $orig_file"
	new_file=$1
	lino=$2
	newstring="$3"
	if [ "$lino" = "" ] || [ "$lino" -lt "1" ] ; then
		echo "Can't find string" >> $LOGFILE
		return 1
	fi
	lines_total=`wc -l $orig_file | $AWK '{print $1;}'`
	lines_remaining=$(($lines_total-$lino))
	head -n$(($lino-1)) $orig_file > $new_file
	echo "$newstring" >> $new_file
	echo "# The above line was added by Mindi, at the user's instruction" >> $new_file
	tail -n$lines_remaining $orig_file >> $new_file
	echo "Replace line $lino of $new_file with user-specified line, '$newstring'" >> $LOGFILE
	[ -x "$orig_file" ] && chmod +x $new_file
	rm -f $orig_file
	return 0
}


ScanCDandTape() {
	local i

	for i in /dev/st0 /dev/ht0 /dev/cdrom /dev/cdrom0 /dev/cdrom 1 ; do
		dd if=$i of=/dev/null bs=64k count=1 &> /dev/null
	done
}


SizeOfPartition() {
	local devpath drive res stub
	device=$1
	if [ "`echo "$device" | grep -F "/dev/md"`" != "" ] ; then
		res=`SizeOfRaidPartition $device`
		[ "$res" = "" ] && Die "Cannot find $device's size - is your /etc/raidtab sane?"
		echo "$res"
		return 0
	fi
	# patch from Bill <bill@iwizard.biz> - 2003/08/25
	res=`$FDISK -s $device 2>> $LOGFILE`
	# end patch
	[ "$res" = "" ] && res=`df -k -P -x supermount | tr -s '\t' ' ' | grep -F "$device " | cut -d' ' -f2`
	[ "$res" = "" ] && res="-1"
	echo $res
	return 0
}


SizeOfRaidPartition() {
	local real_dev smallest_size silly tmp

	silly=999999999
	smallest_size=$silly

	for real_dev in `GetRaidDevMembers $1` ; do
		tmp=`SizeOfPartition $real_dev`
		[ "$tmp" -lt "$smallest_size" ] && smallest_size=$tmp
	done

	if [ "$smallest_size" = "$silly" ] ; then
		echo "-1"
		return 1
	else
		echo "$smallest_size"
		return 0
	fi
}


StripComments()
{
	local tempfile

	tempfile=$MINDI_TMP/$$.strip.txt
	cp -f $1 $tempfile 2>> $LOGFILE
	$AWK '{if (substr($0,0,1)!="#" || substr($0,0,3)=="#!/") {print $0;};}' $tempfile > $1
	rm -f $tempfile
	echo "Stripped comments from $2" >> $LOGFILE
}


SplitDirectoryIntoMinidirs() {
	local bigdir minidir_root i noof_disks old_pwd res

	bigdir=$1
	minidir_root=$2
	[ "$minidir_root" != "" ] && rm -Rf $minidir_root/*

	TryToFitDataIntoSeveralDirs $bigdir $minidir_root
	noof_disks=$?
	if [ "$noof_disks" -eq "0" ] ; then
		echo "Failed to fit data into several dirs."
		return 0
	fi
	RejigHyperlinks $minidir_root $noof_disks
	[ "$bigdir" != "" ] && rm -Rf $bigdir/*
	return $noof_disks
}


StripExecutable()
{
	local tmpfile

	tmpfile=$MINDI_TMP/stripped.$$.dat
	[ -d "$1" ] || [ -h "$1" ] && return
	cp -f $1 $tmpfile 2>> $LOGFILE
	strip $tmpfile 2> /dev/null
	if [ "$?" -eq "0" ] ; then
		cp -f $tmpfile $1 2>> $LOGFILE
		echo "Stripped binary $2" >> $LOGFILE
	fi
	rm -f $tmpfile
}


TemporarilyCompressAllFiles() {
	local i orig_fname out_fname out_list

	i=0
	out_list=$2/compressed/compressed.txt
	mkdir -p $2/compressed
	> $out_list
	for orig_fname in $1 ; do
		out_fname=$2/compressed/$orig_fname.gz
		mkdir -p $out_fname 2> /dev/null
		rmdir $out_fname 2> /dev/null
		gzip -c6 $orig_fname > $out_fname 2> /dev/null
		i=$(((($i+1))%15))
		[ "$i" -eq "0" ] && echo -en "."
		du -sk $out_fname >> $out_list
	done
}


TryToFindKernelPath() {
	local fname incoming res fkern_ver we_want_version possible_kernels noof_kernels kernelpath kdate duff_kernels

	we_want_version=`uname -r`
	possible_kernels=""
	duff_kernels=""
   
	if [ "$ARCH" = "ia64" ] ; then
	   root="/boot/efi/efi"
	else
	   root="/"
	fi
	for fname in `find $root -maxdepth 2 -type f | grep -F lin | grep -Ev '^/proc/|^/net/'` ; do
		[ ! -e "$fname" ] && continue
		[ "$fname" = "/boot/vmlinuz.shipped" ] && [ -f "/boot/vmlinuz" ] && continue; # ignore SuSE's extra kernel
		file $fname | grep -q gzip
		if [ "$?" -eq "0" ] ; then
			# Used by ia64
		    fkern_ver=`gzip -cd $fname | strings 2> /dev/null | grep "[2-9]+*[.][0-9]+*[.][0-9]+*[^\@]*@"`
		else
		    fkern_ver=`strings $fname 2> /dev/null | grep "[2-9]+*[.][0-9]+*[.][0-9]+*[^\@]*@"`
		fi
		[ "$fkern_ver" = "" ] && continue
		[ "`echo "$fkern_ver" |grep -F "$we_want_version "`" = "" ] && continue
		[ -f "$fname" ] || continue
		[ -h "$fname" ] && continue
		kdate=`uname -v | $AWK '{for(i=1;i<NF;i++){if(index($i,":")){print $i;};};}' | $AWK '{print $NF;}'`
		file $fname | grep -q gzip
		if [ "$?" -eq "0" ] ; then
			# Used by ia64
			if [ "`gzip -cd $fname | strings 2> /dev/null | grep -F "$kdate"`" = "" ] ; then
		    	LogIt "Have you recompiled your kernel \"$fname\" w/o rebooting? Naughty but I'll allow it..."
		    	duff_kernels="$fname $duff_kernels"
			else
		        [ "`echo "$fname" | grep -F "vmlinux"`" ] && continue
		        possible_kernels="$fname $possible_kernels"
			fi
		else
			if [ "`strings $fname 2> /dev/null | grep -F "$kdate"`" = "" ] ; then
		    	LogIt "Have you recompiled your kernel \"$fname\" w/o rebooting?\n Naughty but I'll allow it..."
		    	duff_kernels="$fname $duff_kernels"
			else
		        [ "`echo "$fname" | grep -F "vmlinux"`" ] && continue
		        possible_kernels="$fname $possible_kernels"
			fi
		fi
	done
	if [ ! "$possible_kernels" ] && uname -a | grep Knoppix > /dev/null ; then
		possible_kernels=`find /boot/vmlinuz-2.* | tail -n1`
	fi
	if [ ! "$possible_kernels" ] ; then
		LogIt "No kernel matches exactly. Are there any duff kernels?"
		possible_kernels="$duff_kernels"
		if [ ! "$possible_kernels" ] ; then
		    LogIt "Sorry, no duff kernels either"
		else
		    LogIt "I bet you're running Debian or Gentoo, aren't you?"
		    LogIt "Your kernel doesn't have a sane builddate. Oh well..."
		fi
	fi
	possible_kernels=`echo "$possible_kernels" | tr -s ' ' '\n' | sort -u | tr '\n' ' '`
	noof_kernels=`CountItemsIn "$possible_kernels"`
	if [ "$noof_kernels" -eq "0" ] ; then
		LogIt "Could not find your kernel."
		if [ -e "/boot/vmlinuz" ] ; then
			LogIt "Using /boot/vmlinuz as a last resort."
			output=/boot/vmlinuz
		else
			output=""
		fi
	elif [ "$noof_kernels" -eq "1" ] ; then
		kernelpath=`echo "$possible_kernels" | sed s/' '//`
		echo "Your kernel is $kernelpath (v`uname -r`)" >> $LOGFILE
		output="$kernelpath"
	else
		for i in $possible_kernels ; do
		    if echo $i | grep "`uname -r`" ; then
				LogIt "OK, I used my initiative and found that "
		        LogIt "$i is probably your kernel. "
				output="$i"
				return
			fi
		done
		if echo " $possible_kernels " | grep -F "/boot/vmlinuz " &> /dev/null ; then
			output=/boot/vmlinuz
			echo "Schlomo, this one's for you." >> $LOGFILE
		else
		    LogIt "Two or more possible kernels found. You may specify any one of them and the "
			LogIt "boot disks will still work, probably. If one does not work, try another."
		    LogIt "$possible_kernels"
		    echo ""
		fi
	fi
	echo "$output" | tr -s ' ' '\n' | sort -u | tr '\n' ' '
}


TryToFitDataIntoSeveralDirs() {
	local bigdir minidir_root noof_disks diskno list_of_files filename old_pwd progress
	local i retval noof_disks total_files list_of_devs

	bigdir=$1
	minidir_root=$2
	BIG_CLUNKY_SIZE_COUNTER=0
	retval=0
	noof_disks=1

	echo -en "\r                                                                            \rDividing data into several groups..."
	old_pwd=`pwd`
	cd $bigdir
	list_of_files=`GetFileSizeList . | sort -nr | cut -f2 | grep -Fv "/dev/"`
	progress=0
	total_files=`CountItemsIn "$list_of_files"`
	if [ "`echo "$filename" | grep -x "/dev/.*"`" ] ; then
		filesize=1
	fi
	mkdir -p $minidir_root/$noof_disks
	if [ -e "dev" ] ; then
		echo "Copying dev/* to $minidir_root/$noof_disks" >> $LOGFILE
		cp --parents -pRdf dev $minidir_root/$noof_disks 2>> $LOGFILE
	fi
	TemporarilyCompressAllFiles "$list_of_files" $minidir_root
	for filename in $list_of_files ; do
		AddFileToDir $filename $minidir_root $noof_disks
		i=$?
		if [ "$i" -gt "$noof_disks" ] ; then
			noof_disks=$i
			echo -en "\r\t\t\t\t\t\t($noof_disks disks)"
		fi
		if [ "$i" -eq "0" ] ; then
			LogIt "Cannot add file $filename to minidir $minidir_root"
			retval=$(($retval+1))
		fi
		progress=$(($progress+1))
		echo -en "\r\t\t\t\t\t\t\t\t$(($progress*100/$total_files))% complete\r"
	done
	cd $old_pwd
	echo -en "\rThe files have been subdivided into $noof_disks directories.                                                            \r"
	[ "$minidir_root" != "" ] && rm -Rf $minidir_root/compressed
	if [ "$retval" -gt "0" ] ; then
		return 0
	else
		return $noof_disks
	fi
}


TurnTgzIntoRdz() {
	local tgz_dir_fname rdz_fname ramdisksize tempfile mountpoint old_pwd nodes disksize kernelsize maxsize res currsize not_copied j k floppy_modules s w

	tgz_dir_fname=$1
	rdz_fname=$2
	ramdisksize=$3
	disksize=$4
	kernelsize=$5
	maxsize=$(($disksize-$kernelsize))
	maxsize=$(($maxsize*2)); # to allow for compression of 50%
	tempfile=$MINDI_TMP/temp.rd
	mountpoint=$MINDI_TMP/mnt1
	res=0
	echo -en "..."
	dd if=/dev/zero of=$tempfile bs=1k count=$ramdisk_size &> /dev/null || Die "Not enough room for temporary ramdisk (TurnTgzIntoRdz)"
	echo -en "..."
	echo "Creating ext2 filesystem on $tempfile" >> $LOGFILE
	mke2fs -b 1024 -m 1 -i 2048 -F $tempfile >> $LOGFILE 2>> $LOGFILE
	echo -en "..."
	mkdir -p $mountpoint
	mount -t ext2 -o loop $tempfile $mountpoint || Die "Cannot loopmount $tempfile to $mountpoint! The reason may be missing support for loopfs or ext2 (or both) in the running kernel."
	echo -en "..."
	old_pwd=`pwd`
	cd $mountpoint
	cp -Rdf $tgz_dir_fname/* . 2>&1 >> $LOGFILE
	tar -zxf symlinks.tgz || Die "Cannot untar symlinks.tgz"
	cd dev || Die "Can't cd to dev"
	tar -zxf dev-entries.tgz || Die "Cannot untar dev-entries.tgz"
	rm -f dev-entries.tgz
	cd ..

	for w in insmod.static insmod.static.old ; do
		s=`which $w 2> /dev/null`
		if [ -e "$s" ] ; then
			cp --parents -af $s . 2>> $LOGFILE
		fi
	done

	mkdir -p tmp
	[ -e "/dev/.devfsd" ] && echo "/dev/.devfsd found" > tmp/USE-DEVFS
	for w in cdrom floppy groovy-stuff ; do
		mkdir -p mnt/$w
	done
	#if [ "$RUN_AFTER_INITIAL_BOOT_PHASE" ] ; then
		#ReplaceIndividualLine sbin/init `grep -n "#WHOLIVESINAPINEAPPLEUNDERTHESEA#" sbin/init | cut -d':' -f1` "$RUN_AFTER_INITIAL_BOOT_PHASE"
	#fi
	if [ "$RUN_AFTER_BOOT_PHASE_COMPLETE" ] ; then
		ReplaceIndividualLine sbin/init `grep -n "#ABSORBENTANDYELLOWANDPOROUSISHE#" sbin/init | cut -d':' -f1` "$RUN_AFTER_BOOT_PHASE_COMPLETE"
	fi

	lsmod > tmp/original-lsmod.txt
	
	cp --parents -Rdf /dev/fd0*[1,2][4,7,8]* . 2> /dev/null
	cd $old_pwd
	echo -en "..."
	MakeModuleLoadingScript $TMPMODPROBE_FLAG $mountpoint/sbin/insert-all-my-modules
	echo -en "..."
	old_pwd=`pwd`
	if [ "$YOUR_KERNEL_SUCKS" ] ; then
		cd $MINDI_TMP
		floppy_modules_path=lib/modules/$FAILSAFE_KVER
	else
		cd /
###
### Sq-Modification... Use kernel name in module path if specified.
###
		#floppy_modules_path=lib/modules/`uname -r`
		if [ "${kernelname}" != "" ]
		then
			floppy_modules_path=lib/modules/${kernelname}
		else
			floppy_modules_path=lib/modules/`uname -r`
		fi
###
### Sq-Modification end
###
	fi
	floppy_modules=""
	if [ "$disksize" -lt "2880" ] ; then
		list_of_groovy_mods="$FLOPPY_MODS $IDE_MODS ide-scsi sr_mod cdrom isocd isofs `WhichOfTheseModulesAreLoaded "$SCSI_MODS"`"
	else
		list_of_groovy_mods="$CDROM_MODS `WhichOfTheseModulesAreLoaded "$SCSI_MODS"`"
	fi
	if [ "$NFS_DEV" != "" ] ; then
		# For PXE boot
		list_of_groovy_mods="$list_of_groovy_mods $NET_MODS"
	fi
	[ -e "$floppy_modules_path" ] || LogIt "path $floppy_modules_path does not exist.\n If you're not using a modular kernel then you're NUTS."
	for i in $list_of_groovy_mods ; do
		floppy_modules="$floppy_modules `FindSpecificModuleInPath $floppy_modules_path $i`"
	done
	for i in $floppy_modules ; do
		[ -e "$i" ] && s=`du -sk $i | cut -f1` || s=""
		[ "$YOUR_KERNEL_SUCKS" ] && i=$MINDI_TMP/$i
		echo "Adding $i ($s KB) to the rootfs" >> $LOGFILE
		cp -df $i $mountpoint/ 2>/dev/null || LogIt "Unable to copy $i to $mountpoint"
		[ "`echo "$i" | grep -F ".gz"`" ] && gunzip -f $mountpoint/`basename $i`
	done
	if [ ! -e "/sbin/devfsd" ] || [ "$disksize" -lt "2880" ] || [ "$kernelpath" = "$MINDI_LIB/vmlinuz" ] ; then
		echo "Deleting devfsd daemon from ramdisk" >> $LOGFILE
		[ ! -e "/sbin/devfsd" ] && echo "...because /sbin/devfsd not found" >> $LOGFILE
		[ "$disksize" -lt "2880" ] && echo "...because disksize = $disksize" >> $LOGFILE
		[ "$kernelpath" = "$MINDI_LIB/vmlinuz" ] && echo "...because kernel is failsafe" >> $LOGFILE
		rm -f $mountpoint/sbin/devfsd
	fi
	cd $old_pwd
	[ "$PROMPT_MAKE_TAPE_IMAGE" = "yes" ] && echo -en "$TAPEDEV" > $mountpoint/tmp/TAPEDEV-LIVES-HERE
	dd if=/dev/zero of=$mountpoint/zero &> /dev/null
	rm -f $mountpoint/zero
	mkdir -p $mountpoint/tmp
	if [ _"$MONDO_SHARE" != _"" ]; then
		cp -f $MONDO_CACHE/mondo-restore.cfg $mountpoint/tmp &> /dev/null || Die "Cannot copy mondo-restore.cfg to ramdisk"
		cp -f $MINDI_TMP/mountlist.txt $mountpoint/tmp/ 2>/dev/null || Die "Cannot copy mountlist to ramdisk"
	fi
	mkdir -p $mountpoint/proc
	echo "$disksize" > $mountpoint/tmp/$disksize.siz
	find $mountpoint -name CVS -exec rm -rf '{}' \;
	# Determine what filesystem to use for initrd image
	LogIt "Call GetInitrdFilesystemToUse() with parameter ${kernelpath} to get filesystem to use for initrd.\n"
	gvFileSystem=`GetInitrdFilesystemToUse ${kernelpath}`
	[ -z  gvFileSystem ] && Die "GetFilesystemToUse() failed. Terminating."
	case "$gvFileSystem" in
	"ext2fs")
		# say what will be used
    		LogIt "Creating an ext2 initrd image..."
		# kernel expects linuxrc in ext2 filesystem
		( cd $mountpoint && ln -s sbin/init linuxrc )
		# unmount loop filesystem and create image file using the standard approach
		umount $mountpoint || Die "Cannot unmount $tempfile"
		dd if=$tempfile bs=1k 2> /dev/null | gzip -v9 > $rdz_fname 2> /dev/null
		# log that we are done
    		LogIt "done.\n"
	;;
	"initramfs")
		# say what will be used
    		LogIt "Creating a gzip'ed cpio (AKA initramfs) initrd image..."
		# make sure that cpio is there
		which cpio &> /dev/null; [ $? -eq 0 ] || Die "cpio not found. Please install package cpio and try again."
		# go into filesystem
		cd $mountpoint
		# kernel expects init in cpio filesystem
		ln -s sbin/init init
		# create cpio image file and unmount loop filesystem
		find . -print | cpio -o -H newc | gzip -9 > $old_pwd/$rdz_fname 2> /dev/null
		cd $old_pwd
		umount $mountpoint || Die "Cannot unmount $tempfile"
		# log that we are done
    		LogIt "done.\n"
	;;
	*)
		Die "Filesystem $gvFileSystem not supported for initrd image. Terminating."
	;;
	esac
	if [ "$res" -eq "0" ] ; then
		echo -en "..."
	else
		echo -en "\rMade an rdz WITH ERRORS.           \n"
	fi
	return 0
}


WhichOfTheseModulesAreLoaded() {
	local modname loaded_modules
	loaded_modules=" `lsmod | tr -s ' ' '\t' | cut -f1 | grep -Fvx "Modules" | tr '\n' ' '` "
	for modname in $1 ; do
		[ "`echo "$loaded_modules" | grep -F " $modname "`" ] && echo "$modname"
	done
}


ZipMinidirsIntoTarballs() {
	local minidir_root tardir noof_disks diskno old_pwd i
	minidir_root=$1
	tardir=$2
	noof_disks=$3

	echo -en "Tarring and zipping the group`PluralOrNot $noof_disks`..."
	mkdir -p $tardir
	mkdir -p $minidir_root/all
	old_pwd=`pwd`
	diskno=1
	while [ "$diskno" -le "$noof_disks" ] ; do
		cd $minidir_root/$diskno || LogIt "WARNING - cannot cd to $minidir_root/$diskno"
		tar -cf - . 2>> $LOGFILE | gzip -9 > $tardir/$diskno.tar.gz || Die "Can't tar/gzip disk#$diskno; please tell Dev Team -exactly- what the errors where."
		diskno=$(($diskno+1))
		echo -n "..."
		cp -pRdf * $minidir_root/all 2>> $LOGFILE
	done
	mkdir -p $minidir_root/all/tmp
	cd $minidir_root/all
	size_of_all_tools=`du -sk . | cut -f1`
	if [ _"$MONDO_SHARE" != _"" ]; then
		for q in filelist.full.gz biggielist.txt ; do
		    [ ! -e "$MINDI_TMP/$q" ] && Die "Cannot find $MINDI_TMP/$q"
		    cp -pRdf $MINDI_TMP/$q tmp/ 2>> $LOGFILE
		done
		mkdir -p $minidir_root/all/tmp
	fi
	tar -b 4096 -cf - * 2> /dev/null | gzip -9 > $tardir/all.tar.gz
	dd if=/dev/zero bs=1k count=64 >> $imagesdir/all.tar.gz 2> /dev/null
	[ "`du -sm $imagesdir/all.tar.gz | cut -f1`" -ge "30" ] && Die "You have too many tools in your shed"
	cd $old_pwd
	[ "$minidir_root" != "" ] && rm -Rf $minidir_root
	echo -e "$DONE"
}


##############################################################################
#----------------------------------- Main -----------------------------------#
##############################################################################

# Now we can create what we nedd
mkdir -p $MINDI_TMP

# Purge from potential old run
if [ _"$MINDI_CACHE" = _"" ]; then
	Die "MINDI_CACHE undefined"
fi
rm -rf $MINDI_CACHE 2> /dev/null
mkdir -p $MINDI_CACHE


if [ "$1" = "--printvar" ] ; then
	shift
	if [ _"$1" != _"" ] ; then
		set | egrep "^$1" | cut -d= -f2
	fi
	MindiExit 0
fi

> $LOGFILE
echo "mindi v$MINDI_VERSION" >> $LOGFILE
echo "$ARCH architecture detected" >> $LOGFILE
echo "mindi called with the following arguments:" >> $LOGFILE
echo "$@" >> $LOGFILE
echo "Start date : `date`" >> $LOGFILE
echo "-----------------------------" >> $LOGFILE

if [ -e "/etc/conf.modules" ] && [ ! -e "/etc/modules.conf" ] ; then
	LogIt "WARNING - Ancient distro detected." 1
	ln -sf /etc/conf.modules /etc/modules.conf
fi
[ -e "/sbin/mkdosfs" ] && [ ! -e "/sbin/mkfs.vfat" ] && ln -sf /sbin/mkdosfs /sbin/mkfs.vfat

# Log some capital variables
[ "$MINDI_PREFIX" = "XXX" ] && Die "Mindi has not been installed correctly."
echo "MONDO_SHARE = $MONDO_SHARE" >> $LOGFILE
echo "MINDI_LIB = $MINDI_LIB" >> $LOGFILE
echo "MINDI_SBIN = $MINDI_SBIN" >> $LOGFILE
[ "$MINDI_CONF" = "YYY" ] && Die "Mindi has not been installed correctly."
echo "MINDI_CONF = $MINDI_CONF" >> $LOGFILE
if [ -f $MINDI_CONF ]; then
	echo "-----------------------------" >> $LOGFILE
	echo " Mindi configuration file    " >> $LOGFILE
	echo "-----------------------------" >> $LOGFILE
	cat $MINDI_CONF >> $LOGFILE
	echo "-----------------------------" >> $LOGFILE
fi


trap AbortHere SIGTERM SIGHUP SIGQUIT SIGKILL SIGABRT SIGINT

# Sanity checks
which which > /dev/null 2> /dev/null || Die "Please install 'which'."
which strings > /dev/null 2> /dev/null || Die "Please install binutils and libbinutils; you have no 'strings' executable."
which gawk > /dev/null 2> /dev/null || Die "Gawk is missing from your computer. Please install gawk. You may find the package on Debian's website. How did I know you're running Debian? Because only Debian would be stupid enough not to include gawk in your distribution."
which gawk > /dev/null 2> /dev/null && AWK=`which gawk 2>/dev/null` || AWK="`which awk 2>/dev/null`"
if which awk &> /dev/null ; then
	if ! which gawk &> /dev/null ; then
		LogIt "You have awk but not gawk.\nPlease note that mindi works fine with a _sane_ awk binary.\nIf your awk binary misbehaves then please contact your vendor\nor distribution's mailing list for technical support.\n"
	fi
fi
which mke2fs > /dev/null 2> /dev/null || Die "Please put mke2fs in system path"
[ ! -e "$FDISK" ] && Die "Cannot find (s)fdisk"

[ "`uname -r | grep "2.4.[0-6]" | grep -v "2.4.[0-9][0-9]"`" != "" ] &&  echo "WARNING! Your kernel may have buggy loopfs code. Consider upgrading to 2.4.7"
# If we have a 2.6 kernel, the system uses module-init-tools which means that we
# may have the modprobe configuration spread out across multiple files in
# directory /etc/modprobe.d. If this is the case we concatenate these files into
# a temporary file for further processing. Otherwise we continue in the standard
# way. Note further that in case /etc/modprobe.d exists, we use it and ignore
# /etc/modprobe.conf which is exactly what module-init-tools does. The temporary
# modprobe.conf file is created in MakeModuleLoadingScript. AL041128.
if [ -d "/etc/modprobe.d" ] && [ `uname -r | cut -c1-3` == "2.6" ] ; then
	TMPMODPROBE_FLAG="Y"
else
	TMPMODPROBE_FLAG="N"
	[ -e "/etc/modprobe.conf" ] && [ ! -e "/etc/modules.conf" ] && ln -sf /etc/modprobe.conf /etc/modules.conf
	[ ! -e "/etc/modules.conf" ] && Die "/etc/modules.conf not found; you may have to create a softlink from /etc/conf.modules to /etc/modules.conf; of course, all good distros use modules.conf anyway..."
fi

# Update the PATH variable if incomplete
if [ -e "/sbin/mkfs" ] && ! which mkfs &> /dev/null ; then
	PATH=$PATH:/sbin:/usr/sbin
	export PATH
	echo "Your PATH did not include /sbin or /usr/sbin. I have fixed that, temporarily." >> $LOGFILE
	echo "However, you may wish to ask your vendor to provide a permanent fix..." >> $LOGFILE
	echo " Or you might like to call 'su -' instead of 'su', for example." >> $LOGFILE
fi

# If we have a distribution-specific script for finding a FAILSAFE kernel, use it.
if [ -f "$MINDI_LIB/FindDistroFailsafe" ] && [ ! "$1" = "--makemountlist" ] && [ "$kernelpath" = "FAILSAFE" ]; then
	source $MINDI_LIB/FindDistroFailsafe
	# Log kernel image
	LogIt "FAILSAFE kernel image to be used is: $FAILSAFE_KBIN ($FAILSAFE_KVER)"
else
	[ -f "$MINDI_LIB/vmlinuz" ] && FAILSAFE_KVER=`strings $MINDI_LIB/vmlinuz 2> /dev/null | grep -E "2\.[46]" | cut -d' ' -f1`
fi

if ! which mkfs.vfat &> /dev/null ; then
    Die "mkfs.vfat missing from your filesystem - please install your dosfstools RPM or DEB package. Perhaps your PATH environmental variable is broken, too?"
fi

### BERLIOS
### Fix as it's not mandatory on ia64
if [ "$ARCH" = "ia64" ] ; then
	if which elilo &> /dev/null ; then
		LILO_EXE=elilo
	else
		LILO_EXE=`which false`
	fi
else
	FindIsolinuxBinary
	FindLiloBinary
fi
trap "Aborted" SIGTERM
DONE="\r\t\t\t\t\t\t\t\tDone.         "
CHOPSIZE=240
BIGNO=0
MAX_COMPRESSED_SIZE="$mindi_max_compressed_size"

#
# Kernel management: Attempt to locate kernel specific module path
# if module path is found then use it other wise use uname -r to set it...
#
#
kernelpath="$mindi_kernel"
if [ "$kernelpath" = "NATIVE" ]; then
	kernelpath=""
fi
if [ "$kernelpath" = "" ]; then 
	kernelpath=`TryToFindKernelPath`
fi
kernelname=`echo $kernelpath | cut -d'-' -f2-`
echo "kernelname = $kernelname" >> $LOGFILE
echo "kernelpath = $kernelpath" >> $LOGFILE
if [ ! -d "/lib/modules/$kernelname" ] && [ "$kernelpath" != "FAILSAFE" ]
then
   echo "Module path for ${kernelpath} not found..." >> $LOGFILE
   echo "using running kernel\'s modules." >> $LOGFILE
   kernelname=`uname -r`
else
   echo "Using modules for kernel: ${kernelname}" >> $LOGFILE
fi

if [ -d "/proc/lvm" ]; then
	# LVM v1
	LVMCMD=""
	LVM="v1"
elif [ -d "/dev/mapper" ]; then
	# LVM v2
	LVMCMD="lvm"
	LVM="v2"
else
	LVM="false"
fi
echo "LVM set to $LVM" >> $LOGFILE
echo "----------" >> $LOGFILE
echo "df result:" >> $LOGFILE
echo "----------" >> $LOGFILE
df -T >> $LOGFILE
echo "-------------" >> $LOGFILE
echo "lsmod result:" >> $LOGFILE
echo "-------------" >> $LOGFILE
lsmod >> $LOGFILE
echo "-------------" >> $LOGFILE
echo "Liste of extra modules is:" >> $LOGFILE
echo "$EXTRA_MODS" >> $LOGFILE
echo "-------------" >> $LOGFILE


FLOPPY_WAS_MOUNTED=""
for mtpt in /media/floppy /mnt/floppy /floppy ; do
	if mount | grep -w $mtpt &> /dev/null ; then
		FLOPPY_WAS_MOUNTED="$FLOPPY_WAS_MOUNTED $mtpt"
		umount $mtpt
	fi
done

#
# If we have a USB device we need to store info 
# and remove it from the parameters line
#
if [ "$#" -ne "0" ] ; then
	if [ "$1" = "--usb" ] ; then
		shift
		USBDEVICE=$1
		if [ _"$USBDEVICE" = _"" ]; then
			Die "No USB device specified"
		fi
		shift
	fi
fi

#
# Default value for parameters coming from mondo potentially
#
if [ "$ARCH" = "ia64" ] ; then
	USE_LILO=yes
else
	USE_LILO=no
fi

#
# These variables are normaly only significant in a mondo environment
# Not enforced yet
#
CDRECOVERY="no"
NOT_BOOT="no"
EXCLUDE_DEVS=""
IMAGE_DEVS=""
NFS_DEV=""

#
# Deal with parameters
#
if [ "$#" -ne "0" ] ; then
	if [ "$1" = "--findkernel" ] ; then
		res=`TryToFindKernelPath`
		if [ "$res" = "" ] ; then
		    MindiExit -1
		else
		    echo "$res"
		    MindiExit 0
		fi
	elif [ "$1" = "--makemountlist" ] ; then
		[ ! "$2" ] && Die "Please specify the output file"
		MakeMountlist $2
		MindiExit $?
	elif [ "$1" = "-V" ] || [ "$1" = "-v" ] || [ "$1" = "--version" ] || [ "$1" = "-version" ] ; then
		echo "Mindi v$MINDI_VERSION"
		MindiExit 0
	elif [ "$1" = "--custom" ] ; then
		if [ _"$MONDO_SHARE" = _"" ]; then
			Die "--custom is reserved for mondoarchive calls"
		fi
		MONDO_TMP=$2
		# Change MINDI_TMP for the one provided by mondo 
		# So that it can get back the built files
		mv $MINDI_TMP/* $MINDI_TMP/.??* $MONDO_TMP 2> /dev/null
		rmdir $MINDI_TMP
		MINDI_TMP=$MONDO_TMP
		mkdir -p $MINDI_TMP
		# This is the scratch dir in mondo
		MINDI_CACHE=$3
		if [ _"$MINDI_CACHE" != _"" ]; then
			mkdir -p $MINDI_CACHE
		fi

		if [ ! -e "$MONDORESTORECFG" ]; then
			Die "MONDORESTORECFG undefined. Use an uptodate mondoarchive version"
		fi

		if [ ! -e "$MONDO_CACHE" ]; then
			Die "MONDO_CACHE undefined. Use an uptodate mondoarchive version"
		else
			#
			# Get from mondo our additional configuration
			#
			echo "Using $MONDO_CACHE/mindi.conf as additional config file"
			if [ -f $MONDO_CACHE/mindi.conf ]; then
				. $MONDO_CACHE/mindi.conf
				echo "-----------------------------" >> $LOGFILE
				echo " Mondo configuration file    " >> $LOGFILE
				echo "-----------------------------" >> $LOGFILE
				cat $MONDO_CACHE/mindi.conf >> $LOGFILE
				echo "-----------------------------" >> $LOGFILE
			else
				Die "No mindi.conf file created by mondo. Aborting"
			fi
		fi

		echo "Here is your mondoresctore.cfg file:" >> $LOGFILE
		echo "------------------------------------" >> $LOGFILE
		cat $MONDORESTORECFG >> $LOGFILE
		echo "-----------------------------------" >> $LOGFILE

		CDRECOVERY=`grep use-cdrecovery $MONDORESTORECFG | cut -d' ' -f2`
		NOT_BOOT=`grep non-bootable $MONDORESTORECFG | cut -d' ' -f2`
		USE_LILO=`grep use-lilo $MONDORESTORECFG | cut -d' ' -f2`
		EXCLUDE_DEVS=`grep excluded-devs $MONDORESTORECFG | cut -d' ' -f2`
		NFS_DEV=`grep nfs-dev $MONDORESTORECFG | cut -d' ' -f2`
		VALUE=`grep image-devs $MONDORESTORECFG | cut -d' ' -f2`
		if [ "$VALUE" = "(null)" ] || [ "$VALUE" = "" ] ; then
		    IMAGE_DEVS=""
		else
		    IMAGE_DEVS="`echo "$VALUE" | tr '|' ' '`"
		fi
		[ "$CDRECOVERY" = "yes" ] && [ "$PROMPT_MAKE_TAPE_IMAGE" = "yes" ] && Die "Sorry, you can't use --cd-recovery and --write-tapes at the same time"
		MONDO_ROOT=`echo $MINDI_CACHE | sed 's/\(.*\)\/.*/\1/'`
		if [ _"$MONDO_ROOT" != _"" ]; then
			mkdir -p $MONDO_ROOT
		else
			Die "MONDO_ROOT is undefined"
		fi
	else
		echo "Syntax: mindi (--custom ....)" >> /dev/stderr
		MindiExit -1
	fi
fi
#ScanCDandTape
[ "$CDRECOVERY" = "yes" ] || CDRECOVERY=no
if [ "$CDRECOVERY" = "yes" ] ; then
	iso_cfg_file=$MINDI_LIB/isolinux-H.cfg
	sys_cfg_file=$MINDI_LIB/syslinux-H.cfg
else
	iso_cfg_file=$MINDI_LIB/isolinux.cfg
	sys_cfg_file=$MINDI_LIB/syslinux.cfg
fi

[ -e "$iso_cfg_file" ] || Die "Cannot find $iso_cfg_file"
if [ _"$MONDO_SHARE" = _"" ]; then
	LogIt "Mindi Linux mini-distro generator v$MINDI_VERSION"
	LogIt "Latest Mindi is available from http://www.mondorescue.org"
	LogIt "BusyBox sources are available from http://www.busybox.net"
else
	echo "You are using Mindi-Linux v$MINDI_VERSION to make boot+data disks" >> /var/log/mondo-archive.log
fi
if [ -f $MINDI_LIB/rootfs/bin/busybox ]; then
	LogIt "Mindi-`$MINDI_LIB/rootfs/bin/busybox 2>&1 | head -1`"
else
	LogIt "Unable to find mindi-busybox, please install it"
	MindiExit -1
fi

# for Mandrake 9.2, which comes with two aes.o.gz modules :-/
insmod /lib/modules/`uname -r`/*/*/misc/aes.*o.gz >> $LOGFILE 2>> $LOGFILE
for i in loop cdrom ide-cd isofs linear raid0 raid1 raid5 ; do
	insmod $i >> $LOGFILE 2>> $LOGFILE
done

KERN_DISK_MADE=""

if [ "$NOT_BOOT" = "yes" ]; then
	LogIt "Just creating a small all.tar.gz for Mondo. Nothing else."
	mkdir -p $MINDI_TMP/small-all/tmp
	MakeMountlist $MINDI_TMP/small-all/tmp/mountlist.txt
	cp -f $MINDI_TMP/{filelist.full.gz,biggielist.txt} $MONDO_CACHE/mondo-restore.cfg $MINDI_CACHE/small-all/tmp 2>/dev/null || Die "Cannot copy small all.tar.gz"
	cd $MINDI_TMP/small-all
	tar -cv tmp | gzip -9 > $MINDI_CACHE/all.tar.gz || Die "Cannot make small all.tar.gz"
	sync
	LogIt "Done. Exiting."
	MindiExit 0
fi

if [ "$PROMPT_MAKE_USB_IMAGE" = "yes" ]; then
	LogIt "Including the generation of a Bootable USB device on $USBDEVICE"
fi
if [ "$kernelpath" = "" ] ; then
	if [ _"$MONDO_SHARE" != _"" ]; then
		Die "Please use -k <path> to specify kernel."
	fi
	if [ $INTERACTIVE == "yes" ]; then
		echo -en "Do you want to use your own kernel to build the boot disk ([y]/n) ?"
		read ch
		if [ "$ch" != "n" ] && [ "$ch" != "N" ] ; then
	    	USE_OWN_KERNEL="yes"
		fi
	fi
	if [ "$USE_OWN_KERNEL" = "yes" ]; then
		YOUR_KERNEL_SUCKS=""
		kernelpath=`TryToFindKernelPath`
		if [ "$kernelpath" = "" ] ; then
			echo -n "Please enter kernel path : "
			read kernelpath
		fi
	else
		YOUR_KERNEL_SUCKS="That's why you're using mine, dude. :-)"
	fi
fi
if [ _"$MONDO_SHARE" = _"" ] && [ $INTERACTIVE = "yes" ] && [ "$ARCH" != "ia64" ] ; then
	echo -en "Would you like to use LILO (instead of syslinux)\nfor your boot CD/floppies (y/[n]) ?"
	read ch
	if [ "$ch" = "y" ] || [ "$ch" = "Y" ] ; then
		USE_LILO=yes
	fi
fi
if [ "$YOUR_KERNEL_SUCKS" != "" ] || [ "$kernelpath" = "" ] || [ "$kernelpath" = "SUCKS" ] || [ "$kernelpath" = "FAILSAFE" ] ; then
	# If we have a distribution-specific script for finding a FAILSAFE kernel, use it.
	if [ -f "$MINDI_LIB/FindDistroFailsafe" ] && [ ! "$1" = "--makemountlist" ]; then
		source $MINDI_LIB/FindDistroFailsafe
		# Log kernel image
		LogIt "FAILSAFE kernel image to be used is: $FAILSAFE_KBIN ($FAILSAFE_KVER)"
		kernelpath="$FAILSAFE_KBIN"
		LogIt "I shall include a failsafe kernel, not your kernel, in the boot disks.\n"
		LogIt "The failsafe kernel is $kernelpath.\n"
		LogIt "However, you are still running your kernel. If Mindi fails to create your\n"
		LogIt "disks then it may still be a result of a problem with your kernel.\n"
		pwd=`pwd`
		cd $TMP_ROOT
		mkdir -p lib/modules
		cp -a "/lib/modules/$FAILSAFE_KVER" "lib/modules/$FAILSAFE_KVER" || Die "Cannot copy kernel modules."
		cd $pwd
	else
		kernelpath=$MINDI_LIB/vmlinuz
		LogIt "I shall include Mindi's failsafe kernel, not your kernel, in the boot disks."
		LogIt "However, you are still running your kernel. If Mindi fails to create your"
		LogIt "disks then it may still be a result of a problem with your kernel."
		pwd=`pwd`
		cd $MINDI_TMP
		bzip2 -dc $MINDI_LIB/lib.tar.bz2 | tar -x || Die "Cannot unzip lib.tar.bz2"
		cd $pwd
	fi
	YOUR_KERNEL_SUCKS="Your kernel sucks"
fi
echo -e "Mindi's temp dir = $MINDI_TMP \nMindi's output dir=$MINDI_CACHE" >> $LOGFILE
[ "$(($RANDOM%64))" -eq "0" ] && LogIt "Dude, I've looked inside your computer and it's really dusty..."

[ "$YOUR_KERNEL_SUCKS" ] && [ ! "$FAILSAFE_KVER" ] && Die "Please install mindi-kernel package. You need it.\nGo to http://www.mondorescue.org and download it, then install it."

rm -f $MINDI_CACHE/{*img,*gz,*iso}

PrepareDataDiskImages $MINDI_CACHE
noof_disks=$?
ramdisk_size=$(($size_of_all_tools+$EXTRA_SPACE))
rds=$(($ramdisk_size-$((ramdisk_size%4096))))
ramdisk_size=$rds

echo "Ramdisk will be $ramdisk_size KB" >> $LOGFILE
if [ "$USE_LILO" = "yes" ] ; then
	if [ "$ARCH" = "ia64" ] ; then
		PrepareBootDiskImage_LILO $MINDI_CACHE $IA64_BOOT_SIZE $kernelpath $ramdisk_size || Die "Failed to create ia64 floppy disk image."
	else
		if ! PrepareBootDiskImage_LILO $MINDI_CACHE 2880 $kernelpath $ramdisk_size ;  then
			LogIt "WARNING - failed to create 2.88MB floppy disk image."
			LogIt "Please reduce your kernel's size if you want to make a 2.88MB floppy disk."
			PrepareBootDiskImage_LILO $MINDI_CACHE 5760 $kernelpath $ramdisk_size || Die "Failed to create 2.88MB floppy disk image."
		fi
	fi
else
	if ! PrepareBootDiskImage_SYSLINUX $MINDI_CACHE 2880 $kernelpath $ramdisk_size ; then
		LogIt "WARNING - failed to create 2.88MB floppy disk image."
		LogIt "Please reduce your kernel's size if you want to make a 2.88MB floppy disk."
		PrepareBootDiskImage_SYSLINUX $MINDI_CACHE 5760 $kernelpath $ramdisk_size || Die "Failed to create 5.76MB floppy disk image."
	fi
fi

[ -e "$MINDI_LIB/memtest.img" ] && BOOT_MEDIA_MESSAGE="$BOOT_MEDIA_MESSAGE\n\
...Or type 'memtest' to test your PC's RAM thoroughly.\n"

if [ _"$MONDO_SHARE" = _"" ]; then
	ListImagesForUser $MINDI_CACHE
	if [ "$PROMPT_WRITE_BOOT_FLOPPIES" = "yes" ]; then
		OfferToCopyImagesToDisks $MINDI_CACHE $boot_dev $FDDEVICE
	fi
	OfferToMakeBootableISO $MINDI_CACHE
	if [ "$PROMPT_MAKE_USB_IMAGE" = "yes" ]; then
		OfferToMakeBootableUSB $MINDI_CACHE
	fi
	LogIt "Finished."
elif [ "$PROMPT_MAKE_TAPE_IMAGE" = "yes" ] ; then
	rm -f $MINDI_CACHE/{*img,*gz,*iso}
	OfferToMakeBootableISO $MINDI_CACHE
	if [ -e "$MINDI_CACHE/all.tar.gz" ] ; then
		cp -f $MINDI_CACHE/all.tar.gz $MINDI_TMP/ 2>> $LOGFILE
	else
		Die "Cannot find all.tar.gz, to be written to tape"
	fi
elif [ "$PROMPT_MAKE_USB_IMAGE" = "yes" ]; then
	OfferToMakeBootableUSB $MINDI_CACHE
else
	OfferToMakeBootableISO $MINDI_CACHE
fi
# cleanup
LogIt "$FRIENDLY_OUTSTRING"
for mtpt in $FLOPPY_WAS_MOUNTED ; do
	mount $mtpt
done
MindiExit 0
