#!/bin/bash

# $Id: mindi 2126 2009-01-14 20:49:38Z bruno $
#
#-----------------------------------------------------------------------------
# mindi - mini-Linux distro based on the user's filesystem & distribution
#
# Mindi can create a multi-image boot/root kit. The first image 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/uname -m`

ADDITIONAL_BOOT_PARAMS="devfs=nomount noresume selinux=0 barrier=off"

MINDI_REV=2156
MINDI_VER=2.0.5

MINDI_VERSION=${MINDI_VER}-r$MINDI_REV
MINDI_PREFIX=/usr
MINDI_CONF=/etc/mindi
MINDI_SBIN=${MINDI_PREFIX}/sbin
MINDI_LIB=/usr/lib/mindi

# Temporary directory for mindi
TMPDIR=/tmp

EXTRA_SPACE=49152		# increase if you run out of ramdisk space
BOOT_SIZE=16384			# size of the boot disk

PROMPT_MAKE_CD_IMAGE="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_USB_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

USE_OWN_KERNEL="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.

MY_FSTAB=/etc/fstab
TAPE_MODS="ht st osst ide-tape ide_tape"
SCSI_MODS="3w-xxxx 3w_xxxx 3w_9xxx 3w-9xxx 53c7,8xx a100u2w a320raid aacraid adpahci advansys aha152x aha1542 aha1740 aic79xx aic79xx_mod aic7xxx aic7xxx_mod aic7xxx_old AM53C974 atp870u BusLogic cciss cpqfc dmx3191d dpt_i2o dtc eata eata_dma eata_pio fdomain gdth g_NCR5380 i2o_block i2o_core ide-scsi ieee1394 imm in2000 initio ips iscsi iscsi_tcp libiscsi scsi_transport_iscsi isp megaraid megaraid_mm megaraid_mbox megaraid_sas mptbase mptscsih mptsas mptspi mptfc mptscsi mptctl NCR53c406a ncr53c8xx nsp32 pas16 pci2000 pci2220i pcmcia ppa psi240i qla1280 qla2200 qla2300 qla2400 qla2xxx qla2xxx_conf qlogicfas qlogicfc qlogicisp qlogicfas qlogicfas408 raw1394 scsi_mod scsi_transport_sas scsi_transport_spi scsi_transport_fc sd_mod crc_t10dif crc-t10dif seagate sg sim710 sr_mod sym53c416 sym53c8xx sym53c8xx_2 t128 tmscsim u14-34f ultrastor wd7000 vmhgfs intermodule scsi_dh scsi_tgt"

# ide-probe-mod
IDE_MODS="ide ide-floppy floppy ide-generic ide-detect ide-mod ide-disk ide_disk ide-cd ide_cd ide_cd_mod ide-cd_mod ide-cs ide-core ide_core edd paride ata_generic ata_piix libata dock via82cxxx generic nvidia ahci sata_nv cmd64x pata_amd pata_marvell pata_serverworks pata_sis amd74xx sis5513 jmicron sata_promise serverworks"
PCMCIA_MODS="pcmcia_core ds yenta_socket"
USB_MODS="usb-storage usb-ohci usb-uhci usbcore usb_storage input hid uhci_hcd ehci_hcd uhci-hcd ehci-hcd ohci-hcd ohci_hcd usbkbd usbhid keybdev mousedev libusual scsi_mod"
NET_MODS="sunrpc nfs nfs_acl lockd fscache loop mii 3c59x e100 bcm5700 bnx2 e1000 eepro100 ne2k-pci tg3 libphy pcnet32 8139cp 8139too 8390 forcedeth vmxnet vmnet exportfs"
CDROM_MODS="$TAPE_MODS $IDE_MODS $USB_MODS $PCMCIA_MODS $SCSI_MODS $NET_MODS af_packet cdrom isocd isofs inflate_fs nls_iso8859-1 nls_base nls_cp437 nls_utf8 sg sr_mod zlib_inflate iso9660"
# Those modules will only go on the backup media, not the boot media.
EXTRA_MODS="$CDROM_MODS vfat fat loop md-mod linear raid0 raid1 xor raid10 raid5 raid456 lvm-mod dm-mod dm_mod dm-snapshot dm_snapshot dm-zero dm_zero dm-mirror dm_mirror dm-multipath dm-round-robin dm-emc dm-hp-sw dm-rdac multipath jfs xfs xfs_support pagebuf reiserfs ext2 ext3 minix nfs nfs_acl nfsd lockd sunrpc jbd mbcache ext4 jbd2 crc16 fuse"
# Replace with that line for HP OCMP e.g.
#DENY_MODS="MPS_Driver_Mapper mps octtldrv tscttl streams kqemu fdomain"
DENY_MODS="kqemu"
# Force some modules to be included
FORCE_MODS=""

LOGFILE=/var/log/mindi.log
MINDI_CACHE=/var/cache/mindi
BOOT_MEDIA_MESSAGE="\
To format and restore all files automatically, type 'nuke' <enter>.\n\
To restore some/all files interactively, type 'interactive' <enter>.\n\
To compare the archives with your filesystem, type 'compare' <enter>.\n\
To boot to a command-line prompt (expert mode), type 'expert' <enter>.\n\
You may add one or more of the following parameters as well:-\n\n\
		donteject - mondorestore will not eject the CD; this is useful if, for\n\
		            instance, your PC's case has a concealed CD-ROM drive\n\
		noresize  - your mountlist will not be adjusted to use your unallocated\n\
		            hard disk space\n\
		textonly  - do not call any Newt library routines; this is unattractive\n\
		            but valuable if you find your Newt library has bugs in it\n\n\
e.g. Type 'nuke donteject textonly' if you have an unstable Newt library and \n\
a PC whose CD-ROM drive tray would be damaged if it unexpectedly ejected.\n\
"
FDISK=$MINDI_SBIN/parted2fdisk

# Using a config file allow to overwrite some values
MINDI_CONFIG="$MINDI_CONF/mindi.conf"
if [ -f $MINDI_CONFIG ]; then
	. $MINDI_CONFIG
fi
DEPLIST_FILE="$MINDI_CONF/deplist.txt"
ISO_CMD="/usr/bin/mkisofs"
ISO_OPT="-J -r -v -p Mindi -publisher http://www.mondorescue.org -A Mindi"

# Now we can create what we need
export 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"
}


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."
}


AddFileToCfgIfExists() {
	[ -e "$1" ] && echo -en "$2 `cat $1`\n" >> $3
}


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
	tar cf - $mappath 2>> $LOGFILE | (cd $bigdir ; tar xf -) || 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
}


