#!/bin/bash

# $Id: mindi 3330 2014-12-23 06:49:06Z 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_DEFAULT_BOOT_OPTION="interactive"
# For a CD Recovery use 10000 instead rather. Beware till Hardcoded below. Planned to be changed on the perl version
# So this parameter only applies to non CD recovery.
MINDI_BOOT_TIMEOUT="300"

MINDI_REV=3332
MINDI_VER=3.0.0

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

MRCFG=mondorestore.cfg

# Temporary directory for mindi
TMPDIR=/tmp

EXTRA_SPACE=120000		# increase if you run out of ramdisk space
BOOT_SIZE=65600			# 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.

KERNEL_IS_XEN="no"
	# If set to "no", the kernel is not a Xen kernel
	# If "yes", mindi will modify isolinux.cfg for the Xen kernel.
xenkernelpath=""
 
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 hpsa dmx3191d dpt_i2o dtc eata eata_dma eata_pio fdomain gdth g_NCR5380 i2o_block ide-scsi ieee1394 imm in2000 initio ips iscsi be2iscsi cxgb3i cxgb3 cxgb4i cxgb4 uio isp megaraid megaraid_mbox megaraid_sas mega_sr mptscsih mptsas mptspi mptfc mptscsi mptctl NCR53c406a ncr53c8xx nsp32 pas16 pci2000 pci2220i pcmcia ppa psi240i qla1280 qla2200 qla2300 qla2400 qla2xxx qlogicfas qlogicfc qlogicisp qlogicfas qlogicfas408 raw1394 scsi_mod sd_mod seagate sg sim710 sr_mod sym53c416 sym53c8xx sym53c8xx_2 t128 tmscsim u14-34f ultrastor wd7000 vmhgfs intermodule emcpdm emcpgpx emcpmpx emcp dc395x diskdumplib arcmsr"

# 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 edd paride ata_generic ata_piix dock via82cxxx generic nvidia ahci sata_nv cmd64x pata_via pata_amd pata_marvell pata_serverworks pata_sis pata_sil680 pata_jmicron pata_atiixp pata_acpi amd74xx sis5513 jmicron sata_promise sata_via serverworks sata_svw virtio"
PCMCIA_MODS="pcmcia_core ds yenta_socket"
USB_MODS="usb-storage usb_storage usb-ohci usb-uhci input hid uhci_hcd uhci-hcd ehci-hcd ehci-pci ohci-hcd ohci_hcd ohci-pci xhci xhci-hcd usbkbd usbhid keybdev mousedev scsi_mod ff-memless ums_cypress ums-cypress cp210x usbserial"
NET_MODS="nfs nfsv2 nfsv3 nfsv4 nfsd loop mii 3c59x e100 bcm5700 cnic be2net bnx2 bnx2x bnx2i mdio e1000 e1000e igb dca eepro100 ne2k-pci tg3 pcnet32 8139cp 8139too 8390 forcedeth vmxnet vmxnet3 vmnet exportfs fuse netbk xenblktap r8169 virtio_net via_rhine ipv6 ptp"
CDROM_MODS="$TAPE_MODS $IDE_MODS $USB_MODS $PCMCIA_MODS $SCSI_MODS $NET_MODS cdrom isocd isofs sg sr_mod iso9660 vfat fat loop md-mod lvm-mod dm-mod dm_mod dm-multipath dm-emc dm-hp-sw dm-rdac dm-region-hash multipath jfs xfs btrfs reiserfs ext2 ext3 minix nfs nfsd ext4 ocfs2 configfs vxfs "
# Replace with that line for HP OCMP e.g.
#DENY_MODS="MPS_Driver_Mapper mps octtldrv tscttl streams kqemu fdomain"
DENY_MODS="kqemu vxfen"
# Force some modules to be included
FORCE_MODS=""

# Find MBR in case of bootable USB device to build
MBRFILE=/usr/lib/syslinux/mbr.bin
[ ! -r "$MBRFILE" ] && MBRFILE=/usr/lib64/syslinux/mbr.bin
[ ! -r "$MBRFILE" ] && MBRFILE=/usr/share/syslinux/mbr.bin
[ ! -r "$MBRFILE" ] && MBRFILE=/usr/share/lib/syslinux/mbr.bin
[ ! -r "$MBRFILE" ] && MBRFILE=/usr/share/lib64/syslinux/mbr.bin

LOGFILE=/var/log/mindi.log
BOOT_MEDIA_MESSAGE="\
To format and restore all files automatically, type '0enuke07' <enter>.\n\
To restore some/all files interactively, type '0einteractive07' <enter>.\n\
To compare the archives with your filesystem, type '0ecompare07' <enter>.\n\
To boot to a command-line prompt (expert mode), type '0eexpert07' <enter>.\n\
\n\
You may add one or more parameters as well as per the function keys below\n\
e.g. Type '0enuke denymods=\"fdomain impi_si\"07' to not load these 2 modules\n\
\n\
If restoring from a local external disk or USB key, do not connect it \n\
until the boot-up has finished.\n\
\n\
\n0eF107-Main | Boot Parameters 0eF207-1/2 | 0eF307-2/2 | 0eF407-PXE\n\
"
FDISK=$MINDI_SBIN/parted2fdisk

# Using a config file allow to overwrite some values
MINDI_CONFIG="$MINDI_CONF/mindi.conf"
if [ -f $MINDI_CONFIG ]; then
	. $MINDI_CONFIG
fi
DEPLIST_FILE="$MINDI_CONF/deplist.txt"
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


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

# Preserved for compatibility
LogIt() {
	LogAll "$1" "$2"
}

# Last function called before exiting
# Parameter is exit code value
# Should be declared here as used immediately below potentialy
MindiExit() {
	LogFile "Mindi $MINDI_VERSION is exiting" 
	LogFile "End date : `date`" 
	if [ _"$MONDO_SHARE" != _"" ] ; then
		echo "------------- mindi logfile included -------------------------" >> /var/log/mondoarchive.log
		if [ -f $LOGFILE ]; then
			cat $LOGFILE >> /var/log/mondoarchive.log
		else
			echo "No LOGFILE available in that mindi run"  >> /var/log/mondoarchive.log
		fi
		echo "--------------------------------------------------------------">> /var/log/mondoarchive.log
	fi

	cd /
	sync&

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

# 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
	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 "INFO: $mappath already added"
		return
	elif [ -d "$bigdir/$mappath" ] ; then
		echo "Cannot add $mappath: it's a directory. Sorry."
		return
	fi
	LogFile "INFO: 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 "WARNING: Cannot add $mappath: kbd map file not found"
		    return
		fi
	else
		echo -en "`basename $mappath | tr '.' '#' | sed s/#kmap#gz// | sed s/#inc#gz//` " | tr '#' '.'
	fi

	#cp -a -n --parents -t $mappath $bigdir 2>> $MINDI_TMP/$$.log || LogAll "WARNING: AKMF -- Could not copy $mappath to $bigdir" $MINDI_TMP/$$.log
	tar cf - -C / $mappath 2>> $MINDI_TMP/$$.log | (cd "$bigdir" ; tar xf -) || LogAll "WARNING: 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/'"'//g | cut -d' ' -f2`
	else
		included_list=`grep -Fi include $mappath | sed s/'"'//g | 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 counter d found tdir
	outdir=$1
	mkdir -p $outdir
	incoming=`ReadLine`
	counter=0
	while [ "$incoming" != "" ] ; do
		# Non absolute file names should not arrive till here => skipped
		if [ `echo "$incoming" | cut -c1` != '/' ]; then
			LogAll "WARNING: 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" -a ! -h "$incoming" ]; then
		    find $incoming/* -maxdepth 0 2> /dev/null | CopyDependenciesToDirectory $outdir 0
		elif [ -e "$incoming" ] && [ $found = "false" ]; then
			if [ ! -h "$incoming" ]; 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
			else
				tdir=`dirname "$incoming"`
				if [ ! -e "$outdir/$tdir" ]; then
					mkdir -p "$outdir/$tdir"
				fi
				cp --no-dereference --preserve=all $incoming "$outdir/$tdir"
			fi
			# 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 "WARNING: Cannot gunzip $outdir/$incoming"
			fi
			[ -x "$outdir" ] && StripExecutable $outdir
			counter=$(($counter+1))
			LogProgress $counter $2
		fi
		incoming=`ReadLine`
	done
}


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


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

	list_of_optimized_libraries=`grep "lib/i[5-7]86/" $filelist`
	if [ "$list_of_optimized_libraries" = "" ] ; then
		return 0
	fi
	echo -en "Dropping i686-optimized libraries if appropriate"
	for optimized_lib_name in $list_of_optimized_libraries ; do
		echo -en "."
		reason=""
		vanilla_lib_name=`echo "$optimized_lib_name" | sed -e 's/i[5-7]86//' -e 's/cmov//' -e 's/nosegneg//' | tr -s '/' '/'`
		echo "$vanilla_lib_name" >> $filelist
		LogFile "INFO: 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 `mr-read-all-link $vanilla_lib_name`; do
			LogFile "INFO: 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 '/' '/'`
			if [ "$vanilla_resolved_name" != "$resolved" ]; then
				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 "INFO: Excluding deps $resolved" 
				grep -Fvx "$resolved" "$filelist" > $filelist.tmp
				LogFile "INFO: Replacing it with $vanilla_resolved_name" 
				echo "$vanilla_resolved_name" >> $filelist.tmp
				mv -f $filelist.tmp $filelist
			fi
		done
	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
	LogAll "INFO: Analyzing your keyboard's configuration."
	KEYDIR=/usr/lib/kbd
	[ ! -e "$KEYDIR" ] && KEYDIR=/usr/share/kbd		# Slackware
	[ ! -e "$KEYDIR" ] && KEYDIR=/etc/condole
	[ ! -e "$KEYDIR" ] && KEYDIR=/etc/condole-setup
	[ ! -e "$KEYDIR" ] && KEYDIR=/lib/kbd
	if [ ! -e "$KEYDIR" ] ; then
		LogAll "WARNING: Keyboard mapping directory not found. I shall use default map at boot-time."
		return 0
	fi
	if [ -e "/etc/sysconfig/keyboard" ] ; then
		LogFile "INFO: Red Hat-style config detected."
		keyfile=/etc/sysconfig/keyboard
	elif [ -e "/etc/vconsole.conf" ] ; then
 		LogFile "INFO: New Fedora style config detected."
 		keyfile=/etc/vconsole.conf
	elif [ -e "/etc/rc.d/rc.keymap" ] ; then
 		LogFile "INFO: Slackware-style config detected."
 		keyfile=/etc/rc.d/rc.keymap
	elif [ -e "/etc/rc.config" ] ; then
		LogFile "INFO: Debian-style config detected."
		keyfile=/etc/rc.config
	elif [ -e "/etc/console/boottime.kmap.gz" ] ; then
		LogFile "INFO: Debian-style config detected."
		mkdir -p $bigdir/tmp
		echo "keymap-lives-here /etc/console/boottime.kmap.gz" >> $bigdir/tmp/$MRCFG
		KBDEPTH=0
		mkdir -p $bigdir/etc/console
		cp /etc/console/boottime.kmap.gz $bigdir/etc/console 2>> $LOGFILE
		echo ""
		echo -e "$DONE"
		return 0
	elif [ -e "/etc/console-setup/boottime.kmap.gz" ] || [ -e "/etc/console-setup/cached.kmap.gz" ] ; then
		LogFile "INFO: Ubuntu-style config detected."
		mkdir -p $bigdir/tmp
		if [ -e "/etc/console-setup/boottime.kmap.gz" ] ; then
			kbdfile="/etc/console-setup/boottime.kmap.gz"
		else
			kbdfile="/etc/console-setup/cached.kmap.gz"
		fi
		echo "keymap-lives-here $kbdfile" >> $bigdir/tmp/$MRCFG
		KBDEPTH=0
		mkdir -p $bigdir/etc/console-setup
		cp $kbdfile $bigdir/etc/console-setup 2>> $LOGFILE
		echo ""
		echo -e "$DONE"
		return 0
	elif [ -e "/etc/rc.conf" ] ; then
		LogFile "INFO: ArchLinux config detected."
		keyfile=/etc/rc.conf
	elif [ -e "/etc/conf.d/keymaps" ] ; then
		LogFile "INFO: Gentoo-style config detected."
		keyfile=/etc/conf.d/keymaps
	elif [ -e "/etc/X11/xorg.conf.d/00-keyboard.conf" ] ; then
		LogFile "INFO: X11-style config detected."
		keyfile=/etc/X11/xorg.conf.d/00-keyboard.conf
	else
		LogFile "Searching for rc.config ..."
		keyfile=`find /etc -name rc.config | head -n1`
		if [ "$keyfile" = "" ] || [ ! -e "$keyfile" ] ; then
			LogAll "WARNING: Unknown config detected. Default keyboard map will be used."
			return
		else
			LogFile "INFO: Found $keyfile"
		fi
	fi
	if [ ! -e "$KEYDIR/keymaps" ] ; then
		LogAll "WARNING: Keyboard mapping directory not found. Default keyboard map will be used."
		return
	fi
	LogFile "INFO: keyfile=$keyfile"
	# For SLES we need to remove the .map.gz extension Cf #614
	locale=`grep -F KEYTABLE "$keyfile" | grep -v '^#' | tr -d '"' |cut -d'=' -f2 | sed 's/.map.gz$//'`
	[ ! "$locale" ] && locale=`grep '.map$' "$keyfile" | sed 's/^.* //'`		# Slackware
	[ ! "$locale" ] && locale=`grep -E '^KEYMAP=' "$keyfile" | grep -v '^#' | tr -d '"' |cut -d'=' -f2`		# Gentoo, ArchLinux & New fedora
	[ ! "$locale" ] && locale=`grep -E 'XkbLayout' "$keyfile" | grep -v '^#' | awk '{print $3}' | tr -d '"'`		#  Fedora 19
	LogFile "INFO: 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 "INFO: 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 / -wholename "*/kbd/keymaps/*/$locale | head -1")
	fi
	LogFile "INFO: mappath = $mappath"
	if [ ! -e "$mappath" ] || [ -d "$mappath" ] ; then
		LogAll "WARNING: Keyboard mapping file not found. Default keyboard map will be used."
		return
	fi
	LogAll "INFO: Adding the following keyboard mapping tables: "
	mkdir -p $bigdir/tmp
	echo "keymap-lives-here $mappath" >> $bigdir/tmp/$MRCFG
	KBDEPTH=0
	AddKeyboardMappingFile $mappath
	echo ""
	echo -e "$DONE"
	rm -f $MINDI_TMP/keymaps.find
	return 0
}


