#!/bin/bash

# $Id: mindi 2569 2010-02-02 09:40:28Z 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`
KERVERRUN=`/bin/uname -r`
# By default we use the running kernel as a reference
KERVER=$KERVERRUN

# In case of problem with udev you can try to add udevdebug
MINDI_ADDITIONAL_BOOT_PARAMS="devfs=nomount noresume selinux=0 barrier=off udevtimeout=10"

MINDI_REV=PBREV
MINDI_VER=PBVER

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

# Temporary directory for mindi
TMPDIR=/tmp

EXTRA_SPACE=50000		# increase if you run out of ramdisk space
BOOT_SIZE=24576			# 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 emcpdm emcpgpx emcpmpx emcp dc395x diskdumplib scsi_dump_register"

# 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 ide-gd_mod 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 sata_via 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 ff-memless ums_cypress"
NET_MODS="auth_rpcgss sunrpc nfs nfs_acl lockd fscache loop mii 3c59x e100 bcm5700 bnx2 bnx2x e1000 e1000e igb eepro100 ne2k-pci tg3 libphy pcnet32 8139cp 8139too 8390 forcedeth vmxnet vmxnet3 vmnet exportfs fuse libcrc32c crc32c"
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"
# 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
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.conf"
DEPLIST_FILE_MIN="$MINDI_CONF/deplist-minimal.conf"
DEPLIST_DIR="$MINDI_CONF/deplist.d"

ISO_CMD="/usr/bin/mkisofs"
ISO_OPT="-J -r -v -p Mindi -publisher http://www.mondorescue.org -A Mindi"

# Mandriva system e.g. use cdrkit, which uses genisoimage instead of mkisofs.
# However, they use exactly the same command line parameters, so just
# use genisoimage if it's available.
if [ ! -x $ISO_CMD ]; then
	ISO_CMD=/usr/bin/genisoimage
fi

# Now we can create what we need
MINDI_TMP=`mktemp -d $TMPDIR/mindi.XXXXXXXXXX`
if [ $? -ne 0 ]; then
	df $TMPDIR
	Die "Unable to create a temporary directory ! Check space on $TMPDIR"
fi
if [ _"$MINDI_TMP" = _"" ]; then
	Die "MINDI_TMP is empty, aborting"
fi
if [ _"$MINDI_TMP" = _"/" ]; then
	Die "MINDI_TMP is /, aborting"
fi
export MINDI_TMP

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


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
		LogFile "$mappath already added" 
		return
	elif [ -d "$bigdir/$mappath" ] ; then
		echo "Cannot add $mappath: it's a directory. Sorry."
		return
	fi
	LogFile "Added kbd map $mappath" 
	if [ ! -e "$mappath" ] ; then
			mappath=`grep "i[3-8]86" $MINDI_TMP/keymaps.find | grep "$locale[^r][^/]" | grep -vx " *#.*"`
		if [ ! -e "$mappath" ] ; then
		    LogAll "Cannot add $mappath: kbd map file not found"
		    return
		fi
	fi

	mkdir -p $bigdir/etc
	tar cf - -C / $mappath 2>> $MINDI_TMP/$$.log | (cd $bigdir ; tar xf -) || LogAll "AKMF -- Could not copy $mappath to $bigdir" $MINDI_TMP/$$.log
	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
	noof_lines=$2
	mkdir -p $outdir
	incoming=`ReadLine`
	progress=0
	while [ "$incoming" != "" ] ; do
		# Non absolute file names should not arrive till here => skipped
		if [ `echo "$incoming" | cut -c1` != '/' ]; then
			LogAll "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 0
		elif [ -e "$incoming" ] && [ $found = "false" ]; then
			tar cf - -C / $incoming 2>> $MINDI_TMP/$$.log | (cd $outdir ; tar xf -) || Die "Cannot copy $incoming to $outdir - did you run out of disk space?" $MINDI_TMP/$$.log

			# 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 || LogAll "Cannot gunzip $outdir/$incoming"
			fi
			[ -x "$outdir" ] && StripExecutable $outdir "-$filename-"
			progress=$(($progress+1))
			LogProgress $progress $noof_lines
		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

	LogFile "Mindi $MINDI_VERSION is exiting" 
	LogFile "End date : `date`" 
	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 $MINDI_TMP | 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
		LogAll "FATAL ERROR"
	else
		LogAll "FATAL ERROR. $1"
	fi
	if [ _"$2" != _"" ]; then
		grep -Ev "tar: Removing \`/\'" "$2" >> $LOGFILE
	fi
	rm -f "$2"

	LogAll "Please e-mail a copy of $LOGFILE to the mailing list."
	LogAll "See http://www.mondorescue.org for more information."
	LogAll "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 progress
	filelist=$1
	outdir=$2

	progress=0
	list_of_optimized_libraries=`grep "lib/i[5-7]86/" $filelist`
	if [ "$list_of_optimized_libraries" = "" ] ; then
		return 0
	else
		noof_lines=`echo $list_of_optimized_libraries | tr ' ' '\n' | wc -l`
	fi
	echo -en "Dropping i686-optimized libraries if appropriate"
	for optimized_lib_name in $list_of_optimized_libraries ; do
		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
		LogFile "Adding $vanilla_lib_name to filelist" 
		mkdir -p $outdir$optimized_lib_name > /dev/null 2> /dev/null
		rmdir $outdir$optimized_lib_name > /dev/null 2> /dev/null

		# This may return multiple files
		for resolved in `ReadAllLink $vanilla_lib_name`; do
			LogFile "Adding as deps $resolved to filelist" 
			vanilla_resolved_name=`echo "$resolved" | sed -e 's/i[5-7]86//' -e 's/cmov//' -e 's/nosegneg//' | tr -s '/' '/'`
			mkdir -p $outdir$resolved> /dev/null 2> /dev/null
			rmdir $outdir$resolved > /dev/null 2> /dev/null
			ln -sf $vanilla_resolved_name $outdir$resolved
			LogFile "Excluding deps $resolved" 
			grep -Fvx "$resolved" "$filelist" > $filelist.tmp
			LogFile "Replacing it with $vanilla_resolved_name" 
			echo "$vanilla_resolved_name" >> $filelist.tmp
			mv -f $filelist.tmp $filelist
		done
		progress=$(($progress+1))
		LogProgress $progress $noof_lines
	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
	LogFile "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
		LogAll "Keyboard mapping directory not found. I shall use default map at boot-time."
		return 0
	fi
	LogFile "Adding the following keyboard mapping tables: "
	if [ -e "/etc/sysconfig/keyboard" ] ; then
		LogFile "Red Hat-style config detected." 
		keyfile=/etc/sysconfig/keyboard
	elif [ -e "/etc/rc.d/rc.keymap" ] ; then
 		LogFile "Slackware-style config detected." 
 		keyfile=/etc/rc.d/rc.keymap
	elif [ -e "/etc/rc.config" ] ; then
		LogFile "Debian-style config detected." 
		keyfile=/etc/rc.config
	elif [ -e "/etc/console/boottime.kmap.gz" ] ; then
		LogFile "Debian-style config detected." 
		mkdir -p $bigdir/tmp
		echo "/etc/console/boottime.kmap.gz" > $MINDI_CACHE/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
		LogFile "Ubuntu-style config detected." 
		mkdir -p $bigdir/tmp
		echo "/etc/console-setup/boottime.kmap.gz" > $MINDI_CACHE/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
		LogFile "Gentoo-style config detected." 
		keyfile=/etc/conf.d/keymaps
	else
		LogAll "Searching for rc.config ..."
		keyfile=`find /etc -name rc.config | head -n1`
		if [ "$keyfile" = "" ] || [ ! -e "$keyfile" ] ; then
			LogAll "Unknown config detected. Default keyboard map will be used."
			return
		else
			LogFile "Found $keyfile" 
		fi
	fi
	if [ ! -e "$KEYDIR/keymaps" ] ; then
		LogAll "Keyboard mapping directory not found. Default keyboard map will be used."
		return
	fi
	LogFile "keyfile=$keyfile" 
	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
	LogFile "locale=$locale" 
	#
	# 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 " " >> $LOGFILE
	if [ $? -eq 0 ]; then
		LogAll "WARNING: Multiple keymaps found: $mp" 
		LogFile "The following one will be used" 
	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
	LogFile "mappath = $mappath" 
	if [ ! -e "$mappath" ] || [ -d "$mappath" ] ; then
		LogAll "Keyboard mapping file not found. Default keyboard map will be used."
		return
	fi
	mkdir -p $bigdir/tmp
	echo "$mappath" > $MINDI_CACHE/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'"
	LogFile "Found isolinux.bin at $ISOLINUX" 
}