CopyDependenciesToDirectory() {
	local outdir incoming fname counter d found
	outdir=$1
	mkdir -p $outdir
	incoming=`ReadLine`
	counter=0
	while [ "$incoming" != "" ] ; do
		# Non absolute file names should not arrive till here => skipped
		if [ `echo "$incoming" | cut -c1` != '/' ]; then
			LogIt "Unable to handle $incoming"
			incoming=`ReadLine`
			continue
		fi
		# no parent directory of incoming should be a link, copy is not possible in that case
		d=`dirname "$incoming"`
		found="false"
		while [ $d != "/" -a $found = "false" ]; do
			[ -h "$d" ] && found="true"
			d=`dirname "$d"`
		done
		if [ -d "$incoming" ] && [ ! -h "$incoming" ]; then
		    find $incoming/* -maxdepth 0 2> /dev/null | CopyDependenciesToDirectory $outdir
		elif [ -e "$incoming" ] && [ $found = "false" ]; then
			tar cf - $incoming 2>> $LOGFILE | (cd $outdir ; tar xf -) || Die "Cannot copy $incoming to $outdir - did you run out of disk space?"

			# Only uncompress modules if not using udevd
			if [ "`echo "$incoming" | grep "lib/modules/.*\..*o\.gz"`" != "" ] && [ "`ps auxww | grep -v grep | grep -qw udevd`" != "" ]; then
	    		gunzip -f $outdir/$incoming || LogIt "Cannot gunzip $outdir/$incoming"
			fi
			[ -x "$outdir" ] && StripExecutable $outdir "-$filename-"
			counter=$(($counter+1))
			if [ "$counter" -ge "5" ] ; then
				counter=0
		    	echo -en "."
			fi
		fi
		incoming=`ReadLine`
	done
}


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


# 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
	if [ _"$MONDO_SHARE" != _"" ] ; then
		echo "------------- mindi logfile included -------------------------" >> /var/log/mondoarchive.log
		cat $LOGFILE >> /var/log/mondoarchive.log
		echo "--------------------------------------------------------------">> /var/log/mondoarchive.log
	fi

	cd /
	sync&

	# Unmount what 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

	LogIt "Please e-mail a copy of $LOGFILE 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 -e 's/i[5-7]86//' -e 's/cmov//' -e 's/nosegneg//' | 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
	[ ! -e "$KEYDIR" ] && KEYDIR=/etc/condole
	[ ! -e "$KEYDIR" ] && KEYDIR=/etc/condole-setup
	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 "/etc/console/boottime.kmap.gz" > $bigdir/tmp/KEYMAP-LIVES-HERE
		KBDEPTH=0
		mkdir -p $bigdir/etc/console
		cp /etc/console/boottime.kmap.gz $bigdir/etc/console 2>> $LOGFILE
		echo -e "$DONE"
		return 0
	elif [ -e "/etc/console-setup/boottime.kmap.gz" ] ; then
		echo "Ubuntu-style config detected." >> $LOGFILE
		echo -en "Adding the following keyboard mapping tables: "
		mkdir -p $bigdir/tmp
		echo "/etc/console-setup/boottime.kmap.gz" > $bigdir/tmp/KEYMAP-LIVES-HERE
		KBDEPTH=0
		mkdir -p $bigdir/etc/console-setup
		cp /etc/console-setup/boottime.kmap.gz $bigdir/etc/console-setup 2>> $LOGFILE
		echo -e "$DONE"
		return 0
	elif [ -e "/etc/conf.d/keymaps" ] ; then
		echo "Gentoo-style config detected." >> $LOGFILE
		keyfile=/etc/conf.d/keymaps
	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
	[ ! "$locale" ] && locale=`grep -E '^KEYMAP=' "$keyfile" | tr -d '"' |cut -d'=' -f2`		# Gentoo
	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=$(find / -name "*/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 "$mappath" > $bigdir/tmp/KEYMAP-LIVES-HERE
	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/lib64/syslinux/isolinux.bin
	[ ! -e "$ISOLINUX" ] && ISOLINUX=/usr/share/syslinux/isolinux.bin
	[ ! -e "$ISOLINUX" ] && ISOLINUX=/usr/share/lib/syslinux/isolinux.bin
	[ ! -e "$ISOLINUX" ] && ISOLINUX=/usr/share/lib64/syslinux/isolinux.bin
	[ ! -e "$ISOLINUX" ] && ISOLINUX=`find / -name 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
}


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`
	echo "---------------------------------" >> $LOGFILE
	echo "List of dependencies:             " >> $LOGFILE
	echo "---------------------------------" >> $LOGFILE
	for fname in `cat $tempfile` ; do
		echo "$fname" | tee -a $LOGFILE >> $outfile.pre
		LocateDeps $fname | tee -a $LOGFILE >> $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
		cp -f $MINDI_TMP/BOOTLOADER.* $bigdir 2>> $LOGFILE || LogIt "\nMondo v1.2x defaults to LILO as the bootloader, BTW."
		if [ -e "$MINDI_TMP/NFS-DEV" ] ; then
			LogIt "\nIncorporating NFS-related settings"
			for r in NFS-* ISO-PREFIX ; do
				cp -f $MINDI_TMP/$r $bigdir/tmp 2>> $LOGFILE || Die "Cannot copy $r - did you run out of disk space?"
				echo "Copying $r to ramdisk" >> $LOGFILE
			done
		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="EXT2-fs: blocksize too small for device."
	local lcMagicInitfs="<6>checking if image is initramfs...|<6>Unpacking initramfs..."

	# local variables
	local lvOffset
	local lvScanRes
	local lvUseFilesystem

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

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

	# Kernel may be gzip compressed
	file $lvKernelImage 2>&1 | grep -q gzip
	if [ $? -eq 0 ]; then
		lvScanRes=`gzip -cd $lvKernelImage | strings | grep -E "$lcMagicCramfs|$lcMagicExt2fs|$lcMagicInitfs"`
	else
		# 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`
		echo "  GetInitrdFilesystemToUse(): gzip magic found at lvOffset $lvOffset.\n" >> $LOGFILE

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

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

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

	# 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 -Evx " *#.*| *none.*" $MY_FSTAB | $AWK '/^\/dev\/[imhs]d||^LABEL=\/|^UUID=/ && !/\/fdd|\/cdr|\/zip|\/floppy/ {print $1}'
	[ -e "/etc/raidtab" ] && $AWK '/^ *device/ {print $2}' /etc/raidtab
	if [ -e "/vmfs/volumes" ]; then
		# For VMWare ESX 3 get the device names of these volumes
		vdf -P | grep -E '/vmfs/volumes' | awk '{print $1}'
	fi
	return
}


ListImagesForUser() {
	local path fname
	path=$MINDI_CACHE
	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="$MODULES"
	# Remove unwanted modules from list
	for i in $DENY_MODS; do
		module_list=`echo ${module_list} | tr ' ' '\n' | grep -Ev "^${i}$" | tr '\n' ' '`
		EXTRA_MODS=`echo ${EXTRA_MODS} | tr ' ' '\n' | grep -Ev "^${i}$" | tr '\n' ' '`
	done
###
### 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
}

#
# Critical function which computes all dependencies (dyn. lib.) 
# for a list of binaries
#
LocateDeps() {
	local incoming fname deps
	incoming="$*"
	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 echo "$MODULES" | grep lvm &> /dev/null ; then
		    		echo "I think you are, so please take heed!" >> $LOGFILE
				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
		fi
	done
}


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

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

	link=`readlink $file`
	d=`dirname $file`
	fchar=`echo $link | cut -c1`
	# If mother dir is a link print it
	if [ -h "$d" ]; then
		echo "$d"
		d=`readlink $d`
	fi
	if [ "$fchar" != "/" ]; then
		# Relative or local link
		ReadAllLink "$d/$link" 
	else
		# Absolute path
		ReadAllLink $link 
	fi
}


LocateFile() {
	local i path fname_to_find location output resolved tmp stub cache_id loclist
	fname_to_find="$1"
	# It's an absolute path
	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
	# It's not an absolute path
	output=""
	for path in /etc /usr /usr/bin /usr/sbin /bin /usr/X11R6/bin /sbin /usr/local/bin /usr/local/sbin `find /usr/lib /lib /usr/local/lib /usr/X11R6/lib /usr/lib64 /lib64 /usr/local/lib64 /usr/X11R6/lib64 -type d -maxdepth 1 2> /dev/null` ; do
	#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
		[ -h "$path" ] && continue
		[ ! -e "$path/$fname_to_find" ] && continue
		output="$path/$fname_to_find $output"
		if [ -h "$path/$fname_to_find" ] ; then
			output="`ReadAllLink $path/$fname_to_find` $output"
		fi
	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
}