FindLdlinux32Binary() {
	LDLINUXC32=/usr/lib/syslinux/ldlinux.c32
	[ ! -e "$LDLINUXC32" ] && LDLINUXC32=/usr/lib64/syslinux/ldlinux.c32
	[ ! -e "$LDLINUXC32" ] && LDLINUXC32=/usr/share/syslinux/ldlinux.c32
	[ ! -e "$LDLINUXC32" ] && LDLINUXC32=/usr/share/lib/syslinux/ldlinux.c32
	[ ! -e "$LDLINUXC32" ] && LDLINUXC32=/usr/share/lib64/syslinux/ldlinux.c32
	[ ! -e "$LDLINUXC32" ] && LDLINUXC32=/usr/lib/syslinux/modules/bios/ldlinux.c32
	[ ! -e "$LDLINUXC32" ] && LDLINUXC32=/usr/lib64/syslinux/modules/bios/ldlinux.c32
	#[ ! -e "$LDLINUXC32" ] && LDLINUXC32=`find / -name ldlinux.c32 | grep -x "/.*/ldlinux.c32"`
	if [ ! -e "$LDLINUXC32" ]; then 
		LogFile "INFO: If you use syslinux 5.x, you may miss ldlinux.c32. If your syslinux RPM doesn't include ldlinux.c32, you may want to download another one"
		LDLINUXC32=/tmp/idoesnthopefullyexist
	else
		LogFile "INFO: Found ldlinux.c32 at $LDLINUXC32"
	fi
}


FindMboot32Binary() {
	MBOOTC32=/usr/lib/syslinux/mboot.c32
	[ ! -e "$MBOOTC32" ] && MBOOTC32=/usr/lib64/syslinux/mboot.c32
	[ ! -e "$MBOOTC32" ] && MBOOTC32=/usr/share/syslinux/mboot.c32
	[ ! -e "$MBOOTC32" ] && MBOOTC32=/usr/share/lib/syslinux/mboot.c32
	[ ! -e "$MBOOTC32" ] && MBOOTC32=/usr/share/lib64/syslinux/mboot.c32
	[ ! -e "$MBOOTC32" ] && MBOOTC32=/usr/lib/syslinux/modules/bios/mboot.c32
	[ ! -e "$MBOOTC32" ] && MBOOTC32=/usr/lib64/syslinux/modules/bios/mboot.c32
	[ ! -e "$MBOOTC32" ] && MBOOTC32=`find / -name mboot.c32 | grep -x "/.*/mboot.c32"`
	[ ! -e "$MBOOTC32" ] && Die "Please install mboot.c32 first. If your syslinux RPM doesn't include mboot.c32, you may download an isolinux RPM from Mondo's website - go to http://www.mondorescue.org/downloads.shtml"
	LogFile "INFO: Found mboot.c32 at $MBOOTC32"
}

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=/usr/lib/ISOLINUX/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.org/downloads.shtml"
	LogFile "INFO: Found isolinux.bin at $ISOLINUX"
}


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 "WARNING: $incoming not found"
		res=$(($res+$r))
#		LogFile "INFO: '$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/usr/bin
		if [ -e "$MINDI_TMP/post-nuke.tgz" ] ; then
			LogAll "\nINFO: Incorporating post-nuke tarball"
			old_pwd=`pwd`
			cd "$bigdir"
			tar -zxf $MINDI_TMP/post-nuke.tgz 2>> $MINDI_TMP/$$.log || LogAll "ERROR: when untarring post-nuke tarball" $MINDI_TMP/$$.log
			cd "$old_pwd"
		fi
 		if cp -f $MINDI_TMP/mondo*restore $bigdir/usr/bin 2>> $LOGFILE ; then
	    	LocateDeps $bigdir/usr/bin/mondo*restore >> $outfile.pre
		else
			LogIt "ERROR: Cannot find mondo*restore in mondo's tempdir, $MINDI_TMP"
			LogIt "       I bet you've got a spare copy of Mondo or Mindi floating around on your system."
	    	LogIt "       If Mindi was called by Mondo then send me a bug report."
			LogIt "       It not, type 'ps ax' to see which Mondo-related process is still running then kill it. :-)"
			LogIt "       Finally, run Mindi again."
	    	Die "Odd."
		fi
		cp -f $MINDI_TMP/BOOTLOADER.* $bigdir 2>> $LOGFILE || LogIt "\nINFO: Mondo v1.2x defaults to LILO as the bootloader, BTW."
		if [ -e "$MINDI_TMP/NETFS-SERVER-MOUNT" ] ; then
			LogAll "\nINFO: Incorporating Network-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 "INFO: 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
}


# 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 "INFO: GetInitrdFilesystemToUse(): called with parameter: $lvKernelImage"

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

	# Kernel may be gzip compressed - Case of RHEL5 - SLES11SP1
	file $lvKernelImage 2>&1 | grep -q gzip
	if [ $? -eq 0 ]; then
		LogFile "INFO: Found a gzip compressed kernel $lvKernelImage"
		lvScanRes=`gzip -cd $lvKernelImage | strings | grep -E "$lcMagicCramfs|$lcMagicExt2fs|$lcMagicExt3fs|$lcMagicInitfs" 2> /dev/null`
	else
		LogFile "INFO: Found a non gzip compressed kernel $lvKernelImage"
		# kernel is x86 boot sector in RHEL3/4 with embedded gzip content
		# get offet of gzip magic "1f8b0800" in file (for these older kernels)
		lvOffset=`od -vA n -t x1 $lvKernelImage | tr -d '[:space:]' | awk '{ print match($0, "1f8b0800")}' 2> /dev/null`
		if [ $lvOffset -eq 0 ]; then
			LogFile "INFO: gzip magic not found in file $lvKernelImage. Supposing initramfs."
			lvScanRes=$lcMagicInitfs
		else
			lvOffset=`expr $lvOffset / 2`
			LogFile "INFO: GetInitrdFilesystemToUse(): gzip magic found at lvOffset $lvOffset."
			# scan again  kernel image
			lvScanRes=`dd ibs=1 skip=$lvOffset if=$lvKernelImage obs=1M 2>/dev/null | gunzip -c 2> /dev/null | strings | grep -E "$lcMagicCramfs|$lcMagicExt2fs|$lcMagicExt3fs|$lcMagicInitfs" 2> /dev/null`
		fi
	fi

	# 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
		# In that case, we are most probably after 2.6.30 and use the supported initramfs 
		LogFile "WARNING: No automatic detection found previously. Supposing initramfs."
		LogFile "WARNING: Report on the MondoRescue mailing-list with your log files and the result of"
		LogFile "WARNING: dd ibs=1 skip=$lvOffset if=$lvKernelImage obs=1M 2>/dev/null | gunzip -c 2> /dev/null | strings | grep initramfs"
		lvUseFilesystem="initramfs"
	fi

	# say what we are using
	LogFile "INFO: GetInitrdFilesystemToUse(): Filesytem to use for initial ram disk is $lvUseFilesystem."

	# return file system to use
	echo "$lvUseFilesystem"

}