FindSpecificModuleInPath() {
	local modpaths line

	if [ ! -e "$1" ] ; then
		LogAll "WARNING - cannot search specific path '$1'"
		return 1
	fi
	# Find all files and links (required for some VMWare VMs)
	modpaths=`find $1 -name $2.*o -type f -o -type l`
	[ "$modpaths" = "" ] && modpaths=`find $1 -name $2.o.gz -type f -o -type l`
	[ "$modpaths" = "" ] && modpaths=`find $1 -name $2.ko.gz -type f -o -type l`
	[ "$modpaths" = "" ] && modpaths=`find $1 -name $2 -type f -o -type l`
	echo "$modpaths"
}


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" ] && LogAll "$incoming not found"
		res=$(($res+$r))
#		LogFile "'$incoming' generates filelist '$filelist'"
		for fname in $filelist ; do
	    	[ "$fname" != "" ] && echo "$fname" >> $tempfile
		done
		progress=$(($progress+1))
		LogProgress $progress $noof_lines
		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))
			LogProgress $progress $noof_lines
			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`
	LogFile "---------------------------------" 
	LogFile "List of dependencies:             " 
	LogFile "---------------------------------" 
	for fname in `cat $tempfile` ; do
		echo "$fname" | tee -a $LOGFILE >> $outfile.pre
		LocateDeps $fname | tee -a $LOGFILE >> $outfile.pre
		progress=$(($progress+1))
		LogProgress $progress $noof_lines
	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
			LogAll "\nIncorporating post-nuke tarball"
			old_pwd=`pwd`
			cd $bigdir
			tar -zxf $MINDI_TMP/post-nuke.tgz 2>> $MINDI_TMP/$$.log || LogAll "Error occurred when untarring post-nuke tarball" $MINDI_TMP/$$.log
			cd $old_pwd
		fi
		cp -f $MINDI_TMP/BOOTLOADER.* $bigdir 2>> $LOGFILE || LogAll "\nMondo v1.2x defaults to LILO as the bootloader, BTW."
		if [ -e "$MINDI_TMP/NETFS-DEV" ] ; then
			LogAll "\nIncorporating NFS-related settings"
			for r in NETFS-* ; do
				cp -f $MINDI_TMP/$r $bigdir/tmp 2>> $LOGFILE || Die "Cannot copy $r - did you run out of disk space?"
				LogFile "Copying $r to ramdisk" 
			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
# Could be ext2 FS (old mode) or initramfs (new mode)
#
# 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 lcMagicExt3fs="<3>EXT3-fs: blocksize too small for journal device."
	local lcMagicInitfs="<6>checking if image is initramfs...|<6>Unpacking initramfs...|<6>Trying to unpack rootfs image as
initramfs"

	# local variables
	local lvOffset
	local lvScanRes
	local lvUseFilesystem

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

	# 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|$lcMagicExt3fs|$lcMagicInitfs"`

		# determine which filesystem to use for initrd image: ext2|3fs, gzip'ed cpio (initramfs) or cramfs
		if [ `echo $lvScanRes | grep -Ec "$lcMagicExt2fs"` -eq 1 ]; then
			lvUseFilesystem="ext2fs"
		elif [ `echo $lvScanRes | grep -Ec "$lcMagicExt3fs"` -eq 1 ]; then
			lvUseFilesystem="ext3fs"
		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

	else
		# In that case, we are after 2.6.30 and use the supported initramfs 
		lvUseFilesystem="initramfs"
	fi
	# say what we are using
	LogFile "  GetInitrdFilesystemToUse(): Filesytem to use for initial ramdisk is $lvUseFilesystem." 

	# 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
}


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
	outfile=$1
	echo -en "Analyzing modules requirements"
	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
###
	if [ "${kernelname}" != "" ]
	then
		kern=${kernelname}
	else
		kern="$KERVERRUN"
	fi
	export KERVER=$kern
###
### Sq-Mod End
###
	noof_lines=0
	# Get rid of duplicates, so that if a live kernel module also appears
	# in $EXTRA_MODS that it won't get reported as "live module file not found" twice.
	for module in `echo $module_list $EXTRA_MODS | tr ' ' '\n' | sort -u` ; do
		noof_lines=$(($noof_lines+1))
	done
	progress=0
	for module in `echo $module_list $EXTRA_MODS | tr ' ' '\n' | sort -u` ; do
		r=`find /lib/modules/$kern -type f | grep "/${module}\..*o" | tail -n1`
		if [ -z "$r" ]; then
			if [ "`echo "$MODULES" | grep -w $module`" ]; then
				r="[live module file not found]"
			else
				r="[extra module file not found]"
			fi
		fi
		LogFile "module $module --> $r" 
		[ -f "$r" ] && echo "$r" >> $outfile
		[ -f "$oss" ] && find $oss | grep -F $module >> $outfile
		progress=$(($progress+1))
		LogProgress $progress $noof_lines
	done
	find /lib/modules/$kern/modules.* -type f 2> /dev/null >> $outfile
	[ -f "$oss" ] && find $oss.* 2> /dev/null >> $outfile
}