# Called by TurnTgzIntoRdz, to make /tmp/mondo-restore.cfg
MakeMondoConfigFile() {
	local outfile use_lzo use_comp use_star
	outfile=$1
	> $outfile
	[ "$TAPESIZE" ]		&& echo "media-size $TAPESIZE" >> $outfile
	[ "$TAPEDEV" ]	        && echo "media-dev $TAPEDEV" >> $outfile
	[ "$USBDEVICE" ]	        && echo "usb-dev $USBDEVICE" >> $outfile
	[ "$FILES_IN_FILELIST" ]	&& echo "files-in-filelist $FILES_IN_FILELIST" >> $outfile
	[ "$LAST_FILELIST_NUMBER" ]	&& echo "last-filelist-number $LAST_FILELIST_NUMBER" >> $outfile
	[ "$INTERNAL_TAPE_BLOCK_SIZE" ] && echo "internal-tape-block-size $INTERNAL_TAPE_BLOCK_SIZE" >> $outfile
	use_lzo=$USE_LZO; [ "$use_lzo" = "" ] && use_lzo="no"
	use_gzip=$USE_GZIP; [ "$use_gzip" = "" ] && use_gzip="no"
	use_comp=$USE_COMP; [ "$use_comp" = "" ] && use_comp="yes"
	use_star=$USE_STAR; [ "$use_star" = "" ] && use_star="no"
	echo "use-lzo $use_lzo" >> $outfile
	echo "use-gzip $use_gzip" >> $outfile
	echo "use-star $use_star" >> $outfile
	echo "use-comp $use_comp" >> $outfile
	echo "datestamp `date`" >> $outfile
	[ "$ESTIMATED_TOTAL_NOOF_SLICES" ] && echo "total-slices $ESTIMATED_TOTAL_NOOF_SLICES" >> $outfile
	AddFileToCfgIfExists $MINDI_TMP/NFS-CLIENT-IPADDR nfs-client-ipaddr $outfile
	AddFileToCfgIfExists $MINDI_TMP/NFS-CLIENT-NETMASK nfs-client-netmask $outfile
	AddFileToCfgIfExists $MINDI_TMP/NFS-CLIENT-BROADCAST nfs-client-broadcast $outfile
	AddFileToCfgIfExists $MINDI_TMP/NFS-CLIENT-DEFGW  nfs-client-defgw  $outfile
	AddFileToCfgIfExists $MINDI_TMP/NFS-SERVER-MOUNT  nfs-server-mount  $outfile
	AddFileToCfgIfExists $MINDI_TMP/NFS-SERVER-PATH   nfs-server-path   $outfile
	AddFileToCfgIfExists $MINDI_TMP/NFS-DEV           nfs-dev           $outfile
	AddFileToCfgIfExists $MINDI_TMP/NFS-SERVER-IPADDR nfs-server-ipaddr $outfile
	AddFileToCfgIfExists $MINDI_TMP/ISO-DEV           iso-dev           $outfile
	AddFileToCfgIfExists $MINDI_TMP/ISO-MNT           iso-mnt           $outfile
	AddFileToCfgIfExists $MINDI_TMP/ISO-PREFIX        iso-prefix        $outfile
	AddFileToCfgIfExists $MINDI_TMP/ISODIR            isodir            $outfile
	AddFileToCfgIfExists $MINDI_TMP/BOOTLOADER.DEVICE bootloader.device $outfile
	AddFileToCfgIfExists $MINDI_TMP/BOOTLOADER.NAME   bootloader.name   $outfile
	AddFileToCfgIfExists $MINDI_TMP/KEYMAP-LIVES-HERE keymap-lives-here $outfile
	AddFileToCfgIfExists $MINDI_TMP/TAPEDEV-HAS-DATA-DISKS tapedev-has-data-disks $outfile
	AddFileToCfgIfExists $MINDI_TMP/BACKUP-MEDIA-TYPE backup-media-type $outfile
	AddFileToCfgIfExists $MINDI_TMP/DIFFERENTIAL      differential      $outfile
	AddFileToCfgIfExists $MINDI_TMP/ACL      acl      $outfile
	AddFileToCfgIfExists $MINDI_TMP/XATTR      xattr      $outfile
	AddFileToCfgIfExists $MINDI_TMP/OBDR      obdr      $outfile
}


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 uname skip

	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
	all_partitions=""
	
	if [ $LVM != "false" ]; then
		echo -en "Analyzing LVM...\n"
		$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\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=""
		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

		# set default in case we dont't find it
		str_to_find_fmt_with=$current_partition

		# 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
			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
					skip=""
					uname="`uname -r`"
					[ "`echo $uname | grep "2.4.[0-9]"`" != "" ] && skip=16
					# 2.6.12 needs 16 (FC3)
					[ "`echo $uname | grep "2.6.[0-1]"`" != "" ] && skip=16
					# 2.6.19 and upper needs 1052
					[ "`echo $uname | grep "2.6.19"`" != "" ] && skip=1052
					[ "`echo $uname | grep "2.6.[2-9]"`" != "" ] && skip=1052
					if [ $skip = "" ]; then
						Die "Your kernel is too old. I don't know how to support labelled swap spaces with it"
					fi
					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=$skip 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
			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 UUID 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

			# 4th try, with dumpuuid (VMWare only ?) for swap
			if [ "x$actual_dev" = "x" -a -x "/sbin/dumpuuid" ]; then
				list_dev=`cat /proc/swaps | /bin/grep -E '^/' | $AWK '{ print $1 }' `
				for dev in $list_dev ; do
					dev_exists=`/sbin/dumpuuid $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),\nbut you lack the tool to support it.\nPlease replace labels with their correct devices in $MY_FSTAB or\ninstall findfs|blkid|vol_id or\nrelabel the partition with the correct UUID if it's a swap partition."
			fi
		else
			# Needs to handle the recent OpenSUSE fancy way of dealing with fstab :-(
			# they use symlinks in fstab unrelated to what is shown in mount !
			if [ _"$partition_mountpt" = _"" ]; then
				# set default in case we dont't find it
				for tmpp in `tr -s '\t' ' ' < $MY_FSTAB | /bin/grep -Ev "^#" | $AWK '{print $1}'`; do
						if [ _"`readlink -f $tmpp`" = _"$current_partition" ]; then
							str_to_find_fmt_with=$tmpp
							partition_mountpt=`tr -s '\t' ' ' < $MY_FSTAB | /bin/grep -w "$tmpp" | /bin/grep -vx " *#.*" | $AWK '{print $2}' | head -n1`
							break;
						fi
				done
			fi
		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
			# if it's not found, it may well be a real device such as a multipath one
			# /dev/mapper/mpath... Thus we revert the situation so that next test succeed
			if [ _"$current_lvolume" = _"" ]; then
				current_lvolume="$current_partition"
			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*' 2> /dev/null`; 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
		if [ "$redhat_label" ]; then
			label="$redhat_label"
		elif [ "$uuid" ]; then
			label="$uuid"
		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\n" $current_partition $partition_mountpt $partition_format $psz "$label"`
		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\n" $current_partition $partition_mountpt $partition_format $psz "$label" | tee -a $LOGFILE
				printf "%s %s %s %s %s %s\n" $current_partition $partition_mountpt $partition_format $partition_size "$label" >> $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\n" $current_partition $partition_mountpt $partition_format $psz "$label" | tee -a $LOGFILE
			printf "%s %s %s %s %s\n" $current_partition $partition_mountpt $partition_format $partition_size "$label" >> $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
}


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}
	cp -f $MINDI_CACHE/{*.gz,*.img} $MINDI_TMP/iso/images 2>> $LOGFILE || LogIt "OfferToMakeBootableISO: Cannot copy $MINDI_CACHE/*.gz to $MINDI_TMP/iso/images"
	echo "mindi_lib = $MINDI_LIB" >> $LOGFILE
	for i in memdisk memtest.bin memtest.img ; do
		j=$MINDI_LIB/$i
		k=$MINDI_TMP/iso
		if [ -e "$j" ] ; then
			LogIt "Copying $j to $k"
			cp -f $j $k 2>> $LOGFILE || Die "Failed to copy $j to $k"
			cp -f $j $MINDI_TMP 2>> $LOGFILE || 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
	MakeMessageFile > $MINDI_TMP/iso/message.txt
	cp $kernelpath $MINDI_TMP/iso/vmlinuz 2>> $LOGFILE || Die "Cannot copy vmlinuz ($kernelpath) to mindi tmp ($MINDI_TMP/iso/vmlinuz). Did you run out of disk space?"
	cp $MINDI_TMP/initrd.img $MINDI_TMP/iso/initrd.img 2>> $LOGFILE || Die "Cannot copy initrd.img ($MINDI_TMP/initrd.img) to $MINDI_TMP/iso/initrd.img. Did you run out of disk space?"
	if [ _"$MONDO_SHARE" != _"" ]; then 
		cp $kernelpath $MONDO_ROOT/vmlinuz 2>> $LOGFILE || Die "Cannot copy vmlinuz ($kernelpath) to mondo root ($MONDO_ROOT/vmlinuz). Did you run out of disk space?"
		cp $MINDI_TMP/initrd.img $MONDO_ROOT/initrd.img 2>> $LOGFILE || Die "Cannot copy initrd.img ($MINDI_TMP/initrd.img) to $MONDO_ROOT/initrd.img. Did you run out of disk space?"
	fi
	MakeBootConfFile isolinux > $MINDI_TMP/iso/isolinux.cfg
	if [ "$ARCH" != "ia64" ] ; then
		cp $ISOLINUX $MINDI_TMP/iso/isolinux.bin 2>> $LOGFILE || Die "Cannot copy isolinux.bin ($ISOLINUX) to $MINDI_TMP/iso - did you run out of disk space?"
	fi
	old_pwd=`pwd`
	cd $MINDI_TMP/iso
	if [ "$ARCH" != "ia64" ] ; then
		if [ _"$MONDO_SHARE" != _"" ]; then 
			cp -f $MINDI_TMP/iso/{isolinux.cfg,initrd.img,vmlinuz,isolinux.bin,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 $MINDI_TMP/iso 2>> $LOGFILE
		fi
		$ISO_CMD -U $ISO_OPT -V Mindi_Image -o $MINDI_CACHE/mindi.iso -b isolinux.bin -c boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table . > /dev/null 2> $MINDI_TMP/mkisofs.log
	else
		$ISO_CMD $ISO_OPT -V Mindi_Image -o $MINDI_CACHE/mindi.iso -b images/mindi-bootroot.$BOOT_SIZE.img -c images/boot.cat -no-emul-boot . > /dev/null 2> $MINDI_TMP/mkisofs.log
		rm -f images/mindi-bootroot.$BOOT_SIZE.img
	fi
	if [ "$?" -ne "0" ] ; then
		echo "----------- $ISO_CMD's errors --------------" >> $LOGFILE
		cat $MINDI_TMP/mkisofs.log >> $LOGFILE
		echo "$ISO_CMD 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" | tee -a $LOGFILE
	fi
	rm -f $MINDI_TMP/mkisofs.log
	cd $old_pwd
}