# Searches members of raid device
# $1: raid device (/dev/md...)
GetRaidDevMembers() {
	if [ ! -f /etc/raidtab ]; then 
		return
	fi
	$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 r kern
	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' ' '`
	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
###
	# Get rid of duplicates
	for module in `echo $module_list | 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
		else
			[ -f "$r" ] && echo "$r"
		fi
		LogFile "INFO: module $module --> $r"
	done
	find /lib/modules/$kern/modules.* -type f 2> /dev/null
}

#
# Critical function which computes all dependencies (dyn. lib.) 
# for a list of binaries
#
LocateDeps() {
	local incoming fname deps
	incoming="$*"
	deps=""

	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
		else
			deps="$deps $fname" 
		fi
	done
	mr-read-all-link `mr-process-ldd $deps | sort -u` | sort -u
}


LocateFile() {
	local i j path fname_to_find location output resolved tmp stub cache_id loclist
	fname_to_find="$1"
	# It's an absolute path
	j=`echo "$fname_to_find" | cut -c1`
	if [ _"$j" = _"/" ]; then
		dn=`dirname $fname_to_find`
		# We suppose that the link is already included, just add the new file
		if [ -h "$dn" ]; then
			newdn=`readlink -f $dn`
			bn=`basename $fname_to_find`
			output="$newdn/$bn"
		else
			output="$fname_to_find"
		fi
		if [ -h "$output" ] ; then
			output="`mr-read-all-link $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="`mr-read-all-link $path/$fname_to_find` $output"
		fi
	done
	if [ "$output" = "" ] ; then
		return 1
	fi
	echo "$output"
	return 0
}

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

	i=$(($progress*100))
	if [ $noof_lines -ne 0 ]; then
		i=$(($i/$noof_lines))
	else
		i=0
	fi

	if [ _"$MONDO_SHARE" != _"" ]; then 
		echo "$title		$i%"
	else
		echo -en "\r\t\t\t\t\t\t\t\t"
		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|"
	fi
}

# Called by TurnTgzIntoRdz, to make /tmp/$MRCFG
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-gzip $use_gzip" >> $outfile
	echo "use-star $use_star" >> $outfile
	echo "use-lzma $use_lzma" >> $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/ISO-DEV           iso-dev           $outfile
	AddFileToCfgIfExists $MINDI_TMP/ISO-MNT           iso-mnt           $outfile
	AddFileToCfgIfExists $MINDI_TMP/ISO-PREFIX        iso-prefix        $outfile
	AddFileToCfgIfExists $MINDI_TMP/ISO-DIR           iso-dir           $outfile
	AddFileToCfgIfExists $MINDI_TMP/BOOTLOADER.DEVICE bootloader.device $outfile
	AddFileToCfgIfExists $MINDI_TMP/BOOTLOADER.NAME   bootloader.name   $outfile
	AddFileToCfgIfExists $MINDI_TMP/BOOTLOADER.VER    bootloader.ver    $outfile
	AddFileToCfgIfExists $MINDI_TMP/TAPEDEV-HAS-DATA-DISKS tapedev-has-data-disks $outfile
	AddFileToCfgIfExists $MINDI_TMP/BACKUP-MEDIA-TYPE backup-media-type $outfile
	AddFileToCfgIfExists $MINDI_TMP/DIFFERENTIAL      differential      $outfile
	AddFileToCfgIfExists $MINDI_TMP/ACL               acl               $outfile
	AddFileToCfgIfExists $MINDI_TMP/XATTR             xattr             $outfile
	AddFileToCfgIfExists $MINDI_TMP/OBDR              obdr              $outfile

	# Deal with network configuration in a portable way
	if [ -f $MINDI_TMP/NETFS-SERVER-MOUNT ]; then
		mr-net-get-config `cat $MINDI_TMP/NETFS-SERVER-MOUNT` >> $outfile
	fi
}

# Get PV's for an LV
GetPVsForLV() {
  if [ -n "$1" ]; then
    vg=`$LVMCMD lvdisplay $1 2>/dev/null |awk '/VG Name/{print $NF;exit}'`
    if [ -z "$vg" ]; then
      return
    fi
    $LVMCMD vgdisplay -v $vg 2>/dev/null | awk '/PV Name/{print $NF}'
  fi
}