#
# 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
		    LogFile "WARNING - $fname does not exist; cannot be LDD'd." 
			if echo $fname | grep lvm &> /dev/null ; then
				LogFile "This warning only affects you if you are using LVM." 
				if echo "$MODULES" | grep lvm &> /dev/null ; then
		    		LogFile "I think you are, so please take heed!" 
				else
		    		LogFile "I don't think you are, so don't worry about it." 
				fi
			fi
		elif [ -h "$fname" ] && [ -x "$fname" ] ; then
			LogFile "$fname is softlink" 
		else
		    ldd $fname 2> /dev/null | ProcessLDD
		fi
	done
}


# Give all symlinks recursively of a full path name
ReadAllLink() {

	incoming="$*"

	for file in $incoming ; do
		if [ ! -f $file ]; then
			continue
		fi
		echo "$file"
		if [ ! -h $file ]; then
			continue
		fi
	
		link=`readlink -e $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 -e $d`
		fi
		if [ "$fchar" != "/" ]; then
			# Relative or local link
			ReadAllLink "$d/$link" 
		else
			# Absolute path
			ReadAllLink $link 
		fi
	done
}


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
}

LogProgress() {
	local i progress modres noof_lines
 
	progress=$1
	noof_lines=$2

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

# Function to log on screen only
LogScreen() {
	if [ -e /dev/stderr ] ; then
		echo -e "$1" >> /dev/stderr
	elif [ -e /usr/bin/logger ] ; then
		/usr/bin/logger -s $1
	fi
}

# Function to log in log file only
LogFile() {

	echo -e "$1" >> $LOGFILE
	if [ _"$2" != _"" ]; then
		grep -Ev "tar: Removing \`/\'" "$2" >> $LOGFILE
	fi
	rm -f "$2"
}

# Function to log in both screen and logfile
LogAll() {
	LogScreen "$1"
	LogFile "$1" "$2"
}


# Called by TurnTgzIntoRdz, to make mondorestore.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_lzma=$USE_LZMA; [ "$use_lzma" = "" ] && use_lzma="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-lzma $use_lzma" >> $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/NETFS-SERVER-MOUNT  netfs-server-mount  $outfile
	AddFileToCfgIfExists $MINDI_TMP/NETFS-SERVER-PATH   netfs-server-path   $outfile
	AddFileToCfgIfExists $MINDI_TMP/NETFS-DEV           netfs-dev           $outfile
	AddFileToCfgIfExists $MINDI_TMP/BOOTLOADER.DEVICE bootloader.device $outfile
	AddFileToCfgIfExists $MINDI_TMP/BOOTLOADER.NAME   bootloader.name   $outfile
	AddFileToCfgIfExists $MINDI_TMP/TAPEDEV-HAS-DATA-DISKS tapedev-has-data-disks $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

	LogFile "------------------------------------" 
	LogFile "Your raw fstab file looks like this:" 
	LogFile "------------------------------------" 
	cat $MY_FSTAB >> $LOGFILE
	LogAll "-----------------------------------" 
	LogAll "Your mountlist will look like this:" 
	LogAll "-----------------------------------" 

# 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
		LogFile "Analyzing LVM..."
		$MINDI_DATA/analyze-my-lvm > $MINDI_TMP/lvm.res
		if [ $? -ne 0 ]; then
			LVM="false"
		fi
		# Excluded LVs and GVs are not reported here
		all_partitions=`cat $MINDI_TMP/lvm.res | grep -F ">>>" | cut -d' ' -f2-`
	fi
	all_partitions="$all_partitions `ListAllPartitions 2> /dev/null`"
	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 %s\n" DEVICE MOUNTPOINT FORMAT "SIZE MB" LABEL/UUID | tee -a $LOGFILE
	printf "%-15s %-15s %-15s %-15s %s\n" ------ ---------- ------  -------  ---------- | 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
		# Skip evices, network FS, cisf
		[ "`echo "$useless_dev" | grep -F "$c_p"`" != "" ] || [ "`echo "$c_p" | grep ":"`" != "" ] || [ "`echo "$c_p" | grep -E "^//"`" != "" ]&& 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
		# Debian 5 does that
		[ "$c_p" = "proc" ] && 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=$KERVERRUN
					[ "`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

		# Look for devices which have to be excluded
		skip=0
		if [ "$MINDI_EXCLUDE_DEVS" ] ; then
			for d in $MINDI_EXCLUDE_DEVS ; do
				if  [ "`echo " $current_partition " | grep " $d"`" != "" ]; then
	    			echo "Excluding $current_partition from mountlist (due to excluded device $d)" >> $LOGFILE
					skip=1
					continue
				fi
			done
		fi
		if [ $skip -eq 1 ]; then
			continue
		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
				LogFile "WARNING: Multiple Logical Volumes found. Report to dev team" 
			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
		    		LogFile "I'm guessing $c_p is $(($partition_size/1024))MB" 
				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
		LogFile "Examining $current_partition (mount=$partition_mountpt fmt=$partition_format psz=$psz)" 
		[ "$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
	        	LogFile "Are you imaging a mounted swap partition? Silly..." 
	        	LogFile "Reverting format from $old_partition_fmt to $partition_format" 
	        	partition_format=$old_partition_fmt
	    	fi
		fi

		if [ ! "$partition_mountpt" ] ; then
	        LogFile "------- $FDISK -l $qq log ------------" 
			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
	        LogFile "------- $FDISK log end ------------" 
			if [ "$partition_format" = "Compaq diagnostics" ] ; then
				partition_format="compaq"
			elif [ ! "`grep -F device /etc/raidtab 2> /dev/null | grep -w $current_partition`" ] ; then
				LogAll "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 "%-15s %-15s %-15s %7s %-15s\n" $current_partition $partition_mountpt $partition_format $psz "$label"`
		if [ "$current_partition" = "" ] ; then
			LogFile "Unknown partition (outstring = $unofficial_outstring)" 
		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 "%-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
				LogFile "Unknown mountpoint (outstring = $unofficial_outstring)" 
			fi
		elif [ "$partition_format" = "" ] ; then
			LogFile "Unknown format (outstring = $unofficial_outstring)" 
		elif [ "$partition_size" = "" ] ; then
			LogFile "Unknown partition size (outstring = $unofficial_outstring)" 
		elif [ "$partition_mountpt" = "/proc" ] || [ "$partition_mountpt" = "/dev/pts" ] ; then
			continue
		else
	    	if [ "$partition_format" = "dos" ] || [ "$partition_format" = "msdos" ] ; then
				LogFile "vfat should be used instead of dos/msdos as a partition format"
	        	partition_format="vfat"
	    	fi
			printf "%-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
	LogAll "-----------------------------------" 
}

CheckMountlist() {
	local file=$1
	# Coherency verification
	ML01=`cat $file | wc -l`
	ML02=`cat $file | grep -v ' lvm ' | wc -l`
	ML1=`$AWK '{print $1}' $file | sort -u | wc -l`
	ML2=`$AWK '{print $2}' $file | grep -v ' lvm ' | sort -u | wc -l`
	if [ "$ML01" -ne "$ML1" ]; then
		LogFile "--------------------------------------------"
		echo "WARNING: Duplicate device entry in mountlist" | tee -a $LOGFILE
		LogFile "--------------------------------------------"
	fi
	if [ "$ML02" -ne "$ML2" ]; then
		LogFile "--------------------------------------------"
		echo "WARNING: Duplicate mountpoint entry in mountlist" | tee -a $LOGFILE
		LogFile "------------------------------------------------"
	fi
}

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 [ -z "$ISO_CMD" ]; then
		LogIt "Neither mkisofs nor genisoimage found, unable to make CD image"
		return
	fi
	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
	rm -Rf $MINDI_TMP/iso
	mkdir -p $MINDI_TMP/iso/{images,archives}
	cp -f $MINDI_CACHE/{*.gz,*.img} $MINDI_TMP/iso/images 2>> $LOGFILE || LogAll "OfferToMakeBootableISO: Cannot copy $MINDI_CACHE/*.gz to $MINDI_TMP/iso/images"
	LogFile "mindi_lib = $MINDI_DATA" 
	for i in memdisk memtest.bin memtest.img ; do
		j=$MINDI_DATA/$i
		k=$MINDI_TMP/iso
		if [ -e "$j" ] ; then
			LogAll "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
		LogFile "----------- $ISO_CMD's errors --------------" 
		cat $MINDI_TMP/mkisofs.log >> $LOGFILE
		echo "$ISO_CMD returned the following errors:-"
		cat $MINDI_TMP/mkisofs.log
		LogAll "Failed to create ISO image."
	else
		LogAll "Created bootable ISO image at $MINDI_CACHE/mindi.iso" 
	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
	rm -Rf $MINDI_TMP/usb
	mkdir -p $MINDI_TMP/usb
	USBPART="${USBDEVICE}1"

	echo -en "Transforming $USBDEVICE in a Bootable device " 
	echo -en "."
	LogFile "Transforming $USBDEVICE in a Bootable device"  
	LogFile "Checking $USBDEVICE" 
	$FDISK -l $USBDEVICE 2>> $LOGFILE 1>> $LOGFILE
	if [ $? -ne 0 ]; then
		LogAll "Unable to access $USBDEVICE" 
		LogAll "Make sure your USB device is pluged in" 
		exit -1
	fi
	echo -en "."
	# Some distro do auto mount at that point (Ubuntu)
	LogFile "Unmounting $USBPART just in case"
	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
	LogFile "Preparing $USBDEVICE" 
	$FDISK $USBDEVICE 2>> $LOGFILE 1>> $LOGFILE << EOF
d
d
d
d
n
p
1


t
b
a
1
w
EOF
	if [ $? -ne 0 ]; then
		LogAll "Unable to create a vfat Filesystem on $USBDEVICE" 
		LogAll "Make sure your USB device is pluged in" 
		$FDISK -l $USBDEVICE 2>&1 | tee -a $LOGFILE
		MindiExit -1
	fi
	LogFile "The USB device $USBDEVICE now looks like this:" 
	$FDISK -l $USBDEVICE 2>&1 | tee -a $LOGFILE
	echo -en "."
	# Some distro do auto mount at that point (Ubuntu)
	LogFile "Unmounting $USBPART just in case again"
	umount $USBPART 2>> $LOGFILE 1>> $LOGFILE
	echo -en "."
	LogFile "Creating a vfat filesystem on $USBPART" 
	mkdosfs -F 32 $USBPART 2>&1 >> $LOGFILE
	if [ $? -ne 0 ]; then
		LogAll "Unable to create a vfat filesystem on $USBPART" 
		LogAll "Make sure your USB device is pluged in and partitioned ($USBPART must exist on it)" 
		$FDISK -l $USBDEVICE 2>&1 | tee -a $LOGFILE
		MindiExit -1
	fi
	echo -en "."
	LogFile "Mounting $USBPART on $MINDI_TMP/usb" 
	mount $USBPART $MINDI_TMP/usb 2>> $LOGFILE
	if [ $? -ne 0 ]; then
		LogAll "Unable to mount $USBPART on $MINDI_TMP/usb" 
		LogAll "Make sure your USB device is pluged in, partitioned and formated ($USBPART must exist on it)" 
		$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 || LogAll "OfferToMakeBootableUSB: Cannot copy $i to $MINDI_TMP/usb/images"
	echo -en "."
	LogFile "mindi_lib = $MINDI_DATA" 
	for i in memdisk memtest.bin memtest.img ; do
		j=$MINDI_DATA/$i
		k=$MINDI_TMP/usb
		if [ -e "$j" ] ; then
			LogAll "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 "."
	LogAll "----------- syslinux's conf --------------"
	cat $MINDI_TMP/usb/syslinux.cfg |tee -a $LOGFILE
	LogAll "------------------------------------------"
	umount $MINDI_TMP/usb
	if [ "$ARCH" != "ia64" ] ; then
		syslinux -s $USBPART 2>> $MINDI_TMP/syslinux.log
		if [ "$?" -ne "0" ] ; then
			LogAll "----------- syslinux's errors --------------"
			cat $MINDI_TMP/syslinux.log |tee -a $LOGFILE
			echo "------------------------------------------"
			LogAll "Failed to create USB image."
		else
			echo -e "$DONE"
			LogFile "Created bootable USB image on $USBDEVICE" 
		fi
		rm -f $MINDI_TMP/syslinux.log
	else
		echo "No USB boot support for ia64" 
		MindiExit -1
	fi
}


MakeMessageFile() {
	
	if [ -x "/bin/lsb_release" ]; then
		DESC=`/bin/lsb_release -d | cut -d: -f2 | sed "s/[ \t]*//"`
	elif [ -x "/usr/bin/pbdistrocheck" ]; then
		# For pb >= 0.9.8
		DESC=`/usr/bin/pbdistrocheck -d`
	else
		iss="/dev/null"
		[ -r /etc/issue.net ] && iss="/etc/issue.net"
		[ -r /etc/issue ] && iss="/etc/issue"
		DESC=`head -1 $iss`
	fi
	sed "s/ZZZZZ/$MINDI_VERSION/" $MINDI_DATA/msg-txt | sed "s/KKKKK/Kernel $KERVER/" | sed "s/AAAAA/on a $ARCH architecture/" | sed "s/TTTTT/`LC_TIME=C date`/" | sed "s/MMMMM/`hostname`/" | sed "s/DDDDD/$DESC/"
	if [ _"$MONDO_SHARE" != _"" ]; then
		if [ "$CDRECOVERY" != "yes" ] ; then
			if [ -e "$MINDI_TMP/NETFS-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_DATA/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/NETFS-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
			options="interactive expert compare iso nuke isonuke"
		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 $MINDI_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} $MINDI_ADDITIONAL_BOOT_PARAMS\n"
		fi
		echo -en "$outstr"
	done

	if [ -e "$MINDI_DATA/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() {
	local imagesdir dev imagefile mountpoint fname i kernelpath cfg_file testpath options retval outstr old_pwd ooo max_kernel_size bootimage liloconf mountefi
	imagesdir=$MINDI_CACHE
	kernelpath=$1
	do_boot_root_thingy=""
	retval=0

	[ ! -e "$kernelpath" ] && Die "PBDI - cannot find $kernelpath kernel"
	echo -en "Making "$BOOT_SIZE"KB boot disk..."
	TurnTgzIntoRdz $MINDI_DATA/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_CACHE/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"
	LogFile "Creating vfat filesystem on $imagefile" 
	mkdosfs $imagefile >> $LOGFILE 2>> $LOGFILE
	if [ "$ARCH" != "ia64" ] ; then
		# syslinux should be run on a local file (doen't work through NFS Cf: #297)
		# Ensure that $MINDI_CACHE is not on NFS (it shouldn't)
		syslinux $imagefile >> $LOGFILE 2>> $LOGFILE
	fi

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

	# copy Mindi's skeleton fs & lilo/syslinux/whatever stuff into it
	mkdir -p $mountpoint/etc
	liloconf=$mountpoint/elilo.conf

	MakeMessageFile > $mountpoint/message.txt

	if [ "$ARCH" != "ia64" ] ; then
		MakeBootConfFile isolinux > $mountpoint/syslinux.cfg
	else
		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
	fi

	LogFile "Copying $MINDI_TMP/initrd.img to $mountpoint/initrd.img..." 
	cp -f $MINDI_TMP/initrd.img $mountpoint/initrd.img 2>> $LOGFILE
	if [ "$?" -ne "0" ] ; then
		LogAll "Failed to copy $MINDI_TMP/initrd.img to $mountpoint"
		cat $MINDI_TMP/mtpt.$$ >> $LOGFILE
		LogAll "Please unload some of your modules and try again."
		rm -f $MINDI_TMP/mtpt.$$
		LogAll "Cannot incorporate initrd.img in bootdisk (kernel / modules too big?)"
		retval=$(($retval+1))
	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
		LogFile "Files at mountpoint ($mountpoint) :-" 
		du -sk $mountpoint/* >> $LOGFILE
		LogFile "--- end of list of files ---" 
		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 || LogAll "Cannot rmdir (PBDI)"

		rm -f $imagefile
		return 0
	fi
	max_kernel_size=$(($free_space+`du -sk $kernelpath | cut -f1`))
	LogFile "Free space left on image = $free_space KB" 
	LogFile "Max kernel size on $BOOT_SIZE KB image (est'd) = $max_kernel_size K" 

	# make it bootable
	[ "$mountpoint" != "" ] && rm -f $mountpoint/zero
	[ -e "$MINDI_DATA/memdisk" ] && cp -f $MINDI_DATA/memdisk $mountpoint 2>> $LOGFILE

	if [ "$ARCH" = "ia64" ] ; then
		cp `dirname $kernelpath`/*.efi $mountpoint 2>> $LOGFILE
	fi
	umount $mountpoint || Die "Cannot unmount mountpoint ($mountpoint)"
	echo -en "..."
	rmdir $mountpoint || LogAll "Cannot rmdir (PBDI)"

	if [ "$retval" -eq "0" ] ; then
		echo -en "...$DONE\n"
		LogAll "$BOOT_SIZE KB boot disk was created OK\n"
	else
		echo -en "...failed\n"
		LogAll "$BOOT_SIZE KB boot disk was NOT created\n"
		rm -f $imagefile
	fi
	[ "$retval" -ne "0" ] && LogAll "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=`ls $DEPLIST_DIR/* | grep -v /minimal`
	if [ -e "$DEPLIST_FILE" ]; then
		lfiles="$DEPLIST_FILE $lfiles"
	fi
	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
	# This function appends to the file passed in param
	ListKernelModulePaths $needlist
	if [ "$res" -ne "0" ] ; then
		Die "You have $res files present in dependency list\nbut absent from filesystem."
	fi
	FindAndAddUserKeyboardMappingFile
	mkdir -p $bigdir/tmp
	[ -d "/mnt/.boot.d" ] && echo "Oh Jebus" > $bigdir/tmp/DUMBASS-GENTOO
	DropOptimizedLibraries $needlist $bigdir
	echo -en "Assembling dependency files"

	CopyDependenciesToDirectory < $needlist $bigdir `wc -l $needlist`

	# 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
		LogAll "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`
		LogAll "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 || LogAll "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
	if [ -d "/lib/dev-state" ]; then 
		tar cf - -C / ./lib/dev-state 2>> $MINDI_TMP/$$.log | tar xf - || LogAll "Unable to handle /lib/dev-state" $MINDI_TMP/$$.log
	fi
	cd $old_pwd
	echo -e "$DONE"
	TOTAL_BIGDIR_SIZE=`du -sk $bigdir | cut -f1`
	mkdir -p $bigdir/tmp
	if [ $LVM != "false" ]; then
		$MINDI_DATA/analyze-my-lvm > $bigdir/tmp/i-want-my-lvm 
		if [ "$?" -ne "0" ]; then
			LVM="false"
			rm -f $bigdir/tmp/i-want-my-lvm
		else
			echo "Your i-want-my-lvm file content is:" >> $LOGFILE
			echo "-----------------------------------" >> $LOGFILE
			cat  $bigdir/tmp/i-want-my-lvm >> $LOGFILE
			echo "-----------------------------------" >> $LOGFILE
		fi
	fi

	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>> $MINDI_TMP/$$.log | gzip -9 > $imagesdir/all.tar.gz || LogAll "Problem creating all.tar.gz" $MINDI_TMP/$$.log)
	LogFile "Size of the data content"
	LogFile "------------------------"
	du -sk $imagesdir/*gz >> $LOGFILE
	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
	# take only the first in case of multiple mount (cifs, nfs, ...)
	[ "$res" = "" ] && res=`df -k -P -x supermount | tr -s '\t' ' ' | grep -F "$device " | cut -d' ' -f2 | head -1`
	[ "$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
	LogFile "Stripped comments from $2" 
}



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
		LogFile "Stripped binary $2" 
	fi
	rm -f $tmpfile
}

KernelVer() {
		local fkern_ver fname

		fname=$1
		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
		echo "$fkern_ver"
}


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

	we_want_version=$KERVERRUN
	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
		fkern_ver=`KernelVer $fname`
		[ "$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
		    	LogAll "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
		    	LogAll "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
		LogAll "No kernel matches exactly. Are there any duff kernels?"
		possible_kernels="$duff_kernels"
		if [ ! "$possible_kernels" ] ; then
		    LogAll "Sorry, no duff kernels either"
		else
		    LogAll "I bet you're running Debian or Gentoo, aren't you?"
		    LogAll "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
		LogAll "Could not find your kernel."
		if [ -e "/boot/vmlinuz" ] ; then
			LogAll "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/' '//`
		LogFile "Your kernel is $kernelpath (v$KERVERRUN)" 
		output="$kernelpath"
	else
		for i in $possible_kernels ; do
		    if echo $i | grep "$KERVERRUN" ; then
				LogAll "OK, I used my initiative and found that "
		        LogAll "$i is probably your kernel. "
				output="$i"
				return
			fi
		done
		if echo " $possible_kernels " | grep -F "/boot/vmlinuz " &> /dev/null ; then
			output=/boot/vmlinuz
			LogFile "Schlomo, this one's for you." 
		else
		    LogAll "Two or more possible kernels found. You may specify any one of them and the "
			LogAll "boot disks will still work, probably. If one does not work, try another."
		    LogAll "$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 res currsize not_copied j k s w needed_modules_path

	tgz_dir_fname=$1
	rdz_fname=$2
	kernelsize=$3
	# Compute the list of all that should be copied/created on the final mountpoint under MINDI_TMP
	# mkdir.lis will contain the list of directries to create
	# cp.lis will contain the list of files/dirs to copy
	# ln.lis will contain the list of files to link to existing files
	# rm.lis will contain the list of files to remove after the copies
	# AL04Oct08: Check whether /lib64 is a link and if so explicitly create one in rootfs
	if [ -h "/lib64" ]; then
		echo lib  >> $MINDI_TMP/mkdir.lis
		echo ln -s lib lib64  >> $MINDI_TMP/ln.lis
	fi

	[ -e "/dev/.devfsd" ] && echo "/dev/.devfsd found" > $MINDI_CACHE/USE-DEVFS
	echo  $MINDI_CACHE/USE-DEVFS >> $MIDI_TMP/cp.lis

	# We need a minimal conf in the initial ramdisk
	mountlis=`grep -v "^#.*" $DEPLIST_FILE_MIN $DEPLIST_DIR/minimal*.conf | cut -d: -f2 | sort -u`
	ReadAllLink $mountlis >> $MINDI_TMP/mnt.lis
	LocateDeps `cat $MINDI_TMP/mnt.lis` >> $MINDI_TMP/deps.lis
	# Special for libs
	ReadAllLink `grep -E "/lib" $DEPLIST_FILE_MIN $DEPLIST_DIR/minimal*.conf | grep -v "^#.*" | cut -d: -f2` >> $MINDI_TMP/deps.lis

	echo `cat $MINDI_TMP/mnt.lis` `sort -u $MINDI_TMP/deps.lis` >> $MINDI_TMP/cp.lis
	rm -f $MINDI_TMP/deps.lis $MINDI_TMP/mnt.lis

	# Copy of files mandatory for ld.so
	echo /etc/ld.so.c* >> $MINDI_TMP/cp.lis

	# Avoid an issue on some distro (RHEL5)
	echo ./etc/ld.so.conf.d/kernelcap* >> $MINDI_TMP/rm.lis

	# Need for a tmp dir
	echo tmp >> $MINDI_TMP/mkdir.lis

	# 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" > $MINDI_CACHE/USE-UDEV
		echo $MINDI_CACHE/USE-UDEV >> $MINDI_TMP/cp.lis
		LogFile "udev device manager found"
		echo /etc/udev /lib*/udev >> $MINDI_TMP/cp.lis
		# This avoids NIC remapping if on another machine at restore time on Debian at least
		echo ./etc/udev/rules.d/z[0-9][0-9]_persistent-net.rules >> $MINDI_TMP/rm.lis
		# This avoids NIC remapping if on another machine at restore time on Ubuntu at least
		echo ./etc/udev/rules.d/[0-9][0-9]-persistent-net.rules >> $MINDI_TMP/rm.lis
		if [ -x /sbin/udevd ]; then
			# Get only the files which exist in the udev.files list
			# and potentially their symlink structure and their deps
			mountlis=`grep -Ev "^#" $MINDI_CONF/udev.files`
			ReadAllLink $mountlis | sort -u >> $MINDI_TMP/udev.lis
			LocateDeps `cat $MINDI_TMP/udev.lis` | sort -u >> $MINDI_TMP/cp.lis
			cat $MINDI_TMP/udev.lis >> $MINDI_TMP/cp.lis
			rm -f $MINDI_TMP/udev.lis
		else
			LogAll "udevd daemon not in standard place (/sbin)"
			LogAll "mindi will use static devices which may cause problems"
			rm -f $MINDI_CACHE/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
		LogAll "Hardware Information found and saved ..."
		echo $MINDI_CACHE/bkphw >> $MIDNDI_TMP/cp.lis
		if [ -f $MINDI_CACHE/tools.files ]; then
			lis=`grep -Ev '^#' $MINDI_CACHE/tools.files` 
			LocateDeps $lis > $MINDI_TMP/tools.lis
			echo $lis `sort -u $MINDI_TMP/tools.lis` >> $MINDI_TMP/cp.lis
		fi
		if [ -f $MINDI_CACHE/mindi-rsthw ]; then
			chmod 755 $MINDI_CACHE/mindi-rsthw
			echo $MINDI_CACHE/mindi-rsthw >> $MINDI_TMP/cp.lis
		fi
		rm -f $MINDI_TMP/tools.lis $MINDI_CACHE/tools.files
	fi

	# Management of perl scripts delivered needed at restore time
	mindi-get-perl-modules `cat $MINDI_CONF/perl-scripts` >> $MINDI_TMP/cp.lis

	echo mnt/cdrom >> $MINDI_TMP/mkdir.lis

	ls /dev/fd0*[1,2][4,7,8]* >> $MINDI_TMP/cp.lis 2> /dev/null

	if [ "${kernelname}" != "" ]
	then
		needed_modules_path=/lib/modules/${kernelname}
	else
		needed_modules_path=/lib/modules/$KERVERRUN
	fi

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

	if [ -e "$MINDI_TMP/NETFS-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
		LogFile "Removing $i from the list of modules to load" 
		list_of_groovy_mods=`echo ${list_of_groovy_mods} | tr ' ' '\n' | grep -Ev "^${i}$" | tr '\n' ' '`
	done

	[ -e "$needed_modules_path" ] || LogAll "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=""
		LogFile "Adding $i ($s KB) to the rootfs" 
		echo $i >> $MINDI_TMP/cp.lis
	done

	# Also copy modules.dep in case of udev so that normal modprobe works
	echo $needed_modules_path/modules.dep >> $MINDI_TMP/cp.lis

	# Manages mountlit.txt
	MakeMountlist $MINDI_CACHE/mountlist.txt
	CheckMountlist $MINDI_CACHE/mountlist.txt
	echo $MINDI_CACHE/mountlist.txt >> $MINDI_TMP/cp.lis
	cat $MINDI_CACHE/mountlist.txt >> $LOGFILE
	LogFile "-----------------------------------"

	if [ ! -e "/sbin/devfsd" ] ; then
		LogFile "Deleting devfsd daemon from ramdisk because /sbin/devfsd not found" 
		echo ./sbin/devfsd >> $MINDI_TMP/rm.lis
	fi

	cd $old_pwd
	if [ _"$MONDO_SHARE" != _"" ]; then
		MakeMondoConfigFile $MINDI_CACHE/mondorestore.cfg
		echo $MINDI_CACHE/mondorestore.cfg >> $MINDI_TMP/cp.lis
	fi
	echo proc >> $MINDI_TMP/mkdir.lis

	# Copy of files mandatory for ssh to automate mount if sshfs is used
	echo .ssh >> $MINDI_TMP/mkdir.lis

	# Now create the container and do the job
	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 ($tempfile)"
	echo -en "..."
	LogFile "Creating ext2 filesystem on $tempfile" 
	mke2fs -b 1024 -m 0 -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`

	# First create dirs
	for d in `cat $MINDI_TMP/mkdir.lis`; do
		mkdir -p $mountpoint/$d 2>&1 >> $LOGFILE
	done

	# Then copy files needed
	LANGUAGE=C tar cf - `cat $MINDI_TMP/cp.lis` 2> /dev/null | (cd $mountpoint ; tar xf - ) 2>&1 | grep -Ev "tar: Removing.*/\'" >> $LOGFILE 

	# Then handle links
	if [ -f $MINDI_TMP/ln.lis ]; then
		(cd $mountpoint ; bash $MINDI_TMP/ln.lis) 2>&1 >> $LOGFILE
	fi

	# Finally remove useless stff
	(cd $mountpoint ; rm -f `cat $MINDI_TMP/rm.lis`) 2>&1 >> $LOGFILE 

	# Copy of files mandatory for ssh to automate mount if sshfs is used
	cp -rp ~root/.ssh/*.pub ~root/.ssh/config ~root/.ssh/known* $mountpoint/.ssh 2> /dev/null
	cat > $mountpoint/bin/myssh << EOF
ssh -o StrictHostKeyChecking=no $*
EOF
	chmod 755 $mountpoint/bin/myssh

	# Finally integrate what we provide statically as part of mindi
	(cd $tgz_dir_fname ; LANGUAGE=C tar cf - . ) | (cd $mountpoint ; tar xf - ) 2>&1 | grep -Ev "tar: Removing.*/\'" >> $LOGFILE 

	# Extracting devices
	(cd $mountpoint/dev ; tar -zxf dev-entries.tgz) || Die "Cannot untar dev-entries.tgz"
	rm -f $mountpoint/dev/dev-entries.tgz

	LogFile "---------------------------"
	LogFile "Content of initial ramdisk:"
	LogFile "---------------------------"
	(cd $mountpoint ; ls -Rla ) >> $LOGFILE
	LogFile "---------------------------"

	# Determine what filesystem to use for initrd image
	LogFile "Call GetInitrdFilesystemToUse() with parameter ${kernelpath} to get filesystem to use for initrd." 
	gvFileSystem=`GetInitrdFilesystemToUse ${kernelpath}`
	[ -z  gvFileSystem ] && Die "GetFilesystemToUse() failed. Terminating."
	if [ "$gvFileSystem" = "ext2fs" ] || [ "$gvFileSystem" = "ext3fs" ]; then
		# say what will be used
		LogFile "Creating an $gvFileSystem initrd image..."
		# 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/^ *//'`
		MINDI_ADDITIONAL_BOOT_PARAMS="$MINDI_ADDITIONAL_BOOT_PARAMS ramdisk_blocksize=$bs"
		gzip -c9 ${rdz_fname}.tmp > $rdz_fname
		rm -f ${rdz_fname}.tmp
		# log that we are done
		LogFile "...done." 
	elif [ "$gvFileSystem" = "initramfs" ]; then
		# say what will be used
		LogFile "Creating a gzip'ed cpio (AKA initramfs) initrd image..." 
		# make sure that cpio is there
		which cpio &> /dev/null; [ $? -eq 0 ] || Die "cpio not found. Please install package cpio and try again."
		# go into filesystem
		cd $mountpoint
		# kernel expects init in cpio filesystem
		ln -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
    	LogFile "...done." 
	else
		Die "Filesystem $gvFileSystem not supported for initrd image. Terminating."
	fi
	ls -al $MINDI_TMP/initrd.img > /tmp/initrd.log

	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

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

> $LOGFILE
LogFile "mindi v$MINDI_VERSION" 
LogFile "$ARCH architecture detected" 
LogFile "mindi called with the following arguments:" 
LogFile "$*"
LogFile "Start date : `date`" 
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."
LogFile "MONDO_SHARE = $MONDO_SHARE" 
LogFile "MINDI_DATA = $MINDI_DATA" 
LogFile "MINDI_SBIN = $MINDI_SBIN" 
[ "$MINDI_CONF" = "YYY" ] && Die "Mindi has not been installed correctly."
LogFile "MINDI_CONF = $MINDI_CONF" 
if [ -f $MINDI_CONFIG ]; then
	LogFile "-----------------------------" 
	LogFile " Mindi configuration file    " 
	LogFile "-----------------------------" 
	grep -Ev '^#' $MINDI_CONFIG >> $LOGFILE
	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
		LogAll "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 $FDISK"

[ "`echo $KERVERRUN | 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
	LogFile "Your PATH did not include /sbin or /usr/sbin. I have fixed that, temporarily." 
	LogFile "However, you may wish to ask your vendor to provide a permanent fix..." 
	LogFile " Or you might like to call 'su -' instead of 'su', for example." 
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

if [ -e "/proc/cmdline" ]; then
	CMDLINE="/proc/cmdline"
elif [ -e "/tmp/cmdline" ]; then
	CMDLINE="/tmp/cmdline"
else
	CMDLINE="/dev/null"
fi

LogFile "LVM set to $LVM" 
LogFile "----------" 
LogFile "mount result:" 
LogFile "-------------" 
mount >> $LOGFILE
LogFile "-------------" 
if [ -e /etc/raidtab ]; then
	LogFile "-------------" 
	LogFile "/etc/raidtab content:" 
	LogFile "-------------" 
	cat /etc/raidtab >> $LOGFILE
fi
LogFile "-------------" 
LogFile "cat $CMDLINE" 
LogFile "-------------" 
cat $CMDLINE >> $LOGFILE
LogFile "-------------" 
LogFile "cat /proc/swaps:" 
LogFile "-------------" 
cat /proc/swaps >> $LOGFILE
LogFile "-------------" 
LogFile "cat /proc/partitions:" 
LogFile "-------------" 
cat /proc/partitions >> $LOGFILE
LogFile "-------------" 
LogFile "cat /proc/filesystems:" 
LogFile "-------------" 
cat /proc/filesystems >> $LOGFILE
LogFile "-------------" 
LogFile "lsmod result:" 
LogFile "-------------" 
lsmod >> $LOGFILE
MODULES="`cat /proc/modules | $AWK '{print $1}'`"
if [ -x /usr/sbin/esxcfg-module ]; then
	LogFile "-------------" 
	LogFile "VMWare ESX server detected - Enabling dedicated support" 
	LogFile "-------------" 
	LogFile "VMWare modules" 
	LogFile "-------------" 
	/usr/sbin/esxcfg-module -l >> $LOGFILE
	MODULES="$MODULES `/usr/sbin/esxcfg-module -l | $AWK '{print $1}'`"
fi
LogFile "FORCE_MODS:" 
LogFile "-------------" 
LogFile $FORCE_MODS 
LogFile "-------------" 
LogFile "DENY_MODS:" 
LogFile "-------------" 
LogFile $DENY_MODS 
LogFile "-------------" 
LogFile "df result:" 
LogFile "----------" 
df -T >> $LOGFILE
LogFile "-------------" 
LogFile "Liste of extra modules is:" 
LogFile "$EXTRA_MODS" 
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"
		LogFile "ide-generic removed from module list as your system uses libata v2+" 
		LogFile "-------------" 
	fi
fi

# Check for ISO_CMD command
if [ ! -x $ISO_CMD ]; then
	echo "NOTE: No CD image (ISO file) utility found" >> $LOGFILE
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 $*
		# Avoids logfile content for mondo
		export MONDO_SHARE=""
		MindiExit $?
	elif [ "$1" = "--readalllink" ] ; then
		[ ! "$2" ] && Die "Please specify the binary to look at"
		shift
		ReadAllLink $*
		# Avoids logfile content for mondo
		export MONDO_SHARE=""
		MindiExit $?
	elif [ "$1" = "--makemountlist" ] ; then
		[ ! "$2" ] && Die "Please specify the output file"
		MakeMountlist $2
		CheckMountlist $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
		if [ _"$MONDO_TMP" = _"" ]; then
			Die "MONDO_TMP is empty, aborting"
		fi
		if [ _"$MONDO_TMP" = _"/" ]; then
			Die "MONDO_TMP is /, aborting"
		fi
		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

		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-`
		LogAll "kernelname = $kernelname"
		LogAll "kernelpath = $kernelpath"
		if [ ! -d "/lib/modules/$kernelname" ]
		then
		   LogAll "Module path for ${kernelpath} not found..."
		   LogAll "using running kernel\'s modules."
		   kernelname=$KERVERRUN
		else
		   LogAll "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=""
	#	    LogAll "LILO will use conservative settings, to be compatible with older BIOSes."
		fi
		ESTIMATED_TOTAL_NOOF_SLICES=${12}
		export MINDI_EXCLUDE_DEVS="${13}"
		USE_COMP="${14}"
		USE_LILO="${15}"
		USE_STAR="${16}"
		INTERNAL_TAPE_BLOCK_SIZE="${17}"
		DIFFERENTIAL="${18}"
		USE_GZIP="${19}"
		USE_LZMA="${20}"
		[ "$USE_COMP" = "" ] && USE_COMP=yes
		[ "$USE_GZIP" = "" ] && USE_GZIP=no
		[ "$USE_LZMA" = "" ] && USE_LZMA=no
		[ "$TAPEDEV" ] && LogAll "This is a tape-based backup. Fine."
		[ "$kernelpath" = "" ] && kernelpath=`TryToFindKernelPath`
		kernelname=`echo $kernelpath | cut -d'-' -f2-`
		if [ ! -d "/lib/modules/$kernelname" ]
		then
		   LogAll "Module path for ${kernelpath} not found..."
		   LogAll "using running kernel\'s modules."
		   kernelname=$KERVERRUN
		else
		   LogAll "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
		LogScreen "Syntax: mindi (--custom ....)"
		MindiExit -1
	fi
fi

if [ _"$MINDI_CACHE" != _"" ]; then
	rm -rf $MINDI_CACHE/* 2> /dev/null
	mkdir -p $MINDI_CACHE
fi

[ "$CDRECOVERY" = "yes" ] || CDRECOVERY=no

LogAll "Mindi Linux mini-distro generator v$MINDI_VERSION"
LogAll "Latest Mindi is available from http://www.mondorescue.org"
LogAll "------------------------------------------------------------------------------"
LogFile "DIFFERENTIAL = $DIFFERENTIAL" 
LogFile "INTERNAL TAPE BLOCK SIZE = $INTERNAL_TAPE_BLOCK_SIZE" 

if [ "$PROMPT_MAKE_USB_IMAGE" = "yes" ] && [ "$USBDEVICE" != "" ]; then
	LogAll "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
		kernelpath=`TryToFindKernelPath`
		if [ "$kernelpath" = "" ] ; then
			echo -n "Please enter kernel path : "
			read kernelpath
		fi
	fi
fi
LogFile "Mindi's temp dir=$MINDI_TMP"
LogFile "Mindi's output dir=$MINDI_CACHE" 
[ "$(($RANDOM%64))" -eq "0" ] && LogAll "Dude, I've looked inside your computer and it's really dusty..."

PrepareDataDiskImages

export ramdisk_size=$(($size_of_all_tools+$EXTRA_SPACE))

LogFile "Ramdisk will be $ramdisk_size KB" 
PrepareBootDiskImage $kernelpath || Die "Failed to create $ramdisk_size MB disk image."

[ -e "$MINDI_DATA/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
	LogAll "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
LogAll "$FRIENDLY_OUTSTRING"
for mtpt in $FLOPPY_WAS_MOUNTED ; do
	mount $mtpt
done
MindiExit 0