OfferToMakeBootableUSB() {
	local i
	if [ "$PROMPT_MAKE_USB_IMAGE" = "yes" ] && [ _"$MONDO_SHARE" = _"" ]; then
		echo -n "Shall I make a bootable USB image ? (y/[n]) "
		read i
		[ "$i" != "y" ] && [ "$i" != "Y" ] && return 0
		if [ "$USBDEVICE" = "" ]; then
			echo -en "Please enter the device name of your USB device (e.g. /dev/sda) : "
			read dev
			USBDEVICE=$dev
		fi
		echo "WARNING: This will erase all content on $USBDEVICE"
		echo -en "Are you sure you want to use $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>> $LOGFILE 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
		exit -1
	fi
	echo -en "."
	echo "Unmounting $USBDEVICE just in case" >> $LOGFILE
	umount $USBPART 2>> $LOGFILE 1>> $LOGFILE
	# If your key has no MBR it may cause an issue
	# Use dd if=mbr.bin of=$USBDEVICE or ms-sys -s $USBDEVICE
	echo "Preparing $USBDEVICE" >> $LOGFILE
	$FDISK $USBDEVICE 2>> $LOGFILE 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
	mkdosfs -F 32 $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
	cp -f $MINDI_CACHE/*.img $MINDI_CACHE/*.gz $MINDI_TMP/usb/images 2>> $LOGFILE || LogIt "OfferToMakeBootableUSB: Cannot copy $i to $MINDI_TMP/usb/images"
	echo -en "."
	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>> $LOGFILE || Die "Failed to copy $j to $k"
			cp -f $j $MINDI_TMP 2>> $LOGFILE || Die "Failed to copy $j to $MINDI_TMP"
		fi
	done
	echo -en "."
	MakeMessageFile > $MINDI_TMP/usb/message.txt
	echo -en "."
	cp $kernelpath $MINDI_TMP/usb/vmlinuz 2>> $LOGFILE || Die "Cannot copy vmlinuz ($kernelpath) to mindi tmp ($MINDI_TMP/usb/vmlinuz). Did you run out of disk space?"
	echo -en "."
	cp $MINDI_TMP/initrd.img $MINDI_TMP/usb/initrd.img 2>> $LOGFILE
	echo -en "."
	MakeBootConfFile syslinux > $MINDI_TMP/usb/syslinux.cfg
	echo -en "."
	umount $MINDI_TMP/usb
	if [ "$ARCH" != "ia64" ] ; then
		syslinux -s $USBPART 2>> $MINDI_TMP/syslinux.log
		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
	else
		echo "No USB boot support for ia64" | tee -a $LOGFILE
		MindiExit -1
	fi
}


MakeMessageFile() {
	iss="/dev/null"
	[ -e /etc/issue ] && iss="/etc/issue"
	[ -e /etc/issue.net ] && iss="/etc/issue.net"
	if [ "`grep -Fi "debian" $iss 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 $iss` `hostname`"% | sed s/KKKKK/"Kernel `uname  -r` on a `uname -m`"/ | sed s/TTTTT/"`LC_TIME=C date`"/ | sed s/%r/"`uname -r`"/ | sed s/%t/"`hostname`"/
	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" $iss | sed s~/~~ | head -n1 | tr -s ' ' ' '`"/ | sed s/KKKKK/"`grep -i "kernel" $iss | sed s~/~~ | head -n1 | tr -s ' ' ' '`"/ | sed s/TTTTT/"`LC_TIME=C date`"/ | sed s/' 'r' 'on' 'an' 'm/' '`uname -r`' 'on' 'an' '`uname -m`/ | sed s/%r/"`uname -r`"/ | sed s/%t/"`hostname`"/
	fi
	if [ _"$MONDO_SHARE" != _"" ]; then
		if [ "$CDRECOVERY" != "yes" ] ; then
			if [ -e "$MINDI_TMP/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"
		    	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"
		    	fi
			else
				echo -en "$BOOT_MEDIA_MESSAGE"
			fi
		else
			echo -en "\
To restore your disk to factory defaults, type 'RESTORE' <enter>.\n\
CAUTION: THIS WILL ERASE YOUR WHOLE DISK !!!\n"
		fi
	fi
	echo -en "\n\n\n"
}


MakeBootConfFile() {
	local options i ooo
	options=""
	# Type of boot file (elilo or syslinux/isolinux)
	type=$1
	if [ "$type" = "elilo" ]; then
		sep="="
	else
		sep=" "
	fi

	# Generic header for conf file
	if [ "$type" != "elilo" ] ; then
		echo -en "prompt 1\ndisplay message.txt\n"
	else
		echo -en "prompt\n"
	fi

	# Compute which default option to boot from
	if [ "$CDRECOVERY" = "yes" ] ; then
		echo -en "default${sep}RESTORE\n"
	# In case it's mondoarchive
	elif [ _"$MONDO_SHARE" != _"" ]; then
		if [ -e "$MINDI_TMP/NFS-DEV" ] ; then
			echo -en "default${sep}iso\n"
		else
			echo -en "default${sep}interactive\n"
		fi
	else
		echo -en "default${sep}expert\n"
	fi

	# Handle timeout
	if [ "$CDRECOVERY" != "yes" ] ; then
		echo -en "timeout${sep}300\n"
	else
		echo -en "timeout${sep}10000\n"
	fi
	echo -en "\n"

	# prepare which labels will be generated
	if [ "$CDRECOVERY" = "yes" ] ; then
		options="RESTORE expert"
	else
		if [ _"$MONDO_SHARE" != _"" ]; then
		    if [ -e "$MINDI_TMP/NFS-DEV" ] ; then
		        options="iso"
		    else
		        options="interactive expert compare iso nuke isonuke"
		    fi
		else
		    options="expert"
		fi
	fi

	# Generate rest of conf file
	for i in $options ; do
		ooo=$i
		[ "$ooo" = "RESTORE" ] && ooo="nuke"
		if [ "$type" = "elilo" ]; then
			outstr="image=/vmlinuz\n\tlabel=$i\n\tinitrd=/initrd.img\n\troot=/dev/ram0 append=\" rw ramdisk_size=$ramdisk_size $ooo $ADDITIONAL_BOOT_PARAMS \"\n"
		else
			ps="/"
			if [ "$type" = "syslinux" ]; then
				ps=""
			fi
			outstr="label $i\n\tkernel ${ps}vmlinuz\n\tappend initrd=${ps}initrd.img root=/dev/ram0 rw ramdisk_size=$ramdisk_size ${ooo} $ADDITIONAL_BOOT_PARAMS\n"
		fi
		echo -en "$outstr"
	done

	if [ -e "$MINDI_LIB/memtest.img" ] ; then
		if [ "$type" = "elilo" ]; then
			echo -en "image=/memtest.bin\n\tlabel=memtest\n"
			echo -en "image=/memdisk\n\tlabel=memdisk\nappend=\"initrd=memtest.img\"\n"
		else
			ps="/"
			if [ "$type" = "syslinux" ]; then
				ps=""
			fi
			echo -en "label memtest\n\tkernel ${ps}memtest.bin\n"
			echo -en "label memdisk\n\tkernel ${ps}memdisk\nappend initrd=${ps}memtest.img\n"
		fi
	fi
}


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

	retval=0
	[ ! -e "$kernelpath" ] && Die "PBDI - cannot find $kernelpath kernel"
	echo -en "Making "$BOOT_SIZE"KB boot disk..."
	TurnTgzIntoRdz $MINDI_LIB/rootfs $MINDI_TMP/initrd.img `du -sk $kernelpath | cut -f1` || Die "Could not turn rootfs into initrd.img; are you SURE your kernel supports loopfs?"
	echo -en "..."
	imagefile=$imagesdir/mindi-bootroot.$BOOT_SIZE.img
	mountpoint=$MINDI_TMP/mountpoint.$$
	mkdir -p $mountpoint
	dd if=/dev/zero of=$imagefile bs=1k count=$BOOT_SIZE &> /dev/null || Die "Cannot dd blank file"
	mkdosfs $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
	mkdir -p $mountpoint/etc
	liloconf=$mountpoint/elilo.conf

	MakeBootConfFile elilo > $liloconf

	# Copy it so that CD-ROM menu entry is satisfied
	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
	el=`find /boot/efi -name elilo.efi`
	cp $el $mountpoint
	cp $liloconf $mountpoint
	if [ $mountefi -eq 1 ]; then
		umount /boot/efi 2>&1 > /dev/null
	fi

	echo "Copying $MINDI_TMP/initrd.img to $mountpoint..." >> $LOGFILE
	cp -f $MINDI_TMP/initrd.img $mountpoint 2>> $LOGFILE
	if [ "$?" -ne "0" ] ; then
		LogIt "Failed to copy $MINDI_TMP/initrd.img 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 initrd.img in bootdisk (kernel / modules too big?)"
		retval=$(($retval+1))
	fi
	MakeMessageFile > $mountpoint/message.txt

	mkdir -p $mountpoint/tmp
	if [ -f "$MINDI_TMP/mondo-restore.cfg" ]; then
		cp -f $MINDI_TMP/mondo-restore.cfg $mountpoint/tmp
	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>> $LOGFILE
	if [ "$?" -ne "0" ] ; 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 your image.\n" >> $LOGFILE
		[ "$mountpoint" != "" ] && rm -f $mountpoint/vmlinuz
		cd $old_pwd
		umount $mountpoint || Die "Cannot unmount mountpoint ($mountpoint)"
		rmdir $mountpoint || LogIt "Cannot rmdir (PBDI)"
	#	losetup /dev/loop0 -d
		[ "$imagefile" != "" ] && rm -f $imagefile
		return 0
	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 image = $free_space KB" >> $LOGFILE
	echo "Max kernel size on $BOOT_SIZE KB image (est'd) = $max_kernel_size K" >> $LOGFILE
	# make it bootable
	[ "$mountpoint" != "" ] && rm -f $mountpoint/zero
	[ -e "$MINDI_LIB/memdisk" ] && cp -f $MINDI_LIB/memdisk $mountpoint 2>> $LOGFILE
	if [ "$KERN_DISK_MADE" ] ; then
		echo "Not running LILO. It's not that kind of disk." >> $LOGFILE
	fi

	cp `dirname $kernelpath`/*.efi $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\n"
		if [ "$KERN_DISK_MADE" ] ; then
			LogIt "$BOOT_SIZE KB boot disks were created OK\n"
		fi
	else
		echo -en "...failed\n"
		LogIt $BOOT_SIZE"KB boot disk was NOT created\n"
		[ "$imagefile" != "" ] && rm -f $imagefile
	fi
	[ "$retval" -ne "0" ] && LogIt "PrepareBootDiskImage() is returning nonzero"
	return $retval
}


PrepareBootDiskImage_ISOLINUX() {
	local imagesdir dev imagefile mountpoint fname i kernelpath cfg_file testpath options retval outstr old_pwd ooo max_kernel_size bootimage
	imagesdir=$MINDI_CACHE
	kernelpath=$1
	do_boot_root_thingy=""
	local retval old_pwd
	retval=0

	[ ! -e "$kernelpath" ] && Die "PBDI - cannot find $kernelpath kernel"
	echo -en "Making "$BOOT_SIZE"KB boot disk..."
	TurnTgzIntoRdz $MINDI_LIB/rootfs $MINDI_TMP/initrd.img `du -sk $kernelpath | cut -f1` || Die "Could not turn rootfs into initrd.img; are you SURE your kernel supports loopfs?"
	echo -en "..."
	imagefile=$MINDI_TMP/mindi-bootroot.$BOOT_SIZE.img
	mountpoint=$MINDI_TMP/mountpoint.$$
	mkdir -p $mountpoint
	dd if=/dev/zero of=$imagefile bs=1k count=$BOOT_SIZE &> /dev/null || Die "Cannot dd blank file"
	echo "Creating vfat filesystem on $imagefile" >> $LOGFILE
	mkfs.vfat $imagefile >> $LOGFILE 2>> $LOGFILE
	# syslinux should be run on a  local file (doen't work through NFS Cf: #297)
	syslinux $imagefile >> $LOGFILE 2>> $LOGFILE

	# Only move it now to its final destination abd use it now
	mv $imagefile $imagesdir
	imagefile=$imagesdir/mindi-bootroot.$BOOT_SIZE.img

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

	# copy Mindi's skeleton fs & lilo/syslinux/whatever stuff into it
	MakeMessageFile > $mountpoint/message.txt
	MakeBootConfFile isolinux > $mountpoint/syslinux.cfg
	echo "Copying $MINDI_TMP/initrd.img to $mountpoint/initrd.img..." >> $LOGFILE
	cp -f $MINDI_TMP/initrd.img $mountpoint/initrd.img 2>> $LOGFILE
	if [ "$?" -ne "0" ] ; then
		LogIt "Failed to copy $MINDI_TMP/initrd.img 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 initrd.img in bootdisk (kernel / modules too big?)"
		retval=$(($retval+1))
	fi

	mkdir -p $mountpoint/tmp
	if [ -f "$MINDI_TMP/mondo-restore.cfg" ]; then
		cp -f $MINDI_TMP/mondo-restore.cfg $mountpoint/tmp
	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
	if [ "$?" -ne "0" ] ; 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 your image.\n" >> $LOGFILE
		[ "$mountpoint" != "" ] && rm -f $mountpoint/vmlinuz
		cd $old_pwd
		umount $mountpoint || Die "Cannot unmount mountpoint ($mountpoint)"
		rmdir $mountpoint || LogIt "Cannot rmdir (PBDI)"

		[ "$imagefile" != "" ] && rm -f $imagefile
		return 0
	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 image = $free_space KB" >> $LOGFILE
	echo "Max kernel size on $BOOT_SIZE KB image (est'd) = $max_kernel_size K" >> $LOGFILE

	# make it bootable
	[ "$mountpoint" != "" ] && 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\n"
		if [ "$KERN_DISK_MADE" ] ; then
		    [ "$imagefile" != "" ] && rm -f $imagefile
		    LogIt "$BOOT_SIZE KB boot disks were created OK\n"
		fi
	else
		echo -en "...failed\n"
		LogIt $BOOT_SIZE"KB boot disk was NOT created\n"
		[ "$imagefile" != "" ] && rm -f $imagefile
	fi
	[ "$retval" -ne "0" ] && LogIt "PrepareBootDiskImage() is returning nonzero"
	return $retval
}


ParseModprobeForIncludes() {
local MODPROBE_CONF mpincfile includes include

MODPROBE_CONF=/etc/modprobe.conf
mpincfile=$1
touch $mpincfile
if [ -a $MODPROBE_CONF ]; then
	includes=$(awk '/^[ \t]*include[ \t]+/ {if(NF>=2){print $2}}' $MODPROBE_CONF|sort -u)
	if [ -n "$includes" ]; then
		for include in $includes
		do
			if [ -a "$include" ]; then
				echo $include >> $mpincfile
			fi
		done
	fi
fi
}


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

	imagesdir=$MINDI_CACHE
	rm -f $imagesdir/mindi.iso
	needlist=$MINDI_TMP/what-we-need.txt
	bigdir=$MINDI_TMP/bigdir
	mkdir -p $bigdir/usr/bin
	mkdir -p $bigdir/usr/sbin
	includefile=$MINDI_TMP/$$.includefile.txt

	lfiles="$DEPLIST_FILE"
	lines=`grep -vx " *#.*" $lfiles | grep -vx "" | wc -l`
	ParseModprobeForIncludes $includefile
	lines=$(($lines+`cat $includefile | wc -l`))
	cat $lfiles $includefile | GenerateGiantDependencyList $needlist $lines
	res=$?
	rm -f $includefile
	if [ "$YOUR_KERNEL_SUCKS" ]; then
		pwd=`pwd`
		cd $MINDI_TMP
		for i in `ListKernelModulePaths | HackPathsToFailsafe` ; do
			tar cf - ./$i 2>> $LOGFILE | (cd $bigdir ; tar xf -) || Die "PDDI can't copy $i->$bigdir"
		done
		for i in $EXTRA_MODS ; do
			j=`find lib/modules/$FAILSAFE_KVER -name $i.*o.gz 2> /dev/null`
			[ ! "$j" ] && echo "WARNING - cannot find failsafe module $i.o.gz" >> $LOGFILE
			for k in $j ; do
				tar cf - $k 2>> $LOGFILE | (cd $bigdir ; tar xf -)
				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 files present in dependency list\nbut absent from filesystem."
	fi
	FindAndAddUserKeyboardMappingFile
	mkdir -p $bigdir/tmp
	if [ _"$MONDO_SHARE" != _"" ]; then
		MakeMondoConfigFile $MINDI_TMP/mondo-restore.cfg
		cp -f $MINDI_TMP/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=`cat $MINDI_TMP/BOOTLOADER.DEVICE 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>> $LOGFILE || Die "Unable to create /dev/boot_device on ramdisk"
	fi

	old_pwd=`pwd`
	cd $bigdir

	# Get terminfo content
	ti="usr/share/terminfo/l"
	if [ -d /$ti ]; then
		mkdir -p $ti
		cp -Rdf /$ti/* $ti 2>> $LOGFILE || LogIt "WARNING - error occurred while copying terminfo"
	fi
	if [ -e "$MONDO_SHARE/restore-scripts" ]; then
		cp -Rdf $MONDO_SHARE/restore-scripts/* . 2>> $LOGFILE
		[ "$?" -ne "0" ] && [ _"$MONDO_SHARE" != _"" ] && Die "Cannot find/install $MONDO_SHARE/restore-scripts"
	fi
	[ -d "/lib/dev-state" ] && tar cf - /lib/dev-state 2>> $LOGFILE | tar xf -
	cd $old_pwd
	echo -e "$DONE"
	TOTAL_BIGDIR_SIZE=`du -sk $bigdir | cut -f1`
	MakeMountlist $MINDI_TMP/mountlist.txt
	mkdir -p $bigdir/tmp
	cp -f $MINDI_TMP/mountlist.txt $bigdir/tmp/mountlist.txt 2>> $LOGFILE || Die "Cannot copy mountlist.txt from $MINDI_TMP to data disk"
	if [ _"$MONDO_SHARE" != _"" ]; then
		cp -f $bigdir/tmp/mountlist.txt $MINDI_TMP/. 2>> $LOGFILE
	fi
	if [ $LVM != "false" ]; then
		$MINDI_LIB/analyze-my-lvm > $bigdir/tmp/i-want-my-lvm 
		if [ "$?" -ne "0" ]; then
			LVM="false"
			rm -f $bigdir/tmp/i-want-my-lvm
		fi
	fi
	cat $bigdir/tmp/mountlist.txt >> $LOGFILE
	echo -en "$FILES_IN_FILELIST" > $bigdir/FILES-IN-FILELIST 2>> $LOGFILE
	echo -en "$LAST_FILELIST_NUMBER" > $bigdir/LAST-FILELIST-NUMBER 2>> $LOGFILE
	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 $bigdir/tmp 2>> $LOGFILE
		done
	fi

	echo -en "Tarring and zipping the data content..."
	size_of_all_tools=`du -sk $bigdir | cut -f1`
	(cd $bigdir ; tar -b 4096 -cf - . 2>> $LOGFILE | gzip -9 > $imagesdir/all.tar.gz)
	du -sk $imagesdir/*gz >> $LOGFILE
	echo -e "$DONE"

	FRIENDLY_OUTSTRING="Boot and data disk images were created."
	rm -rf $bigdir
	rm -f $needlist
}


ProcessLDD() {
	local incoming f d nd bd bnd
	read incoming
	while [ "$incoming" != "" ]; do
		# We take the full path name of the dyn. lib. we want
		incoming=`echo "$incoming" | awk '{if (match($1,/\//)) {print $1} else {if (match($3,/\//)) print $3} fi}'`
		for f in $incoming ; do
			# echo modified file name if one of the parent dir is a link
			# by replacing the original dirname by the destination of the link
			d="`dirname $f`"
			found="false"
			while [ "$d" != "/" ]; do
				if [ -h "$d" ]; then
					nd=`readlink -f $d`
					bd=`basename $d`
					bnd=`basename $nd`
					f=`echo $f | sed "s~/$bd/~/$bnd/~"`
					echo $d
				fi
				d="`dirname $d`"
			done

			echo "$f"
			echo "`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"
}


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
}



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
}


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 -E 'lin|kern' | 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' ' '
}


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

	tgz_dir_fname=$1
	rdz_fname=$2
	kernelsize=$3
	maxsize=$(($BOOT_SIZE-$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 || Die "Unable to create an ext2 file system on $tempfile"
	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

	# AL04Oct08: Check whether /lib64 is a link and if so explicitly create one in rootfs
	if [ -h "/lib64" ]; then
		mkdir -p lib || LogIt "Unable to create lib in $mountpoint."
		ln -s lib lib64 || LogIt "/lib64 is a symbolic link, but I couldn't create it in $mountpoint."
	fi

	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
			tar cf - $s 2> /dev/null | tar xf -
		fi
	done

	[ -e "/dev/.devfsd" ] && echo "/dev/.devfsd found" > tmp/USE-DEVFS

	# Handle the case where busybox and mount are dynamically linked
	file $MINDI_LIB/rootfs/bin/busybox 2>&1 | grep -q "dynamically" 
	if [ $? -eq 0 ]; then
		# We want to use the real mount and all the supported variants (nfs, cifs, ...)
		rm -f bin/mount $MINDI_TMP/busy.lis
		mountlis=`grep mount $DEPLIST_FILE`
		for f in $MINDI_LIB/rootfs/bin/busybox $mountlis ; do
			if [ -f $f ]; then
				LocateDeps $f >> $MINDI_TMP/busy.lis
			fi
		done
		tar cf - $mountlis `sort -u $MINDI_TMP/busy.lis` 2>> $LOGFILE | tar xf -
		rm -f $MINDI_TMP/busy.lis
	fi

	# Copy of files mandatory for ld.so
	cp -rp /etc/ld.so.c* $mountpoint/etc

	mkdir -p $mountpoint/tmp
	# Management of udev (which includes modprobe in rules)
	ps auxww | grep -v grep | grep -qw udevd
	if [ $? -eq 0 ]; then
		echo "udev device manager found" > $mountpoint/tmp/USE-UDEV
		LogIt "udev device manager found"
		tar cf - /etc/udev 2>> $LOGFILE | tar xf -
		# This avoids NIC remapping if on another machine at restore time on Debian at least
		rm -f ./etc/udev/rules.d/z??_persistent-net.rules
		tar cf - /lib*/udev 2>> $LOGFILE | tar xf -
		if [ -x /sbin/udevd ]; then
			lis2=`grep -Ev '^#' $MINDI_CONF/udev.files` 
			lis=""
			# Get only the files which exist in that list
			# and potentially their symlink structure
			for i in $lis2; do
				if [ -h $i ]; then
					j=$i
					while [ -h $j ]; do
						lis="$lis $j"
						j=`readlink $j`
					done
					lis="$lis $j"
				elif [ -f $i ]; then
					lis="$lis $i"
				fi
			done
			# And their deps
			LocateDeps $lis > $MINDI_TMP/udev.lis
			for i in $lis; do
				if [ "`echo $i | cut -c1`" = "/" ]; then
					j=`echo $i | cut -c2-`
					[ "$j" != "" ] && rm -f $j
				fi
			done
			tar cf - $lis `sort -u $MINDI_TMP/udev.lis` 2>> $LOGFILE | tar xf -
			rm -f $MINDI_TMP/udev.lis
		else
			echo "udevd daemon not in standard place (/sbin)" 2>&1 | tee -a $LOGFILE
			echo "mindi will use static devices which may cause problems" 2>&1 | tee -a $LOGFILE
			rm -f $mountpoint/tmp/USE-UDEV
		fi
	fi

	# Management of potential HW info (Proliant only at the moment)
	rm -rf $MINDI_CACHE/bkphw
	mindi-bkphw $MINDI_CACHE $MINDI_CONF | tee -a $LOGFILE
	if [ -d $MINDI_CACHE/bkphw ]; then
		LogIt "Hardware Information found and saved ..."
		cp -rp $MINDI_CACHE/bkphw .
		if [ -f $MINDI_CACHE/tools.files ]; then
			lis=`grep -Ev '^#' $MINDI_CACHE/tools.files` 
			LocateDeps $lis > $MINDI_TMP/tools.lis
			tar cf - $lis `sort -u $MINDI_TMP/tools.lis` 2>> $LOGFILE | tar xf -
		fi
		if [ -f $MINDI_CACHE/mindi-rsthw ]; then
			mv -f $MINDI_CACHE/mindi-rsthw .
			chmod 755 ./mindi-rsthw
		fi
		rm -f $MINDI_TMP/tools.lis $MINDI_CACHE/tools.files
	fi

	for w in cdrom groovy-stuff ; do
		mkdir -p mnt/$w
	done

	tar cf - /dev/fd0*[1,2][4,7,8]* 2>> $LOGFILE | tar xf -

	cd $old_pwd
	echo -en "..."
	old_pwd=`pwd`
	if [ "$YOUR_KERNEL_SUCKS" ] ; then
		cd $MINDI_TMP
		needed_modules_path=lib/modules/$FAILSAFE_KVER
	else
		cd /
		if [ "${kernelname}" != "" ]
		then
			needed_modules_path=lib/modules/${kernelname}
		else
			needed_modules_path=lib/modules/`uname -r`
		fi
	fi

	needed_modules=""
	list_of_groovy_mods="$CDROM_MODS $FORCE_MODS"

	if [ -e "$MINDI_TMP/NFS-DEV" ] ; then
		# For PXE boot
		list_of_groovy_mods="$list_of_groovy_mods $NET_MODS"
	fi
	if [ "$PROMPT_MAKE_USB_IMAGE" = "yes" ] && [ "$USBDEVICE" != "" ]; then
		list_of_groovy_mods="$list_of_groovy_mods $EXTRA_MODS"
	fi
	for i in $DENY_MODS; do
		echo "Removing $i from the list of modules to load" >> $LOGFILE
		list_of_groovy_mods=`echo ${list_of_groovy_mods} | tr ' ' '\n' | grep -Ev "^${i}$" | tr '\n' ' '`
	done

	[ -e "$needed_modules_path" ] || LogIt "path $needed_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
		needed_modules="$needed_modules `FindSpecificModuleInPath $needed_modules_path $i`"
	done

	for i in $needed_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
		tar cf - $i 2>> $LOGFILE | (cd $mountpoint ; tar xf -) || LogIt "Unable to copy $i to $mountpoint"
		# Uncompress modules if not using udev and native modprobe
		if [ ! -f $mountpoint/tmp/USE-UDEV ]; then
			if [ "`echo "$i" | grep -F ".gz"`" ]; then
				echo "Uncompressing $i" >> $LOGFILE
				gunzip -f $mountpoint/$i
			fi
		fi
	done

	# Also copy modules.dep in case of udev so that normal modprobe works
	tar cf - /$needed_modules_path/modules.dep 2>> $LOGFILE | (cd $mountpoint ; tar xf -) || LogIt "Unable to copy modules.dep to $mountpoint"

	if [ ! -e "/sbin/devfsd" ] || [ "$kernelpath" = "$MINDI_LIB/vmlinuz" ] ; then
		echo "Deleting devfsd daemon from ramdisk" >> $LOGFILE
		[ ! -e "/sbin/devfsd" ] && echo "...because /sbin/devfsd not found" >> $LOGFILE
		[ "$kernelpath" = "$MINDI_LIB/vmlinuz" ] && echo "...because kernel is failsafe" >> $LOGFILE
		rm -f $mountpoint/sbin/devfsd
	fi
	cd $old_pwd
	[ "$TAPEDEV" ] && echo -en "$TAPEDEV" > $mountpoint/tmp/TAPEDEV-LIVES-HERE
	dd if=/dev/zero of=$mountpoint/zero &> /dev/null
	rm -f $mountpoint/zero
	if [ _"$MONDO_SHARE" != _"" ]; then
		MakeMondoConfigFile $mountpoint/tmp/mondo-restore.cfg
		cp -f $mountpoint/tmp/mondo-restore.cfg $MINDI_TMP 2>> $LOGFILE || Die "Cannot copy mondo-restore.cfg to ramdisk"
		cp -f $MINDI_TMP/mountlist.txt $mountpoint/tmp/ 2>> $LOGFILE || Die "Cannot copy mountlist to ramdisk"
		echo -en "$FILES_IN_FILELIST" > $mountpoint/tmp/FILES-IN-FILELIST
		echo -en "$LAST_FILELIST_NUMBER" > $mountpoint/tmp/LAST-FILELIST-NUMBER
		[ "$USE_LZO" = "yes" ] && echo -en "Pras 4 Pres 2004" >> $mountpoint/tmp/USING-LZO
		[ "$USE_GZIP" = "yes" ] && echo -en "YES" >> $mountpoint/tmp/USING-GZIP
		[ "$USE_COMP" = "yes" ] && echo -en "Compression, yep" >> $mountpoint/tmp/USING-COMP
		[ "$USE_STAR" = "yes" ] && echo -en "Using star. Hooray." >> $mountpoint/tmp/USING-STAR
	fi
	mkdir -p $mountpoint/proc
	echo "$BOOT_SIZE" > $mountpoint/tmp/$BOOT_SIZE.siz
	# Determine what filesystem to use for initrd image
	echo "Call GetInitrdFilesystemToUse() with parameter ${kernelpath} to get filesystem to use for initrd." >> $LOGFILE
	gvFileSystem=`GetInitrdFilesystemToUse ${kernelpath}`
	[ -z  gvFileSystem ] && Die "GetFilesystemToUse() failed. Terminating."
	case "$gvFileSystem" in
	"ext2fs")
		# say what will be used
		echo "Creating an ext2 initrd image..." >> $LOGFILE
		# kernel expects linuxrc in ext2 filesystem
		( cd $mountpoint && ln -sf 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 > ${rdz_fname}.tmp 2> /dev/null
		bs=`tune2fs -l ${rdz_fname}.tmp | grep -E '^Block size:' | cut -d: -f2 | sed 's/^ *//'`
		ADDITIONAL_BOOT_PARAMS="$ADDITIONAL_BOOT_PARAMS ramdisk_blocksize=$bs"
		gzip -c9 ${rdz_fname}.tmp > $rdz_fname
		rm -f ${rdz_fname}.tmp
		# log that we are done
		echo "...done." >> $LOGFILE
	;;
	"initramfs")
		# say what will be used
		echo "Creating a gzip'ed cpio (AKA initramfs) initrd image..." >> $LOGFILE
		# 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 -sf sbin/init init
		# create cpio image file and unmount loop filesystem
		find . -print | cpio -o -H newc | gzip -9 > $rdz_fname 2> /dev/null
		cd $old_pwd
		umount $mountpoint || Die "Cannot unmount $tempfile"
		# log that we are done
    	echo "...done." >> $LOGFILE
	;;
	*)
		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
}


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