MakeMountlist() {
	local 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 "-----------------------------------"

# mountlist(OUT)
	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
		LogAll "INFO: Analyzing LVM..."
		$MINDI_LIB/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 %-13s %-15s\n" DEVICE MOUNTPOINT FORMAT "SIZE MB" LABEL/UUID | tee -a $LOGFILE
	printf "%-15s %-15s %-15s %-13s %-15s\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 tmpfs devpts sysfs proc debugfs"
	for c_p in $all_partitions ; do
		# Skip fd/cd devices, network FS, cifs
		[ "`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`
			if [ "`echo "$current_partition" | grep -F "/dev/mapper"`" != "" ]; then
				current_partition="$c_p"
			elif [ "`echo $current_partition | grep -E '^/dev/dm-'`" ]; then
				# For SLES 11 type of distro, do not use dm devices as they are unable to be handled by lvm commands
				current_partition=`$MINDI_LIB/analyze-my-lvm --givevglvofdm $current_partition`
			fi
			[ "`echo "$useless_dev" | grep -F "$current_partition"`" ] && continue
		else
			current_partition="$c_p"
		fi
		[ "$c_p" = "none" ] && continue
		redhat_label=""
		label=""
		uuid=""
		absolute_partition=`readlink -f $c_p`
		partition_mountpt=`tr -s '\t' ' ' < $MY_FSTAB | grep -w "$current_partition" | grep -vx " *#.*" | $AWK '{print $2}' | head -n1`

		# 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" | 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 | 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 | 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 | grep "/dev/" | $AWK '{ print $1 }' `
				for dev_swap in $list_swaps ; do
					dev_exists=`/sbin/vol_id $dev_swap | 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 | 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
					[ "`echo $uname | grep "3.[0-9]*.[0-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" | 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 | 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 | grep -E '^/' | $AWK '{ print $1 }' `
				for dev in $list_dev ; do
					dev_exists=`/sbin/vol_id $dev | 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 | grep -E '^/' | $AWK '{ print $1 }' `
				for dev in $list_dev ; do
					dev_exists=`/sbin/dumpuuid $dev | 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 | grep -Ev "^#" | $AWK '{print $1}'`; do
						if [ _"`readlink -f $tmpp`" = _"`readlink -f $current_partition`" ]; then
							str_to_find_fmt_with=$tmpp
							partition_mountpt=`tr -s '\t' ' ' < $MY_FSTAB | grep -w "$tmpp" | grep -vx " *#.*" | $AWK '{print $2}' | head -n1`
							break;
						fi
				done
			fi
		fi

		# Detects noauto partitions not mounted and exclude them
		partition_option=`tr -s '\t' ' ' < $MY_FSTAB | grep -w "$str_to_find_fmt_with" | grep -vx " *#.*" | $AWK '{print $4}' | head -n1`
		if [ "`echo "$partition_option" | grep -i noauto`" != "" ] && [ "`mount | grep -w "$partition_mountpt"`" =  "" ] ; then
	    		LogFile "INFO: Excluding $current_partition from mountlist (due to noauto option in fstab)"
			continue
		fi
		# Detects bind partitions and exclude them
		if [ "`echo "$partition_option" | grep -iw bind`" != "" ]; then
	    		LogFile "INFO: Excluding $current_partition from mountlist (due to bind option in fstab)"
			continue
		fi

		# Look for devices which have to be excluded
		skip=0
		if [ "$MINDI_EXCLUDE_DEVS" ] ; then
			l=""
			list_of_devices="`mr-read-all-link $current_partition`"
			for d in $list_of_devices; do
				l="$l `$MINDI_LIB/analyze-my-lvm --givemapperofdm $d`"
			done

			# Remove PVs from LVs excluded
			l="$l `GetPVsForLV $current_partition`"

			# We want a single unique list
			list_of_devices="`echo $l | sort -u`"

			for d in `echo $MINDI_EXCLUDE_DEVS | sed 's/|/ /g'`; do
				if  [ "`echo " $list_of_devices " | grep " $d"`" != "" ]; then
	    			LogFile "INFO: Excluding $current_partition from mountlist (due to excluded device $d)"
					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`
		# Detects iso9660 ISO images and exclude them
		if [ "`echo "$partition_format" | grep -iw iso9660`" != "" ]; then
	    		LogFile "INFO: Excluding $current_partition from mountlist (due to iso9660 format in fstab)"
			continue
		fi
		# 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
			[ "`echo "$current_partition" | grep "[0-9]"`" = "" ] && continue
			[ "`echo "$current_partition" | grep -c "^/"`" -ne "1" ] && continue
			if [ "$partition_format" = "swap" ] || [ "$partition_mountpt" = "swap" ] ; then
				# Skip swap files
				[ "`echo "$current_partition" | grep -E "^/dev"`" = "" ] && continue
				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 "INFO: I'm guessing $c_p is $(($partition_size/1024))MB"
				fi
			else
				partition_size=`SizeOfPartition $current_partition`
			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 "INFO: 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 "WARNING: Are you imaging a mounted swap partition? Silly..."
	        	LogFile "WARNING: 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 "WARNING: Unable to find mountpoint of $current_partition - ignoring"
				continue
			fi
		fi
		if [ "$redhat_label" ]; then
			label="$redhat_label"
		elif [ "$uuid" ]; then
			label="$uuid"
		fi

		# On RHEL 7 they use UUID concretely, even when not mentioned in fstab
		# in order to mount the root part e.g. in grub.
		# One way to solve this is to add the UUID now, if there wasn't one so it's
		# restored correctly
		if [ _"$label" = _"" ]; then
			label=`blkid $current_partition | perl -p -e 's/.* UUID="([A-z0-9-]+)" .*/$1/'`
		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 "WARNING: 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 "WARNING: Unknown mountpoint (outstring = $unofficial_outstring)"
			fi
		elif [ "$partition_format" = "" ] ; then
			LogFile "WARNING: Unknown format (outstring = $unofficial_outstring)"
		elif [ "$partition_size" = "" ] ; then
			LogFile "WARNING: 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 "WARNING: 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=`grep -vE ' lvm | raid | swap ' $file | wc -l`
	ML1=`$AWK '{print $1}' $file | sort -u | wc -l`
	ML2=`grep -vE ' lvm | raid | swap ' $file | $AWK '{print $2}' | sort -u | wc -l`
	if [ "$ML01" -ne "$ML1" ]; then
		LogFile "--------------------------------------------"
		LogAll "WARNING: Duplicate device entry in mountlist"
		LogFile "--------------------------------------------"
	fi
	if [ "$ML02" -ne "$ML2" ]; then
		LogFile "--------------------------------------------"
		LogAll "WARNING: Duplicate mountpoint entry in mountlist"
		LogFile "------------------------------------------------"
	fi
}

OfferToMakeBootableISO() {
	local i old_pwd
	if [ -z "$ISO_CMD" ]; then
		LogAll "ERROR: 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}
	LogFile "INFO: mindi_lib = $MINDI_LIB"
	cp -f $MINDI_CACHE/{*.gz,*.img} $MINDI_TMP/iso/images 2>> $LOGFILE || LogAll "WARNING: OfferToMakeBootableISO: Cannot copy $MINDI_CACHE/*.gz to $MINDI_TMP/iso/images"
	for i in memdisk memtest.bin memtest.img ; do
		j=$MINDI_LIB/$i
		k=$MINDI_TMP/iso
		if [ -e "$j" ] ; then
			LogAll "INFO: 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 | cut -c1-80 > $MINDI_TMP/iso/message.txt
	if [ $KERNEL_IS_XEN = "yes" ]; then
		FindMboot32Binary 
		cp $xenkernelpath $MINDI_TMP/iso/xen.gz 2>> $LOGFILE || Die "Cannot copy xen.gz ($xenkernelpath) to mindi tmp ($MINDI_TMP/iso/xen.gz). Did you run out of disk space?"
		cp $MBOOTC32 $MINDI_TMP/iso/mboot.c32  2>> $LOGFILE || Die "Cannot copy mboot.c32 ($MBOOTC32) to mindi tmp ($MINDI_TMP/iso/mboot.c32). Did you run out of disk space?"
	fi
	# Useful for syslinux 5.x
	FindLdlinux32Binary
	if [ -e $LDLINUXC32 ]; then
		cp $LDLINUXC32 $MINDI_TMP/iso/ldlinux.c32  2>> $LOGFILE || Die "Cannot copy ldlinux.c32 ($LDLINUXC32) to mindi tmp ($MINDI_TMP/iso/ldlinux.c32). Did you run out of disk space?"
	fi
	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 
		if [ $KERNEL_IS_XEN = "yes" ]; then
			cp $xenkernelpath $MONDO_ROOT/xen.gz 2>> $LOGFILE || Die "Cannot copy xen.gz ($xenkernelpath) to mindi tmp ($MONDO_ROOT/xen.gz). Did you run out of disk space?"
			cp $MBOOTC32 $MONDO_ROOT/mboot.c32  2>> $LOGFILE || Die "Cannot copy mboot.c32 ($MBOOTC32) to mindi tmp ($MONDO_ROOT/mboot.c32). Did you run out of disk space?"
		fi
		if [ -e $LDLINUXC32 ]; then
			cp $LDLINUXC32 $MONDO_ROOT/ldlinux.c32  2>> $LOGFILE || Die "Cannot copy ldlinux.c32 ($LDLINUXC32) to $MONDO_ROOT/ldlinux.c32. Did you run out of disk space?"
		fi
		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,boot*.txt,pxe.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?"
			if [ -e $MINDI_TMP/iso/ldlinux.c32 ]; then
				cp $MINDI_TMP/iso/ldlinux.c32 $MONDO_ROOT 2>> $LOGFILE || Die "Cannot copy ldlinux.c32 (from $MINDI_TMP/iso/$LDLINUXC32) to $MONDO_ROOT. Did you run out of disk space?"
			fi
			if [ $KERNEL_IS_XEN = "yes" ]; then
				cp -f $MINDI_TMP/iso/{mboot.c32,xen.gz} $MONDO_ROOT 2>> $LOGFILE || Die "Cannot copy Xen core files to ramdisk for boot disk (under $MONDO_ROOT). Did you run out of disk space?"
			fi
			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
	fi
	if [ "$?" -ne "0" ] ; then
		LogFile "----------- $ISO_CMD's errors --------------"
		LogAll "$ISO_CMD returned the following errors:"
		cat $MINDI_TMP/mkisofs.log | tee -a $LOGFILE
		LogAll "ERROR: Failed to create ISO image."
	else
		LogAll "INFO: 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 device ? (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 "INFO: Transforming $USBDEVICE in a Bootable device"
	LogFile "INFO: Checking $USBDEVICE"
	$FDISK -l $USBDEVICE 2>&1 >> $LOGFILE
	if [ $? -ne 0 ]; then
		LogAll "ERROR: Unable to access $USBDEVICE"
		LogAll "       Make sure your USB device is plugged in"
		MindiExit -1
	fi
	echo -en "."
	# Some distro do auto mount at that point (Ubuntu)
	LogFile "INFO: 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
	if [ -r $MBRFILE ]; then
		LogAll "INFO: Installing an MBR ($MBRFILE) on $USBDEVICE"
		dd if=$MBRFILE of=$USBDEVICE
	else
		LogAll "WARNING: You may need to install an MBR (usually in $MBRFILE, but not found on your system)"
		LogAll "         on $USBDEVICE with dd if=$MBRFILE of=$USBDEVICE"
	fi
	LogFile "INFO: Preparing $USBDEVICE"
	cat > $MINDI_TMP/fdisk.txt << EOF
d
d
d
d
n
p
1


t
b
a
1
w
EOF
	$FDISK $USBDEVICE 2>> $LOGFILE 1>> $LOGFILE < $MINDI_TMP/fdisk.txt
	if [ $? -ne 0 ]; then
		LogAll "ERROR: Unable to create a vfat Filesystem on $USBDEVICE"
		LogAll "       Make sure your USB device is plugged in"
		$FDISK -l $USBDEVICE 2>&1 | tee -a $LOGFILE
		MindiExit -1
	fi
	LogFile "fdisk build file"
	LogFile "----------------"
	cat $MINDI_TMP/fdisk.txt >> $LOGFILE
	LogFile "----------------"
	rm -f $MINDI_TMP/fdisk.txt
	LogFile "INFO: The USB device $USBDEVICE now looks like this:"
	$FDISK -l $USBDEVICE 2>&1 | tee -a $LOGFILE
	echo -en "."
	# Calling kpartx in case devices were not created
	if [ -x "/sbin/kpartx" ]; then
		/sbin/kpartx -a $USBDEVICE
	fi
	# Some distro do auto mount at that point (Ubuntu)
	LogFile "INFO: Unmounting $USBPART just in case again"
	umount $USBPART 2>> $LOGFILE 1>> $LOGFILE
	echo -en "."
	# Some distro have a dmsetup conf at that point so removing it Cf: http://trac.mondorescue.org/ticket/651
	if [ "`which dmsetup`" != "" ]; then
        block_id="`echo $USBPART | sed 's|/dev/||g'`"
        if [[ "`dmsetup ls | awk '{print $1}' | grep $block_id`" != "" ]]; then
            LogFile "INFO: Removing $block_id from device mapper."
            sleep 1
            dmsetup remove $block_id
        fi
    fi
	echo -en "."
	LogFile "INFO: Creating a vfat filesystem on $USBPART"
	mkdosfs -F 32 $USBPART 2>&1 >> $LOGFILE
	if [ $? -ne 0 ]; then
		LogAll "ERROR: Unable to create a vfat filesystem on $USBPART"
		LogAll "       Make sure your USB device is plugged in and partitioned ($USBPART must exist on it)"
		$FDISK -l $USBDEVICE 2>&1 | tee -a $LOGFILE
		MindiExit -1
	fi
	echo -en "."
	LogFile "INFO: Mounting $USBPART on $MINDI_TMP/usb"
	mount $USBPART $MINDI_TMP/usb 2>> $LOGFILE
	if [ $? -ne 0 ]; then
		LogAll "ERROR: Unable to mount $USBPART on $MINDI_TMP/usb"
		LogAll "       Make sure your USB device is plugged 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 "ERROR: OfferToMakeBootableUSB: Cannot copy $i to $MINDI_TMP/usb/images"
	echo -en "."
	LogFile "INFO: mindi_lib = $MINDI_LIB"
	for i in memdisk memtest.bin memtest.img ; do
		j=$MINDI_LIB/$i
		k=$MINDI_TMP/usb
		if [ -e "$j" ] ; then
			LogIt "INFO: 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 | cut -c1-80 > $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 -v 2>&1 | grep -q 4.02
		if [ $? -eq 0 ]; then
			# This buggy version of syslinux requires a call to --stupid and not -s
			syslinux --stupid $USBPART 2>> $MINDI_TMP/syslinux.log
			res=$?
		else
			syslinux -s $USBPART 2>> $MINDI_TMP/syslinux.log
			res=$?
		fi
		if [ $res -ne 0 ] ; then
			LogAll "----------- syslinux's errors --------------"
			cat $MINDI_TMP/syslinux.log |tee -a $LOGFILE
			LogAll "------------------------------------------"
			LogIt "ERROR: Failed to create USB image."
		else
			echo -e "$DONE"
			LogFile "INFO: Created bootable USB image on $USBDEVICE"
		fi
		rm -f $MINDI_TMP/syslinux.log
	else
		LogAll "ERROR: 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 [ -r /etc/arch-release ]; then  # this code must be written before /etc/issue test to avoid errors
		DESC="Arch Linux"
		if [ -r /var/log/pacman.log ]; then
			# there are no releases but we can get the last system upgrade
			# Output example:   Arch Linux [2011-03-03 01:39]
			DESC="$DESC $(tac /var/log/pacman.log | grep -m1 'full system upgrade' | cut -d']' -f1)]"
		fi
	elif [ -r /etc/issue.net ]; then
		DESC=`head -1 /etc/issue.net`
	elif [ -r /etc/issue ]; then
		DESC=`head -1 /etc/issue`
	elif [ -x "/usr/bin/pbdistrocheck" ]; then
		# For pb >= 0.9.8
		DESC=`/usr/bin/pbdistrocheck -s | cut -d, -f1-4`
	else
		DESC="Unknown desc"
	fi
	sed "s/ZZZZZ/$MINDI_VERSION/" $MINDI_LIB/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-SERVER-MOUNT" ] ; then
				echo -en "Press <0eenter07> for 0cnetwork restore07\n"
				echo -en "$BOOT_MEDIA_MESSAGE"
			elif [ ! "$MINDI_TMP" ] ; then
				echo -en "FYI, this is _not_ a Mondo Rescue CD.\n"
		    	if [ -e "$MINDI_LIB/memtest.img" ] ; then
		       	 echo -en "Type 'memtest' <Enter> to test your PC's memory intensively.\nJust press <Enter> to go to the main test menu.\n"
		    	fi
			else
				echo -en "$BOOT_MEDIA_MESSAGE"
			fi
		else
			echo -en "\
To restore your disk to factory defaults, type 'RESTORE' <enter>.\n\
CAUTION: THIS WILL ERASE YOUR WHOLE DISK !!!\n"
		fi
	fi

	# Also create the other help screens
	head -24 $MINDI_CONF/README.bootparam | cut -c1-80 > $1/boot1.txt
	head -48 $MINDI_CONF/README.bootparam | tail -24 | cut -c1-80 > $1/boot2.txt
	head -24 $MINDI_CONF/README.pxe | cut -c1-80 > $1/pxe.txt
}


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\nF1 message.txt\nF2 boot1.txt\nF3 boot2.txt\nF4 pxe.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-SERVER-MOUNT" ] ; then
			echo -en "default${sep}iso\n"
		else
			echo -en "default${sep}${MINDI_DEFAULT_BOOT_OPTION}\n"
		fi
	else
		echo -en "default${sep}expert\n"
	fi

	# Handle timeout
	if [ "$CDRECOVERY" != "yes" ] ; then
		echo -en "timeout${sep}${MINDI_BOOT_TIMEOUT}\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="RESTORE 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
			if [ $KERNEL_IS_XEN = "no" ]; then
				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"
			else
				outstr="label $i\n\tkernel ${ps}mboot.c32\n\tappend ${ps}xen.gz --- ${ps}vmlinuz root=/dev/ram0 rw ramdisk_size=$ramdisk_size  ${ooo} $MINDI_ADDITIONAL_BOOT_PARAMS --- ${ps}initrd.img\n"
			fi
		fi
		echo -en "$outstr"
	done
	if [ -e "$MINDI_LIB/memtest.img" ] ; then
		if [ "$type" = "elilo" ]; then
			echo -en "image=/memtest.bin\n\tlabel=memtest\n"
			echo -en "image=/memdisk\n\tlabel=memdisk\nappend=\"initrd=memtest.img\"\n"
		else
			ps="/"
			if [ "$type" = "syslinux" ]; then
				ps=""
			fi
			echo -en "label memtest\n\tkernel ${ps}memtest.bin\n"
			echo -en "label memdisk\n\tkernel ${ps}memdisk\nappend initrd=${ps}memtest.img\n"
		fi
	fi
}


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

	retval=0

	old_pwd=`pwd`
	[ ! -e "$kernelpath" ] && Die "PBDI lilo - cannot find $kernelpath kernel"
	echo -en "Making "$BOOT_SIZE"KB boot disk..."
	TurnTgzIntoRdz $MINDI_LIB/rootfs $MINDI_TMP/initrd.img `du -sk $kernelpath | cut -f1` || Die "Could not turn rootfs into initrd.img; are you SURE your kernel supports loopfs?"
	echo -en "..."
	imagefile=$imagesdir/mindi-bootroot.$BOOT_SIZE.img
	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
	mount -t vfat -o loop $imagefile $mountpoint || LogAll "ERROR: Cannot mount (PBDI)"

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

	MakeBootConfFile elilo > $liloconf

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

	LogFile "INFO: Copying $MINDI_TMP/initrd.img to $mountpoint..."
	cp -f $MINDI_TMP/initrd.img $mountpoint 2>> $LOGFILE
	if [ "$?" -ne "0" ] ; then
		LogIt "ERROR: Failed to copy $MINDI_TMP/initrd.img to $mountpoint"
		cat $MINDI_TMP/mtpt.$$ >> $LOGFILE
		LogIt "       Please unload some of your modules and try again. Or increase EXTRA_SPACE and BOOT_SIZE in $MINDI_CONFIG"
		rm -f $MINDI_TMP/mtpt.$$
		LogIt "ERROR: Cannot incorporate initrd.img in bootdisk (kernel / modules too big?)"
		retval=$(($retval+1))
	fi
	MakeMessageFile $mountpoint | cut -c1-80 > $mountpoint/message.txt

	mkdir -p $mountpoint/tmp
	if [ -f "$MINDI_TMP/$MRCFG" ]; then
		cp -f $MINDI_TMP/$MRCFG $mountpoint/tmp
	fi

	# copy the kernel across
	[ "$mountpoint" != "" ] && rm -Rf $mountpoint/lost+found
	dd if=/dev/zero of=$mountpoint/zero bs=1k count=16 &> /dev/null
	free_space=`df -k -P $mountpoint | tail -n1 | tr -s ' ' '\t' | cut -f4`
	cp -f $kernelpath $mountpoint/vmlinuz > /dev/null 2>> $LOGFILE
	if [ "$?" -ne "0" ] ; then
		LogFile "INFO: 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" >> $LOGFILE
		[ "$mountpoint" != "" ] && rm -f $mountpoint/vmlinuz
		cd "$old_pwd"
		umount $mountpoint || Die "Cannot unmount mountpoint ($mountpoint)"
		rmdir $mountpoint || LogIt "ERROR: Cannot rmdir (PBDI)"
	#	losetup /dev/loop0 -d
		[ "$imagefile" != "" ] && rm -f $imagefile
		LogIt "ERROR: Sorry, your kernel is too big for your image"
		Die "Try to increase EXTRA_SPACE and BOOT_SIZE in $MINDI_CONFIG"
		return 0
	fi
	max_kernel_size=$(($free_space+`du -sk $kernelpath | cut -f1`))
	LogFile "INFO: Free space left on image = $free_space KB"
	LogFile "INFO: Max kernel size on $BOOT_SIZE KB image (est'd) = $max_kernel_size K"
	# make it bootable
	[ "$mountpoint" != "" ] && rm -f $mountpoint/zero
	[ -e "$MINDI_LIB/memdisk" ] && cp -f $MINDI_LIB/memdisk $mountpoint 2>> $LOGFILE
	if [ "$KERN_DISK_MADE" ] ; then
		LogFile "INFO: Not running LILO. It's not that kind of disk."
	fi

	cp `dirname $kernelpath`/*.efi $mountpoint 2>> $LOGFILE
	umount $mountpoint || Die "Cannot unmount mountpoint ($mountpoint)"
	echo -en "..."
	rmdir $mountpoint || LogIt "ERROR: Cannot rmdir (PBDI)"
	if [ "$retval" -eq "0" ] ; then
		echo -en "...$DONE\n"
		if [ "$KERN_DISK_MADE" ] ; then
			LogIt "INFO: $BOOT_SIZE KB boot disks were created OK\n"
		fi
	else
		echo -en "...failed\n"
		LogIt "WARNING: $BOOT_SIZE""KB boot disk was NOT created\n"
		[ "$imagefile" != "" ] && rm -f $imagefile
	fi
	[ "$retval" -ne "0" ] && LogIt "WARNING: PrepareBootDiskImage() is returning nonzero"
	return $retval
}


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

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

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

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

	# copy Mindi's skeleton fs & lilo/syslinux/whatever stuff into it
	MakeMessageFile $mountpoint | cut -c1-80 > $mountpoint/message.txt
	MakeBootConfFile isolinux > $mountpoint/syslinux.cfg
	LogFile "INFO: 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 "ERROR: 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?)."
		LogAll "       Try to increase EXTRA_SPACE and BOOT_SIZE in $MINDI_CONFIG"
		retval=$(($retval+1))
	fi

	mkdir -p $mountpoint/tmp
	if [ -f "$MINDI_TMP/$MRCFG" ]; then
		cp -f $MINDI_TMP/$MRCFG $mountpoint/tmp
	fi

	# copy the kernel across
	[ "$mountpoint" != "" ] && rm -Rf $mountpoint/lost+found
	dd if=/dev/zero of=$mountpoint/zero bs=1k count=16 &> /dev/null
	free_space=`df -k -P $mountpoint | tail -n1 | tr -s ' ' '\t' | cut -f4`
         
	retval=0
	cp -f $kernelpath $mountpoint/vmlinuz &> /dev/null
	retval=$?
	if [ $KERNEL_IS_XEN = "yes" ]; then
		cp -f $xenkernelpath $mountpoint/xenkernel &> /dev/null
		let retval+=$?
	fi
 
	if [ "$retval" -ne "0" ] ; then
		LogFile "INFO: 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" >> $LOGFILE
		[ "$mountpoint" != "" ] && rm -f $mountpoint/vmlinuz
		cd "$old_pwd"
		umount $mountpoint || Die "Cannot unmount mountpoint ($mountpoint)"
		rmdir $mountpoint || LogAll "ERROR: Cannot rmdir (PBDI)"

		LogIt "ERROR: Sorry, your kernel is too big for your image"
		Die "Try to increase EXTRA_SPACE and BOOT_SIZE in $MINDI_CONFIG"
	fi
	max_kernel_size=$(($free_space+`du -sk $kernelpath | cut -f1`))
	LogFile "INFO: Free space left on image = $free_space KB"
	LogFile "INFO: Max kernel size on $BOOT_SIZE KB image (est'd) = $max_kernel_size K"

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

	if [ "$retval" -eq "0" ] ; then
		echo -en "...$DONE\n"
		if [ "$KERN_DISK_MADE" ] ; then
		    [ "$imagefile" != "" ] && rm -f $imagefile
		    LogAll "INFO: $BOOT_SIZE KB boot disks were created OK\n"
		fi
	else
		echo -en "...failed\n"
		LogAll "WARNING: $BOOT_SIZE""KB boot disk was NOT created\n"
		[ "$imagefile" != "" ] && rm -f $imagefile
	fi
	[ "$retval" -ne "0" ] && LogAll "ERROR: 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
	ListKernelModulePaths >> $needlist
	if [ "$res" -ne "0" ] ; then
		Die "You have $res files present in dependency list\nbut absent from filesystem."
	fi
	mkdir -p $bigdir/tmp
	if [ _"$MONDO_SHARE" != _"" ]; then
		# BCO: no reason to have the cfg file stored twice
		MakeMondoConfigFile $MINDI_TMP/$MRCFG
		cp -f $MINDI_TMP/$MRCFG $bigdir/tmp &> /dev/null
	fi

	# Needs to be done after the MRCFG creation
	FindAndAddUserKeyboardMappingFile

	[ -d "/mnt/.boot.d" ] && echo "GENTOO" > $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 "INFO: 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 "INFO: 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 "ERROR: issue 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 
		cp -a /lib/dev-state ./lib/ 2>> $MINDI_TMP/$$.log || LogAll "ERROR: Unable to handle /lib/dev-state" $MINDI_TMP/$$.log
	fi
	cd "$old_pwd"
	echo -e "$DONE"
	TOTAL_BIGDIR_SIZE=`du -sk $bigdir | cut -f1`
	MakeMountlist $MINDI_TMP/mountlist.txt
	CheckMountlist $MINDI_TMP/mountlist.txt
	mkdir -p $bigdir/tmp
	cp -f $MINDI_TMP/mountlist.txt $bigdir/tmp/mountlist.txt 2>> $LOGFILE || Die "Cannot copy mountlist.txt from $MINDI_TMP to data disk"
	if [ _"$MONDO_SHARE" != _"" ]; then
		cp -f $bigdir/tmp/mountlist.txt $MINDI_TMP/. 2>> $LOGFILE
	fi
	if [ $LVM != "false" ]; then
		$MINDI_LIB/analyze-my-lvm > $bigdir/tmp/i-want-my-lvm 
		if [ "$?" -ne "0" ]; then
			LVM="false"
			rm -f $bigdir/tmp/i-want-my-lvm
		else
			LogFile "Your i-want-my-lvm file content is:"
			LogFile "-----------------------------------"
			cat  $bigdir/tmp/i-want-my-lvm >> $LOGFILE
			LogFile "-----------------------------------"
		fi
	fi
	LogFile "Your mountlist.txt file content is:"
	LogFile "-----------------------------------"
	cat $bigdir/tmp/mountlist.txt >> $LOGFILE
	LogFile "-----------------------------------"

	echo -en "$FILES_IN_FILELIST" > $bigdir/FILES-IN-FILELIST 2>> $LOGFILE
	echo -en "$LAST_FILELIST_NUMBER" > $bigdir/LAST-FILELIST-NUMBER 2>> $LOGFILE
	if [ _"$MONDO_SHARE" != _"" ]; then
		for q in filelist.full.gz biggielist.txt ; do
		    [ ! -e "$MINDI_TMP/$q" ] && Die "Cannot find $MINDI_TMP/$q"
		    cp -pRdf $MINDI_TMP/$q $bigdir/tmp 2>> $LOGFILE
		done
	fi

	echo -en "Tarring and zipping the data content..."
	size_of_all_tools=`du -sk $bigdir | cut -f1`
	(cd "$bigdir" ; tar -b 4096 -cf - . 2>> $MINDI_TMP/$$.log | gzip -9 > $imagesdir/all.tar.gz || LogAll "ERROR: 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
}


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 -E "^/dev/"`" = "" ] ; then
		Die "Cannot find $device's size - is your /etc/fstab sane?"
	fi
	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
}


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 "INFO: 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 -E "[2-9]+\.[0-9]+\.[0-9]+[^\@]*@"`
		else
		    fkern_ver=`strings $fname 2> /dev/null | grep -E "[2-9]+\.[0-9]+\.[0-9]+[^\@]*@"`
		fi
		echo "$fkern_ver"
}


# WARNING: This function should just echo the final result !!!
#
TryToFindKernelPath() {
	local fname fkern_ver we_want_version possible_kernels noof_kernels possible_xenkernels noof_xenkernels kp kdate duff_kernels output root

	we_want_version=$KERVERRUN
	possible_kernels=""
	duff_kernels=""
	output=""
   
	if [ "$ARCH" = "ia64" ] ; then
	   root="/boot/efi/efi"
	else
	   root="/"
	fi
	# See if we're booted from a Xen kernel
	# From http://wiki.xensource.com/xenwiki/XenCommonProblems#head-26434581604cc8357d9762aaaf040e8d87b37752
	if [ -f /proc/xen/capabilities ]; then
		# It's a Xen kernel
		KERNEL_IS_XEN="yes"
		LogFile "INFO: It's a Xen kernel..."
	fi

	for fname in `find $root -maxdepth 2 -type f | grep -Ei 'lin|kern|xen' | grep -Ev '^/proc/|^/net/|^/mnt|^/lib|^/lib64|^/bin|^/sbin|^/usr|^/tmp'` ; 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
		    	LogFile "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
		    	LogFile "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-[23].* | tail -n1`
	fi
	if [ ! "$possible_kernels" ] ; then
		LogAll "INFO: No kernel matches exactly. Are there any duff kernels?"
		possible_kernels="$duff_kernels"
		if [ ! "$possible_kernels" ] ; then
		    LogAll "INFO: Sorry, no duff kernels either"
		else
		    LogAll "INFO: I bet you're running Debian or Gentoo, aren't you?"
		    LogAll "INFO: Your kernel doesn't have a sane builddate. Oh well..."
		fi
	fi
	if [ $KERNEL_IS_XEN = "yes" ]; then
		possible_xenkernels=`echo "$possible_kernels" | tr -s ' ' '\n' | grep -i "xen" | sort -u | tr '\n' ' '`
		noof_xenkernels=`CountItemsIn "$possible_xenkernels"`
	fi
	possible_kernels=`echo "$possible_kernels" | tr -s ' ' '\n' | grep -vi "xen" | 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 "INFO: Using /boot/vmlinuz as a last resort."
			output=/boot/vmlinuz
		else
			output=""
		fi
	elif [ "$noof_kernels" -eq "1" ] ; then
		kp=`echo "$possible_kernels" | sed s/' '//`
		LogFile "INFO: Your kernel is $kp (v$KERVERRUN)"
		output="$kp"
	else
		for i in $possible_kernels ; do
		    if [ "`echo $i | grep "$KERVERRUN"`" ]; then
				LogAll "INFO: OK, I used my initiative and found that "
				LogAll "INFO: $i is probably your kernel. "
				output="$i"
				break
			fi
		done
		if [ ! -n "$output" ]; then
			if [ "`echo " $possible_kernels " | grep -F "/boot/vmlinuz " &> /dev/null`" ]; then
				output=/boot/vmlinuz
				LogFile "INFO: Schlomo, this one's for you."
			else
		    	LogFile "INFO: Two or more possible kernels found. You may specify any one of them and the "
				LogFile "INFO: boot disks will still work, probably. If one does not work, try another."
		    	LogFile "INFO: $possible_kernels"
		    	output=""
			fi
		fi
	fi
	if [ $KERNEL_IS_XEN = "yes" ]; then
		if [ "$noof_xenkernels" -eq "0" ]; then
			xenkernelpath=""
		elif [ "$noof_xenkernels" -eq "1" ]; then
			xenkernelpath=`echo "$possible_xenkernels" | sed s/' '//`
			LogFile "INFO: Your Xen kernel is $xenkernelpath (v$KERVERRUN)"
		else
			for i in $possible_xenkernels ; do
		    	if [ "`echo $i | grep "$KERVERRUN"`" ]; then
					LogFile "INFO: OK, I used my initiative and found that "
				 	LogFile "INFO: $i is probably your Xen kernel. "
					xenkernelpath="$i"
					break
				fi
			done
			if [ ! -n "$xenkernelpath" ]; then
				new_possible_xenkernels=`echo "$possible_xenkernels" | tr -s ' ' '\n' | grep -E "^/boot" | sort -u | tr '\n' ' '`
				if [ ! -n "$new_possible_xenkernels" ]; then
					xenkernelpath=`echo $new_possible_xenkernels | tr -s ' ' '\n' | head -1`
					LogFile "INFO: Using $xenkernelpath"
				else
		    		LogFile "INFO: Two or more possible Xen kernels found. You may specify any one of them and the "
					LogFile "INFO: boot disks will still work, probably. If one does not work, try another."
		    		LogFile "INFO: $possible_xenkernels"
		    		output=""
					xenkernelpath=`echo $possible_xenkernels | tr -s ' ' '\n' | head -1`
					LogFile "INFO: Using $xenkernelpath"
				fi
			fi
		fi
		if [[ -z "$xenkernelpath" || ! -f "$xenkernelpath" ]]; then
			Die "Cannot find Xen kernel $xenkernelpath, aborting"
		fi
	fi
	LogAll "TryToFindKernelPath found $output"
	echo "$output"
}


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

	tgz_dir_fname=$1
	rdz_fname=$2
	kernelsize=$3
	maxsize=$(($BOOT_SIZE-$kernelsize))
	maxsize=$(($maxsize*2)); # to allow for compression of 50%
	tempfile=$MINDI_TMP/temp.rd
	res=0
	echo -en "..."
	dd if=/dev/zero of=$tempfile bs=1k count=$ramdisk_size &> /dev/null || Die "Not enough room for temporary ramdisk (TurnTgzIntoRdz)"
	echo -en "..."
	LogFile "INFO: Creating ext2 filesystem on $tempfile"
	mke2fs -b 1024 -m 1 -i 2048 -F $tempfile >> $LOGFILE 2>> $LOGFILE || Die "Unable to create an ext2 file system on $tempfile"
	echo -en "..."
	mkdir -p $mountpoint
	mount -t ext2 -o loop $tempfile $mountpoint || Die "Cannot loopmount $tempfile to $mountpoint! The reason may be missing support for loopfs or ext2 (or both) in the running kernel."
	echo -en "..."
	old_pwd=`pwd`
	cd "$mountpoint"

	# Check whether /lib64 or /lib or /sbin or /bin is a link and if so explicitly create one in rootfs (Fedora 17 crazyness)
	for d in bin sbin lib lib64; do
		if [ -h "/$d" ]; then
			thelink=`readlink /$d`
			mkdir -p $mountpoint/$thelink || LogIt "ERROR: Unable to create $thelink in $mountpoint."
			mv $mountpoint/$d/* $mountpoint/$d/.??* $mountpoint/$thelink 2> /dev/null
			if [ -d "$mountpoint/$d" -a ! -h "$mountpoint/$d" ]; then
				rmdir $mountpoint/$d
			fi
			if [ ! -h $mountpoint/$d ]; then
				rm -f $mountpoint/$d 2> /dev/null
				(cd $mountpoint ; ln -s $thelink $d) || LogIt "ERROR: /$d is a symbolic link, but I couldn't create it in $mountpoint."
			fi
		fi
	done
	LogFile "INFO: what is now in $mountpoint"
	ls -alR $mountpoint >> $LOGFILE
	
	# Check files before copying to discover configuration issues or McAfee preventing mindi reading these files
	for f in $tgz_dir_fname/*; do 
		if [ ! -r $f ]; then
			Die "ERROR: Unable to copy $f to the target dir. Check your installation or McAfee presence"
		else
			cp -Rdf $f . 2>&1 >> $LOGFILE
		fi
	done
	(cd etc ; ln -sf bashrc profile ; ln -sf bashrc shrc ; ln -sf ../proc/mounts mtab ; ln -sf ../usr/sbin/init linuxrc)
	ln -sf usr/sbin/init linuxrc

	cd dev || Die "Can't cd to dev"
	tar -zxf dev-entries.tgz || Die "Cannot untar dev-entries.tgz"
	rm -f dev-entries.tgz
	cd ..

	for w in insmod.static insmod.static.old ; do
		s=`which $w 2> /dev/null`
		if [ -e "$s" ] ; then
			tar cf - -C / $s 2> /dev/null | tar xf -
		fi
	done

	[ -e "/dev/.devfsd" ] && echo "/dev/.devfsd found" > tmp/USE-DEVFS
	
	# Copy of files mandatory for ssh to automate mount if sshfs is used
	mkdir $mountpoint/.ssh $mountpoint/tmp
	cp -a ~root/.ssh/* $mountpoint/.ssh 2> /dev/null
	cat > $mountpoint/tmp/myssh << EOF
ssh -o StrictHostKeyChecking=no $*
EOF
	chmod 755 $mountpoint/tmp/myssh

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

	# Handle the case where busybox and mount are dynamically linked
	file $MINDI_LIB/rootfs/usr/bin/busybox 2>&1 | grep -q "dynamically" 
	if [ $? -eq 0 ]; then
		# We want to use the real mount and all the supported variants (nfs, cifs, ...)
		rm -f bin/mount
	fi

	# Copy of files from the minimal env needed as per the deplist.d/minimal.conf & udev.conf file (which includes all busybox deps)
	rm -f $MINDI_TMP/minimal.lis $MINDI_TMP/minimal2.lis
	for f in `cat $DEPLIST_DIR/minimal.conf $DEPLIST_DIR/udev.conf | grep -vE " *#.*|^#" | sort -u` ; do
		if [ -d $f ]; then
			for g in `find $f`; do 
				echo $g >> $MINDI_TMP/minimal.lis
				LocateDeps $g  >> $MINDI_TMP/minimal2.lis
			done
		else 
			if [ -r $f ]; then
				echo $f >> $MINDI_TMP/minimal.lis
				LocateDeps $f >> $MINDI_TMP/minimal2.lis
			fi
		fi
	done
	for f in `cat $MINDI_TMP/minimal.lis` `sort -u $MINDI_TMP/minimal2.lis`; do
		mr-read-all-link $f >> $MINDI_TMP/minimal.lis
	done
	# Initial / are trucated by tar
	finallist=""
	# Remove directories from the list, as tar/cp will create them anyway
	# and it may hurt if /lib is in it as on Debian/Ubuntu
	# recent bash says that -d is true for a link to a dir !
	for f in `sort -u $MINDI_TMP/minimal.lis`; do
		if [ -e $f -a ! -d $f ] || [ -h $f ]; then
			finallist="$finallist $f"
		fi
	done
	#tar cf - $finallist 2>> $MINDI_TMP/$$.log | tar xf - || LogIt "WARNING: Problem in minimal analysis" $MINDI_TMP/$$.log
	echo "cp -a -n --parents $finallist -t $mountpoint" 2>&1 >> $MINDI_TMP/$$.log
	cp -a -n --parents $finallist -t $mountpoint 2>> $MINDI_TMP/$$.log || LogIt "WARNING: Problem in minimal analysis" $MINDI_TMP/$$.log

	# To improve support for distribution scripts, we now prefer to use bash as the std shell. Also fixes #600
	ln -sf /bin/bash bin/sh
	LogIt "INFO: Using bash as default shell"
	rm -f $MINDI_TMP/minimal.lis $MINDI_TMP/minimal2.lis

	# Avoids an issue on some distro (RHEL5)
	rm -f $mountpoint/etc/ld.so.conf.d/kernelcap*

	mkdir -p $mountpoint/tmp
	# Management of udev (which includes modprobe in rules)
	ps auxww | grep -v grep | grep -qw udevd
	if [ $? -eq 0 ]; then
		echo "udev device manager found" > $mountpoint/tmp/USE-UDEV
		LogIt "INFO: udev device manager found"
		tar cf - -C / /etc/udev 2>> $MINDI_TMP/$$.log | tar xf -  || LogIt "ERROR: Problem in /etc/udev analysis" $MINDI_TMP/$$.log
		# This avoids NIC remapping if on another machine at restore time on Debian/Ubuntu at least
		rm -f ./etc/udev/rules.d/[z]*[0-9][0-9][-_]persistent-net.rules
		# Do not do it if it's a link (Ubuntu 64 bits #503)
		if [ -e "/lib64/udev" ] && [ ! -h "/lib64" ] && [ ! -h "/lib64/udev" ]; then
			tar cf - -C / /lib64/udev 2>> $MINDI_TMP/$$.log | tar xf -  || LogIt "ERROR: Problem in /lib64/udev analysis" $MINDI_TMP/$$.log
		fi
		if [ -e "/lib32/udev" ] && [ ! -h "/lib32" ] && [  ! -h "/lib32/udev" ]; then
			tar cf - -C / /lib32/udev 2>> $MINDI_TMP/$$.log | tar xf -  || LogIt "ERROR: Problem in /lib32/udev analysis" $MINDI_TMP/$$.log
		fi
		if [ -e "/lib/udev" ] && [ ! -h "/lib" ] && [  ! -h "/lib/udev" ]; then
			tar cf - -C / /lib/udev 2>> $MINDI_TMP/$$.log | tar xf -  || LogIt "ERROR: Problem in /lib/udev analysis" $MINDI_TMP/$$.log
		fi
		if [ -e "/usr/lib/udev" ] && [ ! -h "/usr/lib" ] && [  ! -h "/usr/lib/udev" ]; then
			tar cf - -C / /usr/lib/udev 2>> $MINDI_TMP/$$.log | tar xf -  || LogIt "ERROR: Problem in /usr/lib/udev analysis" $MINDI_TMP/$$.log
		fi
		if [ -x /sbin/udevd ] || [ -x /usr/bin/udevd ] || [ -x /usr/lib/systemd/systemd-udevd ]; then
			lis2=`grep -Ev '^#' $DEPLIST_DIR/udev.conf`
			lis=""
			# Get only the files which exist in that list
			# and potentially their symlink structure
			for i in $lis2; do
				if [ -h $i ]; then
					j=$i
					while [ -h $j ]; do
						lis="$lis $j"
						j=`readlink -f $j`
					done
					lis="$lis $j"
				elif [ -f $i ]; then
					lis="$lis $i"
				fi
			done
			# And their deps
			LocateDeps $lis > $MINDI_TMP/udev.lis
			for i in $lis; do
				if [ "`echo $i | cut -c1`" = "/" ]; then
					j=`echo $i | cut -c2-`
					[ "$j" != "" ] && rm -f $j
				fi
				echo "$i" >> $MINDI_TMP/udev.lis
			done
			finallist=""
			# Remove directories from the list, as tar/cp will create them anyway
			# and it may hurt if /lib is in it as on Debian/Ubuntu
			# recent bash says that -d is true for a link to a dir !
			for f in `sort -u $MINDI_TMP/udev.lis`; do
				if [ -e $f -a ! -d $f ] || [ -h $f ]; then
					finallist="$finallist $f"
				fi
			done
			#tar cf - -C / $lis `sort -u $MINDI_TMP/udev.lis` 2>> $MINDI_TMP/$$.log | tar xf - || LogIt "ERROR: Problem in udev.lis analysis" $MINDI_TMP/$$.log
			echo "cp -a -n --parents $finallist -t $mountpoint/" 2>&1 >> $MINDI_TMP/$$.log
			cp -a -n --parents $finallist -t $mountpoint/ 2>> $MINDI_TMP/$$.log  || LogIt "ERROR: Problem in udev.lis analysis" $MINDI_TMP/$$.log
			rm -f $MINDI_TMP/udev.lis
		else
			LogAll "WARNING: udevd daemon not in standard place (/sbin or /usr/bin)"
			LogAll "         mindi will use static devices which may cause problems"
			rm -f $mountpoint/tmp/USE-UDEV
		fi
	fi

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

	# Management of perl scripts delivered needed at restore time
	mindi-get-perl-modules `cat $MINDI_CONF/perl-scripts` /usr/bin/mr-* > $MINDI_TMP/perl.lis
	tar cf - `cat $MINDI_TMP/perl.lis` 2>> $MINDI_TMP/$$.log | tar xf - || LogIt "ERROR: Problem in perl scripts analysis" $MINDI_TMP/$$.log

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

	tar cf - -C / /dev/fd0*[1,2][4,7,8]* 2>> $MINDI_TMP/$$.log | tar xf -  || LogIt "ERROR: Problem in fd dev analysis" $MINDI_TMP/$$.log

	echo -en "..."
	cd /

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

	if [ -e "$MINDI_TMP/NETFS-SERVER-MOUNT" ] ; then
		# For PXE boot
		list_of_groovy_mods="$list_of_groovy_mods $NET_MODS"
	fi
	for i in $DENY_MODS; do
		LogFile "INFO: 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

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

	[ -e "$needed_modules_path" ] || LogIt "WARNING: path $needed_modules_path does not exist.\n         If you're not using a modular kernel then mindi won't probably work."
	needed_modules=`mr-kernel-get-modules $mkgmopt $list_of_groovy_mods`

	LogFile "INFO: Adding $needed_modules to the rootfs with $mkgmopt"
	cp --parents -aL $needed_modules $mountpoint/ 2>> $MINDI_TMP/$$.log || LogIt "ERROR: Unable to copy modules to $mountpoint" $MINDI_TMP/$$.log

	# Uncompress modules if not using udev and native modprobe
	if [ ! -f $mountpoint/tmp/USE-UDEV ]; then
		for i in $needed_modules; do
			if [ "`echo "$i" | grep -E ".gz$"`" ]; then
				gunzip -f $mountpoint/$i
			fi
			if [ "`echo "$i" | grep -E ".bz$"`" ]; then
				bunzip2 -f $mountpoint/$i
			fi
			if [ "`echo "$i" | grep -E ".xz$"`" ]; then
				unxz -f $mountpoint/$i
			fi
			LogFile "INFO: Uncompressing $i"
		done
	fi

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

	# Copy FW in case some drivers needs it
	for d in "/lib" "/usr/lib"; do
		if [ -d "$d/firmware" -a ! -h $d ]; then
			cp -a "$d/firmware" "$mountpoint/$d"
		fi
	done

	# Copy multipath dynamic libraries in case multipath is used (RHEL 6.4 and later)
	for d in "/lib" "/usr/lib" "/lib64" "/usr/lib64"; do
		if [ -d "$d/multipath" -a ! -h $d ]; then
			cp -a "$d/multipath" "$mountpoint/$d"
		fi
	done

	# Ensure that with mindi-busybox 1.21, the links also exists under /bin for older distro which need it for their scripts
	(cd $mountpoint/usr/bin ; for i in `ls`; do if [ ! -e $mountpoint/bin/$i ]; then (cd $mountpoint/bin ; ln -sf ../usr/bin/$i .); fi; done)

	# Copy an additional ProLiant tool for OBDR support
	if [ -f $MINDI_TMP/OBDR ]; then
		found=0
		if [ -x /usr/bin/hpsa_obdr_mode ]; then
			mkdir -p $mountpoint/usr/bin
			cp -a /usr/bin/hpsa_obdr_mode $mountpoint/usr/bin
			LogIt "INFO: Copying /usr/bin/hpsa_obdr_mode to ramdisk for improved Smart Array OBDR support"
			found=1
		fi
		if [ -x /usr/bin/sg_wr_mode ]; then
			mkdir -p $mountpoint/usr/bin
			lis="/usr/bin/sg_map /usr/bin/sg_inq /usr/bin/sg_reset /usr/bin/rev"
			LocateDeps $lis > $MINDI_TMP/obdr.lis
			(cd $mountpoint ; tar cf - $lis -C /  `sort -u $MINDI_TMP/obdr.lis` 2>> $MINDI_TMP/$$.log | tar xf - || LogIt "ERROR: Problem in obdr.lis analysis" $MINDI_TMP/$$.log)
			LogIt "INFO: Copying /usr/bin/sg_reset to ramdisk for improved SCSI OBDR support"
			found=1
		fi
		if [ $found -eq 0 ]; then
			LogAll "WARNING: You're using OBDR mode without having the /usr/bin/hpsa_obdr_mode nor the /usr/bin/sg_wr_mode tool"
			LogAll "         This may lead to a tape not going back to sequential mode after OBDR boot"
		fi
	fi

	if [ ! -e "/sbin/devfsd" ] || [ "$kernelpath" = "$MINDI_LIB/vmlinuz" ] ; then
		LogFile "INFO: Deleting devfsd daemon from ramdisk"
		[ ! -e "/sbin/devfsd" ] && LogFile "      ...because /sbin/devfsd not found"
		rm -f $mountpoint/sbin/devfsd
	fi
	cd "$old_pwd"
	[ "$TAPEDEV" ] && echo -en "$TAPEDEV" > $mountpoint/tmp/TAPEDEV-LIVES-HERE
	if [ _"$MONDO_SHARE" != _"" ]; then
		MakeMondoConfigFile $mountpoint/tmp/$MRCFG
		cp -f $mountpoint/tmp/$MRCFG $MINDI_TMP 2>> $LOGFILE || Die "Cannot copy $MRCFG to ramdisk"
		cp -f $MINDI_TMP/mountlist.txt $mountpoint/tmp/ 2>> $LOGFILE || Die "Cannot copy mountlist to ramdisk"
		echo -en "$FILES_IN_FILELIST" > $mountpoint/tmp/FILES-IN-FILELIST
		echo -en "$LAST_FILELIST_NUMBER" > $mountpoint/tmp/LAST-FILELIST-NUMBER
	fi

	# Create module list to load at restore time
	rm -f $mountpoint/tmp/modules
	for m in $CDROM_MODS; do
		echo $m >> $mountpoint/tmp/modules
	done

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

	# Determine what filesystem to use for initrd image
	LogFile "INFO: 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" ] || [ "$gvFileSystem" = "ext4fs" ]; then
		# say what will be used
		LogFile "INFO: Creating an $gvFileSystem initrd image..."
		# kernel expects linuxrc in ext2 filesystem
		( cd "$mountpoint" && ln -sf usr/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
		if [ "$gvFileSystem" = "ext4fs" ] && [ -x "/sbin/tune4fs" ]; then
			bs=`/sbin/tune4fs -l ${rdz_fname}.tmp | grep -E '^Block size:' | cut -d: -f2 | sed 's/^ *//'`
		else
			bs=`tune2fs -l ${rdz_fname}.tmp | grep -E '^Block size:' | cut -d: -f2 | sed 's/^ *//'`
		fi
		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 "INFO: 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 usr/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

	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

# --nolog needs to be first, and is used in analyze-my-lvm
if [ "$1" = "--nolog" ] ; then
	shift
	LOGFILE=/dev/stderr
else
	> $LOGFILE
fi
if [ "$1" = "--printvar" ] ; then
	shift
	if [ _"$1" != _"" ] ; then
		set | grep -Ew "^$1" | cut -d= -f2
	fi
	exit 0
fi

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

[ -e "/sbin/mkdosfs" ] && [ ! -e "/sbin/mkfs.vfat" ] && LogAll "/sbin/mkfs.vfat is missing!"

# Log some capital variables
[ "$MINDI_PREFIX" = "XXX" ] && Die "Mindi has not been installed correctly."
[ "$MINDI_CONF" = "YYY" ] && Die "Mindi has not been installed correctly."
LogFile "MONDO_SHARE = $MONDO_SHARE"
LogFile "MINDI_LIB = $MINDI_LIB"
LogFile "MINDI_SBIN = $MINDI_SBIN"
LogFile "MINDI_CONF = $MINDI_CONF"
if [ -f $MINDI_CONFIG ]; then
	LogFile "-----------------------------"
	LogFile " Mindi configuration file    "
	LogFile "-----------------------------"
	grep -Ev '^#' $MINDI_CONFIG >> $LOGFILE
	LogFile "-----------------------------"