# Now we can create what we need
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 | grep -Ew "^$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

[ -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_CONFIG ]; then
	echo "-----------------------------" >> $LOGFILE
	echo " Mindi configuration file    " >> $LOGFILE
	echo "-----------------------------" >> $LOGFILE
	grep -Ev '^#' $MINDI_CONFIG >> $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"

# 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 1> /dev/null 2> /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 2> /dev/null`
	fi
else
	FindIsolinuxBinary
fi
trap "Aborted" SIGTERM
DONE="\r\t\t\t\t\t\t\t\tDone.         "
kernelpath=""
MONDO_ROOT=/var/cache/mondo
mkdir -p $MONDO_ROOT

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 "mount result:" >> $LOGFILE
echo "-------------" >> $LOGFILE
mount >> $LOGFILE
echo "-------------" >> $LOGFILE
if [ -e /etc/raidtab ]; then
	echo "-------------" >> $LOGFILE
	echo "/etc/raidtab content:" >> $LOGFILE
	echo "-------------" >> $LOGFILE
	cat /etc/raidtab >> $LOGFILE
fi
echo "-------------" >> $LOGFILE
echo "cat /proc/cmdline:" >> $LOGFILE
echo "-------------" >> $LOGFILE
cat /proc/cmdline >> $LOGFILE
echo "-------------" >> $LOGFILE
echo "cat /proc/swaps:" >> $LOGFILE
echo "-------------" >> $LOGFILE
cat /proc/swaps >> $LOGFILE
echo "-------------" >> $LOGFILE
echo "cat /proc/partitions:" >> $LOGFILE
echo "-------------" >> $LOGFILE
cat /proc/partitions >> $LOGFILE
echo "-------------" >> $LOGFILE
echo "cat /proc/filesystems:" >> $LOGFILE
echo "-------------" >> $LOGFILE
cat /proc/filesystems >> $LOGFILE
echo "-------------" >> $LOGFILE
echo "lsmod result:" >> $LOGFILE
echo "-------------" >> $LOGFILE
lsmod >> $LOGFILE
MODULES="`cat /proc/modules | awk '{print $1}'`"
if [ -x /usr/sbin/esxcfg-module ]; then
	echo "-------------" >> $LOGFILE
	echo "VMWare ESX server detected - Enabling dedicated support" >> $LOGFILE
	echo "-------------" >> $LOGFILE
	echo "VMWare modules" >> $LOGFILE
	echo "-------------" >> $LOGFILE
	/usr/sbin/esxcfg-module -l >> $LOGFILE
	MODULES="$MODULES `/usr/sbin/esxcfg-module -l | awk '{print $1}'`"