fi
LogFile "In Mindi"
LogFile "--------"
LogFile "EXTRA_SPACE = $EXTRA_SPACE"
LogFile "BOOT_SIZE = $BOOT_SIZE"
LogFile "--------"

trap AbortHere SIGTERM SIGHUP SIGQUIT SIGKILL SIGABRT SIGINT

# Sanity checks
which which > /dev/null 2> /dev/null || Die "Please install 'which'."
which strings > /dev/null 2> /dev/null || Die "Please install binutils and libbinutils; you have no 'strings' executable."
which gawk > /dev/null 2> /dev/null || Die "Gawk is missing from your computer. Please install gawk. You may find the package on Debian's website. How did I know you're running Debian? Because only Debian would be stupid enough not to include gawk in your distribution."
which gawk > /dev/null 2> /dev/null && AWK=`which gawk 2>/dev/null` || AWK="`which awk 2>/dev/null`"
if which awk &> /dev/null ; then
	if ! which gawk &> /dev/null ; then
		LogIt "INFO: 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 -E "2\.4\.[0-6]" | grep -vE "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 "INFO: Your PATH did not include /sbin or /usr/sbin. I have fixed that, temporarily."
	LogFile "INFO: However, you may wish to ask your vendor to provide a permanent fix..."
	LogFile "INFO: 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

### TODO
### 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 "INFO: LVM set to $LVM"
LogFile "----------"
LogFile "mount result:"
LogFile "-------------"
mount >> $LOGFILE
if [ -e /etc/raidtab ]; then
	LogFile "-------------"
	LogFile "/etc/raidtab content:"
	LogFile "-------------"
	cat /etc/raidtab >> $LOGFILE
else
	LogFile "No file /etc/raidtab"
fi
if [ -e /etc/mdadm.conf ]; then
	LogFile "-------------"
	LogFile "/etc/mdadm.conf content:"
	LogFile "-------------"
	cat /etc/mdadm.conf >> $LOGFILE
else
	LogFile "-------------"
	LogFile "No file /etc/mdadm.conf"
fi
LogFile "-------------"
LogFile "cat $CMDLINE"
LogFile "-------------"
cat $CMDLINE >> $LOGFILE
LogFile "-------------"
LogFile "cat /proc/swaps:"
LogFile "-------------"
cat /proc/swaps >> $LOGFILE
LogFile "-------------"
if [ -e /proc/mdstat ]; then
	LogFile "cat /proc/mdstat:"
	LogFile "-------------"
	cat /proc/mdstat >> $LOGFILE
else
	LogFile "No pseudo file /proc/mdstat"
fi
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 "INFO: 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 "-------------" 
LogFile "FORCE_MODS:"
LogFile "-------------"
LogFile "$FORCE_MODS"
LogFile "-------------"
LogFile "DENY_MODS:"
LogFile "-------------"
LogFile "$DENY_MODS"
LogFile "-------------"
LogFile "df result:"
LogFile "----------"
df -aT >> $LOGFILE
LogFile "-------------"
LogFile "df -i result:"
LogFile "----------"
df -i >> $LOGFILE
LogFile "-------------"
if [ -r /boot/grub/menu.lst ]; then
	LogFile "-------------"
	LogFile "INFO: /boot/grub/menu.lst content"
	LogFile "-------------"
	cat /boot/grub/menu.lst >> $LOGFILE
	LogFile "-------------"