fi
echo "FORCE_MODS:" >> $LOGFILE
echo "-------------" >> $LOGFILE
echo $FORCE_MODS >> $LOGFILE
echo "-------------" >> $LOGFILE
echo "DENY_MODS:" >> $LOGFILE
echo "-------------" >> $LOGFILE
echo $DENY_MODS >> $LOGFILE
echo "-------------" >> $LOGFILE
echo "df result:" >> $LOGFILE
echo "----------" >> $LOGFILE
df -T >> $LOGFILE
echo "-------------" >> $LOGFILE
echo "Liste of extra modules is:" >> $LOGFILE
echo "$EXTRA_MODS" >> $LOGFILE
echo "-------------" >> $LOGFILE

# Compute libata version
laver=`modinfo libata | grep -Ei '^Version:' | cut -d: -f2 | cut -d. -f1 | sed 's/  *//g' 2> /dev/null`
# If libata v2 is used then remove ide-generic as it will perturbate boot
if [ "`echo $MODULES | grep libata`" ]; then
	if [ "$laver" = "2" ]; then
		DENY_MODS="$DENY_MODS ide-generic"
		echo "ide-generic removed from module list as your system uses libata v2+" >> $LOGFILE
		echo "-------------" >> $LOGFILE
	fi
fi

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