fi
if [ -r /boot/grub/grub.conf ]; then
	LogFile "-------------"
	LogFile "INFO: /boot/grub/grub.conf content"
	LogFile "-------------"
	cat /boot/grub/grub.conf >> $LOGFILE
	LogFile "-------------"
fi
if [ -r /boot/grub/grub.cfg ]; then
	LogFile "-------------"
	LogFile "INFO: /boot/grub/grub.cfg content"
	LogFile "-------------"
	cat /boot/grub/grub.cfg >> $LOGFILE
	LogFile "-------------"
fi
if [ -r /boot/grub/device.map ]; then
	LogFile "-------------"
	LogFile "INFO: /boot/grub/device.map content"
	LogFile "-------------"
	cat /boot/grub/device.map >> $LOGFILE
	LogFile "-------------"
fi
if [ -r /etc/lilo.conf ]; then
	LogFile "-------------"
	LogFile "INFO: /etc/lilo.conf content"
	LogFile "-------------"
	cat /etc/lilo.conf >> $LOGFILE
fi
LogFile "Full fdisk info"
LogFile "---------------"
$FDISK -l >> $LOGFILE
LogFile "----------------"

# Compute libata version
laver=`modinfo libata 2> /dev/null | 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 "INFO: ide-generic removed from module list as your system uses libata v2+"
		LogFile "-------------"
	fi
fi

# Check for McAfee which disturbs the access to some files (tgz in articular)
if [ "x`cat /proc/linuxshield/enabled 2>/dev/null`" = "x1" ]; then
	LogFile "WARNING: McAfee LinuxShield is enabled. McAfee might block access to certain special files."
	LogFile "WARNING: Check in /var/opt/NAI/LinuxShield/etc/nailsd.cfg for 'nailsd.profile.OAS.action.error: Block'"
	LogFile "WARNING: You have two options:"
	LogFile "WARNING:  - Exclude all directories with special files (check McAfee System Events Log)"
	LogFile "WARNING:  - Disable the scanner during the backup"
fi

# Check for ISO_CMD command
if [ ! -x $ISO_CMD ]; then
	LogFile "NOTE: No CD image (ISO file) utility found"
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
		resk=`TryToFindKernelPath`
		# Avoids logfile content for mondo
		export MONDO_SHARE=""
		if [ "$resk" = "" ] ; then
			if [ $KERNEL_IS_XEN = "yes" ]; then
				echo "$xenkernelpath"
				LogFile "INFO: xenkernelpath = $xenkernelpath"
				MindiExit 0
			else
				MindiExit -1
			fi
		else
			echo "$resk"
			LogFile "INFO: kernelpath = $resk"
			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"
		# Avoids logfile content for mondo
		export MONDO_SHARE=""
		mr-read-all-link $2
		MindiExit $?
	elif [ "$1" = "--makemessage" ] ; then
		MakeMessageFile | cut -c1-80
		MindiExit 0
	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=""
		[ "$kernelpath" = "" ] && kernelpath=`TryToFindKernelPath`
		
###
### 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...
###
		if [ $KERNEL_IS_XEN = "yes" ]; then
			LogAll "INFO: xenkernelpath = $xenkernelpath"
		fi
		kernelname=`echo $kernelpath | cut -d'-' -f2- | sed 's/.[bg]z[2]*$//'`
		if [ ! -d "/lib/modules/$kernelname" ]; then
		   LogAll "WARNING: Module path for ${kernelpath} not found..."
		   LogAll "         using running kernel\'s modules."
		   kernelname=$KERVERRUN
		else
		   LogAll "Using modules for kernel: ${kernelname}"
		fi
		LogAll "INFO: kernelname = $kernelname"
		LogAll "INFO: kernelpath = $kernelpath"
###
### 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 "INFO: LILO will use conservative settings, to be compatible with older BIOSes."
		fi
		LAST_FILELIST_NUMBER=${12}
		ESTIMATED_TOTAL_NOOF_SLICES=${13}
		export MINDI_EXCLUDE_DEVS="${14}"
		USE_COMP="${15}"
		USE_LILO="${16}"
		USE_STAR="${17}"
		INTERNAL_TAPE_BLOCK_SIZE="${18}"
		DIFFERENTIAL="${19}"
		USE_GZIP="${20}"
		NOT_BOOT="${21}"
		[ "$USE_COMP" = "" ] && USE_COMP=yes
		[ "$USE_GZIP" = "" ] && USE_GZIP=no
		[ "$NOT_BOOT" = "" ] && NOT_BOOT=no
		[ "$TAPEDEV" ] && LogIt "INFO: This is a tape-based backup. Fine."
		# 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

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

for i in loop cdrom ide-cd isofs linear raid0 raid1 raid5 ; do
	modinfo $i 2> /dev/null 1> /dev/null
	if [ $? -eq 0 ]; then
		modprobe $i 2>&1 > /dev/null
	fi
done

KERN_DISK_MADE=""

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

if [ "$PROMPT_MAKE_USB_IMAGE" = "yes" ] && [ "$USBDEVICE" != "" ]; then
	LogIt "INFO: 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

echo -e "Mindi's temp dir = $MINDI_TMP \nMindi's output dir=$MINDI_CACHE" >> $LOGFILE
[ "$(($RANDOM%64))" -eq "0" ] && LogIt "INFO: Dude, I've looked inside your computer and it's really dusty..."

mountpoint=$MINDI_TMP/mountpoint.$$
PrepareDataDiskImages

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

LogFile "INFO: Ramdisk will be $ramdisk_size KB"
if [ "$ARCH" = "ia64" ] ; then
	PrepareBootDiskImage_LILO $kernelpath || Die "Failed to create ia64 image disk image."
else
	PrepareBootDiskImage_ISOLINUX $kernelpath || Die "Failed to create $ramdisk_size KB disk image."
fi

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

if [ _"$MONDO_SHARE" = _"" ]; then
	ListImagesForUser
	OfferToMakeBootableISO
	if [ "$PROMPT_MAKE_USB_IMAGE" = "yes" ]; then
		OfferToMakeBootableUSB
	fi
	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 "INFO: $FRIENDLY_OUTSTRING"
for mtpt in $FLOPPY_WAS_MOUNTED ; do
	mount $mtpt
done
MindiExit 0