if [ "$#" -ne "0" ] ; then
	if [ "$1" = "--findkernel" ] ; then
		res=`TryToFindKernelPath`
		# Avoids logfile content for mondo
		export MONDO_SHARE=""
		if [ "$res" = "" ] ; then
		    MindiExit -1
		else
		    echo "$res"
		    MindiExit 0
		fi
	elif [ "$1" = "--locatedeps" ] ; then
		[ ! "$2" ] && Die "Please specify the binary to look at"
		LocateDeps $2
		# Avoids logfile content for mondo
		export MONDO_SHARE=""
		MindiExit $?
	elif [ "$1" = "--readalllink" ] ; then
		[ ! "$2" ] && Die "Please specify the binary to look at"
		ReadAllLink $2
		# Avoids logfile content for mondo
		export MONDO_SHARE=""
		MindiExit $?
	elif [ "$1" = "--makemountlist" ] ; then
		[ ! "$2" ] && Die "Please specify the output file"
		MakeMountlist $2
		# Avoids logfile content for mondo
		export MONDO_SHARE=""
		MindiExit $?
	elif [ "$1" = "-V" ] || [ "$1" = "-v" ] || [ "$1" = "--version" ] || [ "$1" = "-version" ] ; then
		echo "Mindi v$MINDI_VERSION"
		# Avoids logfile content for mondo
		export MONDO_SHARE=""
		MindiExit 0
	elif [ "$#" -ge "9" ] && [ "$1" = "--custom" ] ; then
		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>> $LOGFILE
		rmdir $MINDI_TMP
		export MINDI_TMP=$MONDO_TMP
		mkdir -p $MINDI_TMP
		# This is the scratch dir in mondo - subdir images
		MINDI_CACHE=$3
		if [ _"$MINDI_CACHE" != _"" ]; then
			mkdir -p $MINDI_CACHE
		fi
		kernelpath=$4; [ "$kernelpath" = "(null)" ] && kernelpath=""
###
### Sq-Modification...
### Attempt to locate kernel specific module path
### if module path is found then use it other wise use uname -r to set it...
###
		kernelname=`echo $kernelpath | cut -d'-' -f2-`
		LogIt "kernelname = $kernelname"
		LogIt "kernelpath = $kernelpath"
		if [ ! -d "/lib/modules/$kernelname" ] && [ "$kernelpath" != "FAILSAFE" ]
		then
		   LogIt "Module path for ${kernelpath} not found..."
		   LogIt "using running kernel\'s modules."
		   kernelname=`uname -r`
		else
		   LogIt "Using modules for kernel: ${kernelname}"
		fi
###
### end of Sq-Modification
###
		TAPEDEV=$5
		TAPESIZE=$6
		FILES_IN_FILELIST=$7
		USE_LZO=$8
		CDRECOVERY=$9
		if [ "${10}" = "(null)" ] || [ "${10}" = "" ] ; then
		    IMAGE_DEVS=""
		else
		    IMAGE_DEVS="`echo "${10}" | tr '|' ' '`"
		fi
		if [ "${11}" ] ; then
			LILO_OPTIONS=""
	#	    LogIt "LILO will use conservative settings, to be compatible with older BIOSes."
		fi
		LAST_FILELIST_NUMBER=${12}
		ESTIMATED_TOTAL_NOOF_SLICES=${13}
		EXCLUDE_DEVS="${14}"
		USE_COMP="${15}"
		USE_LILO="${16}"
		USE_STAR="${17}"
		INTERNAL_TAPE_BLOCK_SIZE="${18}"
		DIFFERENTIAL="${19}"
		USE_GZIP="${20}"
		NOT_BOOT="${21}"
		[ "$USE_COMP" = "" ] && USE_COMP=yes
		[ "$USE_GZIP" = "" ] && USE_GZIP=no
		[ "$NOT_BOOT" = "" ] && NOT_BOOT=no
		[ "$TAPEDEV" ] && LogIt "This is a tape-based backup. Fine."
		[ "$kernelpath" = "" ] && kernelpath=`TryToFindKernelPath`
		kernelname=`echo $kernelpath | cut -d'-' -f2-`
		if [ ! -d "/lib/modules/$kernelname" ] && [ "$kernelpath" != "FAILSAFE" ]
		then
		   LogIt "Module path for ${kernelpath} not found..."
		   LogIt "using running kernel\'s modules."
		   kernelname=`uname -r`
		else
		   LogIt "Using modules for kernel: ${kernelname}"
		fi
		# MONDO_ROOT is the real scratchdir
		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
[ "$CDRECOVERY" = "yes" ] || CDRECOVERY=no

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"
	LogIt "------------------------------------------------------------------------------"
else
	echo "You are using Mindi-Linux v$MINDI_VERSION to make boot+data disks" >> $LOGFILE
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=""

echo "DIFFERENTIAL = $DIFFERENTIAL" >> $LOGFILE
echo "INTERNAL TAPE BLOCK SIZE = $INTERNAL_TAPE_BLOCK_SIZE" >> $LOGFILE
echo "NOT_BOOT = '$NOT_BOOT'" >> $LOGFILE
if [ "$NOT_BOOT" != "" ] && [ "$NOT_BOOT" != "0" ] && [ "$NOT_BOOT" != "no" ] ; then
	LogIt "Just creating mondo-restore.cfg and a small all.tar.gz for Mondo. Nothing else."
	MakeMondoConfigFile $MINDI_TMP/mondo-restore.cfg
	MakeMountlist $MINDI_TMP/mountlist.txt
	mkdir -p $MINDI_TMP/small-all/tmp
	cd $MINDI_TMP/small-all
	cp -f $MINDI_TMP/{mountlist.txt,mondo-restore.cfg,filelist.full.gz,biggielist.txt} tmp 2>> $LOGFILE || Die "Cannot copy small all.tar.gz"
	tar -cv ./tmp | gzip -9 > $MINDI_TMP/all.tar.gz || Die "Cannot make small all.tar.gz"
	sleep 2
	LogIt "Done. Exiting."
	MindiExit 0
fi

if [ "$PROMPT_MAKE_USB_IMAGE" = "yes" ] && [ "$USBDEVICE" != "" ]; then
	LogIt "Including the generation of a Bootable USB device on $USBDEVICE"
fi

if [ "$kernelpath" = "" ] ; then
	[ _"$MONDO_SHARE" != _"" ] && Die "Please use -k <path> to specify kernel."
	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"
	else
		USE_OWN_KERNEL="no"
	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 [ "$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 $MINDI_TMP
		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."

PrepareDataDiskImages

ramdisk_size=$(($size_of_all_tools+$EXTRA_SPACE))
rds=$(($ramdisk_size-$((ramdisk_size%4096))))
export ramdisk_size=$rds

echo "Ramdisk will be $ramdisk_size KB" >> $LOGFILE
if [ "$ARCH" = "ia64" ] ; then
	PrepareBootDiskImage_LILO $kernelpath || Die "Failed to create ia64 image disk image."
else
	PrepareBootDiskImage_ISOLINUX $kernelpath || Die "Failed to create $ramdisk_size MB disk image."
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
	OfferToMakeBootableISO
	if [ "$PROMPT_MAKE_USB_IMAGE" = "yes" ]; then
		OfferToMakeBootableUSB
	fi
	LogIt "Finished."
elif [ "$TAPEDEV" ] ; then
	if [ "$ARCH" != "ia64" ] ; then
		# We need to keep the img file as boot file for ia64 platform
		rm -f $MINDI_CACHE/{*img,*iso}
	else
		rm -f $MINDI_CACHE/*iso
	fi
	if [ "$PROMPT_MAKE_USB_IMAGE" = "yes" ] && [ "$USBDEVICE" != "" ]; then
		OfferToMakeBootableUSB
	fi
	OfferToMakeBootableISO
	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" ] && [ "$USBDEVICE" != "" ]; then
	OfferToMakeBootableUSB
else
	OfferToMakeBootableISO
fi
# cleanup
LogIt "$FRIENDLY_OUTSTRING"
for mtpt in $FLOPPY_WAS_MOUNTED ; do
	mount $mtpt
done
MindiExit 0
