#!/bin/bash

# $Id: mindi 3555 2016-04-08 23:25:07Z 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=PBREV
MINDI_VER=PBVER

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=${TMPDIR:=/tmp}
if [ ! -d $TMPDIR ]; then
	mkdir -p $TMPDIR
fi

EXTRA_SPACE=150000		# increase if you run out of ramdisk space

PROMPT_MAKE_CD_IMAGE="yes"
	# Ask if you want to make a CD Image to be written?
	# if this is set to 'no' in the conf file, 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' in the conf file, 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 hpvsa hpdsa 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 mpt2sas mpt3sas 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 virtio_scsi vmw_pvscsi"

# 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 virtio_blk virtio_pci hv_storvsc"
PCMCIA_MODS="pcmcia_core ds yenta_socket"
USB_MODS="usb-storage usb_storage usb-ohci usb-uhci input hid hid_generic hid-generic 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 enic forcedeth vmxnet vmxnet3 vmnet exportfs fuse netbk xenblktap r8169 virtio_net via_rhine ipv6 ptp rpcsec_gss_krb5"
CDROM_MODS="$TAPE_MODS $IDE_MODS $USB_MODS $PCMCIA_MODS $SCSI_MODS $NET_MODS cdrom isocd isofs sg sr_mod iso9660 nls_iso8859-1 nls_cp437 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 nls_utf8"
# 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=""

LOGFILE=/var/log/mindi.log
BOOT_MEDIA_MESSAGE="\
To format and restore all files automatically, type '0enuke07' <enter>.\n\
To restore some/all files interactively, type '0einteractive07' <enter>.\n\
To compare the archives with your filesystem, type '0ecompare07' <enter>.\n\
To boot to a command-line prompt (expert mode), type '0eexpert07' <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\
\n0eF107-Main | Boot Parameters 0eF207-1/2 | 0eF307-2/2 | 0eF407-PXE\n\
"
FDISK=$MINDI_SBIN/mr-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"

# Debian 8 system e.g. use xorriso for UEFI support.
# However, they use exactly the same command line parameters as mkisofs, so just
# use it if it's available.
ISO_CMD="/usr/bin/xorriso"

# Mandriva system e.g. use cdrkit, which uses genisoimage.
# However, they use exactly the same command line parameters as mkisofs, so just
# use it if it's available.
if [ ! -x $ISO_CMD ]; then
	ISO_CMD="/usr/bin/genisoimage"
	# For compatibility with previous versions default to mkisofs
	if [ ! -x $ISO_CMD ]; then
		ISO_CMD="/usr/bin/mkisofs"
	fi
	if [ ! -x $ISO_CMD ]; then
		LogFile "NOTE: No CD image (ISO file) utility found"
		ISO_CMD = ""
	fi
else
	ISO_CMD="/usr/bin/xorriso -as mkisofs"
fi

ISO_OPT="-J -r -v -p Mindi -publisher http://www.mondorescue.org -A Mindi -V Mindi_Image -o $MINDI_CACHE/mindi.iso "

# Mindi set this as default in case it's invoked alone
BOOT_TYPE="BIOS"
# and we also check whether we're UEFI or not.
if [ -d "/sys/firmware/efi" ]; then
	BOOT_TYPE="UEFI"
else
	# 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
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 [a-z ]*\`/\'" "$2" >> $LOGFILE
		rm -f "$2"
	fi
}

# 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 "INFO: Mindi $MINDI_VERSION is exiting" 
	LogFile "INFO: 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 [a-z ]*\`/\'" "$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" ] && sync && 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
	fi

	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 templog
	outdir=$1
	templog=$MINDI_TMP/$$.log
	mkdir -p $outdir
	incoming=`ReadLine`
	counter=$3
	> $templog

	while [ "$incoming" != "" ] ; do
		if [ "$3" = "1" ]; then
			counter=$(($counter+1))
			LogProgress $counter $2
		fi
		# 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 0
		elif [ -e "$incoming" ] && [ $found = "false" ]; then
			if [ ! -h "$incoming" ]; then
				tar cf - -C / $incoming 2> $templog | (cd "$outdir" ; tar xf -) || Die "Cannot copy $incoming to $outdir - did you run out of disk space?" $templog
			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
		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/console
	[ ! -e "$KEYDIR" ] && KEYDIR=/etc/console-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
	echo -en "INFO: Adding 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"
}

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

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

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 tempdepfile modres noof_lines lvmversion lvmresolved

	echo -en "INFO: 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\nINFO: Making 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"
			(cd "$bigdir" ; tar -zxf $MINDI_TMP/post-nuke.tgz 2>> $MINDI_TMP/$$.log || LogAll "ERROR: when untarring post-nuke tarball" $MINDI_TMP/$$.log)
		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 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
}


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 MakeBootInitFile, 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 "boot-type $BOOT_TYPE" >> $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 "INFO: Your raw fstab file looks like this:"
	LogFile "------------------------------------"
	cat $MY_FSTAB >> $LOGFILE
	LogAll "-----------------------------------"
	LogAll "INFO: 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
		LogFile "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 | tr ' ' '\n' | 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
}


MakeISOErrors() {

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

MakeISO() {

LogAll "INFO: Invoking $CMD ."
(cd "$MINDI_TMP/mpt" ; $CMD .) > /dev/null 2> $MINDI_TMP/mkisofs.log
if [ $? -ne 0 ] ; then
	if [ "$BOOT_TYPE" = "UEFI" ]; then
		CMD=`echo $CMD | perl -p -e 's|--efi-boot |-eltorito-platform 0xEF -eltorito-boot |; s|-efi-boot |-eltorito-platform 0xEF -eltorito-boot |;'`
		LogAll "INFO: Invoking instead $CMD"
		(cd "$MINDI_TMP/mpt" ; $CMD .) > /dev/null 2> $MINDI_TMP/mkisofs.log
		if [ $? -eq 0 ] ; then
			LogAll "INFO: Created bootable ISO image at $MINDI_CACHE/mindi.iso"
		else
			MakeISOErrors
		fi
	else
		MakeISOErrors
	fi
else
	LogAll "INFO: Created bootable ISO image at $MINDI_CACHE/mindi.iso"
fi
rm -f $MINDI_TMP/mkisofs.log
}

MakeBootableDevice() {

local target tbc retval part size mount_opt

target="$1"

rm -Rf $MINDI_TMP/target
mkdir -p $MINDI_TMP/target/{images,archives,tmp}

LogAll "INFO: Copying $MINDI_CACHE/*.gz to $MINDI_TMP/target/images"
cp -f $MINDI_CACHE/*.gz $MINDI_TMP/target/images 2>> $LOGFILE || LogAll "WARNING: MakeBootableDevice: Cannot copy files to $MINDI_TMP/target/images"
for i in memdisk memtest.bin memtest.img ; do
	j=$MINDI_LIB/$i
	k=$MINDI_TMP/target
	if [ -e "$j" ] ; then
		LogAll "INFO: Copying $j to $k"
		cp -f $j $k 2>> $LOGFILE || LogAll "Failed to copy $j to $k"
		cp -f $j $MINDI_TMP 2>> $LOGFILE || LogAll "Failed to copy $j to $MINDI_TMP"
		if [ _"$MONDO_SHARE" != _"" ]; then 
			cp -f $j $MONDO_ROOT 2>> $LOGFILE || LogAll "Failed to copy $j to $MONDO_ROOT"
		fi
	fi
done

retval=0
LogAll "INFO: Copying $kernelpath to $MINDI_TMP/target/vmlinuz"
cp $kernelpath $MINDI_TMP/target/vmlinuz 2>> $LOGFILE
if [ $? -ne 0 ] ; then
	LogAll "ERROR: Failed to copy $kernelpath $MINDI_TMP/target/"
	retval=$(($retval+1))
fi
LogAll "INFO: Copying $MINDI_TMP/initrd.img to $MINDI_TMP/target/initrd.img"
cp $MINDI_TMP/initrd.img $MINDI_TMP/target/ 2>> $LOGFILE
if [ $? -ne 0 ] ; then
	LogAll "ERROR: Failed to copy $MINDI_TMP/initrd.img to $MINDI_TMP/target/"
	retval=$(($retval+1))
fi

# copy boot stuff now generated in PrepareDataDiskImage
if [ "$BOOT_TYPE" = "UEFI" ]; then
	(cd $MINDI_TMP/target ; tar xfz $MINDI_CACHE/all.tar.gz ./EFI)
	tbc="EFI"
	# Also prepare a BIOS compatible boot
	if  [ "$target" = "ISO" ]; then
		cp $ISOLINUX $MINDI_TMP/target/$tbc/ 2>> $LOGFILE
	fi
else
	(cd $MINDI_TMP/target ; tar xfz $MINDI_CACHE/all.tar.gz ./syslinux)
	tbc="syslinux"
	if [ -f "$MINDI_TMP/target/$tbc/syslinux.cfg" ]; then
		LogFile "----------- syslinux's conf --------------"
		cat $MINDI_TMP/target/$tbc/syslinux.cfg >> $LOGFILE
		LogFile "------------------------------------------"
	fi
	if  [ "$target" = "ISO" ]; then
		cp $ISOLINUX $MINDI_TMP/target/$tbc/ 2>> $LOGFILE
		if [ $? -ne 0 ] ; then
			LogAll "ERROR: Failed to copy $ISOLINUX to $MINDI_TMP/target/$tbc"
			retval=$(($retval+1))
		fi
	fi
fi

if [ "$ARCH" != "ia64" ] ; then
	if [ $KERNEL_IS_XEN = "yes" ]; then
		FindMboot32Binary 
		cp $xenkernelpath $MINDI_TMP/target/xen.gz 2>> $LOGFILE
		if [ $? -ne 0 ] ; then
			LogAll "ERROR: Failed to copy $xenkernelpath to $MINDI_TMP/target/"
			retval=$(($retval+1))
		fi
		cp $MBOOTC32 $MINDI_TMP/target/$tbc/mboot.c32  2>> $LOGFILE
		if [ $? -ne 0 ] ; then
			LogAll "ERROR: Failed to copy $MBOOTC32 to $MINDI_TMP/target/$tbc"
			retval=$(($retval+1))
		fi
	fi
fi

MakeMessageFile $MINDI_TMP/target/$tbc | cut -c1-80 > $MINDI_TMP/target/$tbc/message.txt

if [ _"$MONDO_SHARE" != _"" ]; then 
	cp -rf $MINDI_TMP/target/$tbc $MONDO_ROOT 2>> $LOGFILE
	if [ $? -ne 0 ] ; then
		LogAll "ERROR: Failed to copy $MINDI_TMP/target/$tbc to $MONDO_ROOT"
		LogAll "       Please check the target directory."
		retval=$(($retval+1))
	fi
	if [ $KERNEL_IS_XEN = "yes" ]; then
		cp -f $MINDI_TMP/target/xen.gz $MONDO_ROOT 2>> $LOGFILE
		if [ $? -ne 0 ] ; then
			LogAll "ERROR: Failed to copy $MINDI_TMP/target/xen.gz to $MONDO_ROOT"
			LogAll "       Please check the target directory."
			retval=$(($retval+1))
		fi
	fi
	cp -f $MONDO_SHARE/autorun $MINDI_TMP/target 2>> $LOGFILE
	cp -f $MINDI_TMP/target/vmlinuz $MONDO_ROOT 2>> $LOGFILE
	if [ $? -ne 0 ] ; then
		LogAll "ERROR: Failed to copy $MINDI_TMP/vmlinuz to $MONDO_ROOT"
		LogAll "       Please check the target directory."
		retval=$(($retval+1))
	fi
	cp -f $MINDI_TMP/target/initrd.img $MONDO_ROOT 2>> $LOGFILE
	if [ $? -ne 0 ] ; then
		LogAll "ERROR: Failed to copy $MINDI_TMP/initrd.img to $MONDO_ROOT"
		LogAll "       Please check the target directory."
		retval=$(($retval+1))
	fi
fi

if [ -f "$MINDI_TMP/$MRCFG" ]; then
	cp -f $MINDI_TMP/$MRCFG $MINDI_TMP/target/tmp
fi

LogFile "----------- target dir content -----------"
LogFile "------------------------------------------"
ls -lR $MINDI_TMP/target >> $LOGFILE
LogFile "------------------------------------------"
LogFile "----------- target dir sizes -------------"
du -sk $MINDI_TMP/target/* >> $LOGFILE
LogFile "------------------------------------------"

if [ "$retval" -ne "0" ] ; then
	LogFile "--------------------------------"
	LogFile "INFO: Size of $MINDI_TMP/target:"
	du -sk $MINDI_TMP/target/* >> $LOGFILE
	LogFile "--------------------------------"
	echo -en "Kernel size = `du -sk $kernelpath | cut -f1` K\nRamdisk free = $free_space K\n" >> $LOGFILE
	sync
	umount $MINDI_TMP/target
	LogAll "ERROR: Problems while creating boot media."
	LogAll "       Please unload some of your modules and try again."
	Die    "       Try to increase EXTRA_SPACE in $MINDI_CONFIG"
fi

mkdir -p $MINDI_TMP/mpt

if  [ "$target" = "USB" ]; then
	LogAll "INFO: Transforming $USBDEVICE in a Bootable device"
	LogAll "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
	# Some distro do auto mount at that point (Ubuntu)
	LogAll "INFO: Unmounting $USBPART just in case"
	sync
	umount $USBPART 2>> $LOGFILE 1>> $LOGFILE
	if [ "$BOOT_TYPE" = "BIOS" ]; then
		# 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 >> $LOGFILE 2>> $LOGFILE
		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
	fi
	LogAll "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
	LogAll "INFO: The USB device $USBDEVICE now looks like this:"
	$FDISK -l $USBDEVICE 2>&1 | tee -a $LOGFILE
	# 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)
	LogAll "INFO: Unmounting $USBPART just in case again"
	sync
	umount $USBPART 2>> $LOGFILE 1>> $LOGFILE
	# 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
			LogAll "INFO: Removing $block_id from device mapper."
			sleep 1
			dmsetup remove $block_id
		fi
	fi
	part=$USBPART
	mount_opt=""
else
	# ISO image
	part=$MINDI_TMP/mindi-bootroot.img
	size=`du -sk $MINDI_TMP/target 2> /dev/null | cut -f1`
	# Adds 10 MB to allow for additional space
	size=$(($size+10000))
	LogAll "INFO: Creating a $size KB empty file for boot device of the ISO image"
	dd if=/dev/zero of=$part bs=1k count=$size &> /dev/null || Die "Cannot dd blank $part"
	mount_opt="-o loop"
fi

LogAll "INFO: Creating a vfat filesystem on $part"

mkfs.vfat $part 2>&1 >> $LOGFILE
if [ $? -ne 0 ]; then
	LogAll "ERROR: Unable to create a vfat filesystem on $part"
	if  [ "$target" = "USB" ]; then
		LogAll "       Make sure your USB device is plugged in and partitioned ($part must exist on it)"
		$FDISK -l $USBDEVICE 2>&1 | tee -a $LOGFILE
	fi
	MindiExit -1
fi
if  [ "$target" = "ISO" ]; then
	if [ "$BOOT_TYPE" = "BIOS" ]; then
		# syslinux should be run on a local file (doen't work through NFS Cf: #297)
		# and run after the formating for versions > 6 it seems
		syslinux $part >> $LOGFILE 2>> $LOGFILE
	fi
fi
LogAll "INFO: Mounting $part on $MINDI_TMP/mpt"
mount -t vfat $mount_opt $part $MINDI_TMP/mpt 2>> $LOGFILE
if [ $? -ne 0 ]; then
	LogAll "ERROR: Unable to mount $part on $MINDI_TMP/mpt"
	if  [ "$target" = "USB" ]; then
		LogAll "       Make sure your USB device is plugged in, partitioned and formated ($part must exist on it)"
		$FDISK -l $USBDEVICE 2>&1 | tee -a $LOGFILE
	fi
	MindiExit -1
fi

LogAll "INFO: Moving boot info on $MINDI_TMP/mpt"
mv $MINDI_TMP/target/* $MINDI_TMP/mpt
if [ $? -ne 0 ] ; then
	LogFile "--------------------------------"
	LogFile "INFO: Size of $MINDI_TMP/mpt:"
	du -sk $MINDI_TMP/mpt/* >> $LOGFILE
	LogFile "--------------------------------"
	sync
	umount $MINDI_TMP/mpt
	LogAll "ERROR: Problems while creating boot media."
	LogAll "       Please unload some of your modules and try again."
	Die    "       Try to increase EXTRA_SPACE in $MINDI_CONFIG"
fi

if  [ "$target" = "ISO" ]; then
	if [ "$ARCH" != "ia64" ]; then
		ISO_OPT="$ISO_OPT -b $tbc/isolinux.bin -c $tbc/boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table"
	fi
	# ISO
	if [ "$ARCH" != "ia64" ] && [ "$BOOT_TYPE" = "BIOS" ]; then
		CMD="$ISO_CMD $ISO_OPT"
		MakeISO
	else
		if [ "$ARCH" = "ia64" ]; then
			CMD="$ISO_CMD $ISO_OPT -b images/mindi-bootroot.img -c images/boot.cat"
		else
			# UEFI
			echo "$CMD" | grep -q "xorriso"
			if [ $? -eq 0 ]; then
				CMD="$ISO_CMD $ISO_OPT -eltorito-alt-boot --efi-boot images/mindi-bootroot.img -no-emul-boot"
			else
				CMD="$ISO_CMD $ISO_OPT -eltorito-alt-boot -efi-boot images/mindi-bootroot.img -no-emul-boot"
			fi
		fi
	fi
fi

# Avoids graphical tool to keep the FS mounted
sync
umount $MINDI_TMP/mpt || Die "Unable to unmount $MINDI_TMP/mpt"

if  [ "$target" = "ISO" ]; then
	cp $part $MINDI_CACHE
	if [ "$ARCH" = "ia64" ] || [ "$BOOT_TYPE" = "UEFI" ]; then
		# We just need the EFI dir and the boot image for this case
		mkdir -p $MINDI_TMP/mpt2 $MINDI_TMP/mpt/images $MINDI_TMP/mpt/archives
		mount -o loop $MINDI_CACHE/mindi-bootroot.img $MINDI_TMP/mpt2 2>> $LOGFILE
		# We need again the kernel+initrd at the root for UEFI boot at least
		cp -a $MINDI_TMP/mpt2/EFI $MINDI_TMP/mpt2/vmlinuz $MINDI_TMP/mpt2/initrd.img $MINDI_TMP/mpt
		# We need the boot image now and what mindi needs at restore time as well
		cp -a $MINDI_TMP/mpt2/images/all.tar.gz $MINDI_CACHE/mindi-bootroot.img $MINDI_TMP/mpt/images
		# Avoids graphical tool to keep the FS mounted
		sync
		umount $MINDI_TMP/mpt2
		LogFile "----------- target dir content -----------"
		LogFile "------------------------------------------"
		ls -lR $MINDI_TMP/mpt >> $LOGFILE
		LogFile "------------------------------------------"
		MakeISO
	fi
else
	# 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
			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
fi
}


OfferToMakeBootableUSB() {

local i files

if [ "$PROMPT_MAKE_USB_IMAGE" = "yes" ] && [ _"$MONDO_SHARE" = _"" ]; then
	echo -en "\nShall 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
else
	if [ "$PROMPT_MAKE_USB_IMAGE" = "no" ] && [ _"$MONDO_SHARE" = _"" ] && [ "$USBDEVICE" = "" ]; then
		Die "No USBDEVICE environment variable declared, aborting"
	fi
fi
USBPART="${USBDEVICE}1"

MakeBootableDevice USB
}


OfferToMakeBootableISO() {

local i files

if [ -z "$ISO_CMD" ]; then
	LogAll "ERROR: Neither mkisofs nor genisoimage nor xorriso found, unable to make CD image"
	return
fi

if [ "$PROMPT_MAKE_CD_IMAGE" = "yes" ] && [ _"$MONDO_SHARE" = _"" ]; then
	echo -en "\nShall I make a bootable CD image? (y/[n]) "
	read i
	[ "$i" != "y" ] && [ "$i" != "Y" ] && return 0
fi

MakeBootableDevice ISO

}


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 [ -x "/etc/os-release" ]; then
		DESC=`grep PRETTY_NAME /etc/os-release | cut -d= -f2`
	elif [ -x "/usr/bin/pbdistrocheck" ]; then
		# For pb >= 0.9.8
		DESC=`/usr/bin/pbdistrocheck -s | cut -d, -f1-4 | sed 's/,/-/g'`
	elif [ -r /etc/issue.net ]; then
		DESC=`head -1 /etc/issue.net`
	elif [ -r /etc/issue ]; then
		DESC=`head -1 /etc/issue`
	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 <0eenter07> for 0cnetwork restore07\n"
				echo -en "$BOOT_MEDIA_MESSAGE"
			elif [ ! "$MINDI_TMP" ] ; then
				echo -en "FYI, this is _not_ a MondoRescue 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="="
		sepdef="="
	else
		sep=" "
		sepdef=" "
		if [ "$type" = "grub" ]; then
			sepdef="="
		fi
	fi

	# Generic header for conf file
	if [ "$type" = "elilo" ]; then
		echo -en "prompt\n"
	elif [ "$type" = "grub" ]; then
		echo -en "pause Press a key when ready to restore\n"
	elif [ "$type" = "grub2" ]; then
		echo -en "set "
	else
		# syslinux family
		echo -en "prompt 1\ndisplay message.txt\nF1 message.txt\nF2 boot1.txt\nF3 boot2.txt\nF4 pxe.txt\n"
	fi

	# Compute which default option to boot from
	echo -en "default${sepdef}"
	if [ "$CDRECOVERY" = "yes" ] ; then
		if [ "$type" = "grub" ]; then
			# TODO: Which num ???
			echo -en "0\n"
		else
			echo -en "RESTORE\n"
		fi
	# In case it's mondoarchive
	elif [ _"$MONDO_SHARE" != _"" ]; then
		if [ -e "$MINDI_TMP/NETFS-SERVER-MOUNT" ] ; then
			if [ "$type" = "grub" ]; then
				echo -en "3\n"
			else
				echo -en "iso\n"
			fi
		else
			if [ "$type" = "grub" ]; then
				echo -en "1\n"
			else
				echo -en "${MINDI_DEFAULT_BOOT_OPTION}\n"
			fi
		fi
	else
		if [ "$type" = "grub" ]; then
			echo -en "0\n"
		else
			echo -en "expert\n"
		fi
	fi

	# Handle timeout
	if [ "$type" = "grub" ]; then
		sep='='
	fi
	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"
		elif [ "$type" = "grub" ]; then
			outstr="title $i\n\tkernel /vmlinuz root=/dev/ram0 rw ramdisk_size=$ramdisk_size ${ooo} $MINDI_ADDITIONAL_BOOT_PARAMS\n\tinitrd=/initrd.img\n"
		elif [ "$type" = "grub2" ]; then
			if [ "$BOOT_TYPE" = "UEFI" ]; then
				lorder="linuxefi"
				iorder="initrdefi"
			else
				lorder="linux"
				iorder="initrd"
			fi
			outstr="menuentry '$i' {\n\tinsmod all_video\n\tinsmod gzio\n\tinsmod part_msdos\n\tinsmod part_gpt\n\tinsmod ext2\n\tinsmod xfs\n\techo 'Loading kernel...'\n\t$lorder /vmlinuz root=/dev/ram0 rw ramdisk_size=$ramdisk_size ${ooo} $MINDI_ADDITIONAL_BOOT_PARAMS\n\techo 'Loading ramdisk...'\n\t$iorder /initrd.img\n}\n"
		else
			ps="/"
			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"
		elif [ "$type" = "grub" ]; then
			echo -en "title memtest\n\tkernel /memtest.efi\n\tinitrd=/memtest.img\n"
		elif [ "$type" = "grub2" ]; then
			echo -en "menuentry 'memtest' {\n\tload_video\n\tinsmod gzio\n\tinsmod part_msdos\n\tinsmod xfs\n\tlinux /memtest\n\tinitrd /memtest.img\n}\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
}

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 res i j k lines lfiles includefile

	rm -f $MINDI_CACHE/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
		# TODO: 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 "INFO: Assembling dependency files"

	CopyDependenciesToDirectory < $needlist $bigdir `wc -l $needlist` 1
	echo -e "$DONE"

	# 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" ] && [ "$BOOT_TYPE" = "BIOS" ]; 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

	# Get terminfo content
	ti="usr/share/terminfo/l"
	if [ -d /$ti ]; then
		mkdir -p $bigdir/$ti
		cp -Rdf /$ti/* $bigdir/$ti 2>> $LOGFILE || LogAll "ERROR: issue copying terminfo"
	fi
	if [ -e "$MONDO_SHARE/restore-scripts" ]; then
		cp -Rdf $MONDO_SHARE/restore-scripts/mondo/* $bigdir/usr/bin 2>> $LOGFILE
		[ $? -ne 0 ] && [ _"$MONDO_SHARE" != _"" ] && Die "Cannot find/install $MONDO_SHARE/restore-scripts"
		cp -Rdf $MONDO_SHARE/restore-scripts/etc/* $bigdir/etc 2>> $LOGFILE
	fi
	if [ -d "/lib/dev-state" ]; then 
		cp -a /lib/dev-state $bigdir/lib/ 2>> $MINDI_TMP/$$.log || LogAll "ERROR: Unable to handle /lib/dev-state" $MINDI_TMP/$$.log
	fi
	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 "INFO: 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

	# copy (e)lilo/isolinux/grub/whatever stuff into it as well
	# to get it on the media (in addition to the boot part
	# and also to support UEFI boot mechanism
	bootdir=$bigdir/syslinux
	bootconf="$bootdir/syslinux.cfg"
	boottype=syslinux
	mkdir -p $bootdir
	FindLdlinux32Binary
	if [ "$BOOT_TYPE" != "BIOS" ]; then
		if [ "$BOOT_TYPE" = "UNKNOWN" ]; then
			LogAll "ERROR: UNKNOWN BOOT_TYPE. Please report upstream"
			MindiExit -1
		fi
		# EFI or UEFI
		# TODO: names are hard-coded for now
		if [ "$BOOT_TYPE" = "UEFI" ]; then
			# UEFI
			efidir=$bigdir/EFI/BOOT
			# On RHEL6 grub works
			dname=`pbdistrocheck | grep -E '^Name:' | cut -d':' -f2`
			dver=`pbdistrocheck | grep -E '^Ver:' | cut -d':' -f2`
			if [ $dname = "rhel" ] && [ $dver = "6" ]; then
				bootbin=`find /boot/efi -iname "grub*.efi" | head -1`
				bootconf="$efidir/BOOTX64.conf"
				boottype=grub
			elif [ $dname = "rhel" ] && [ $dver = "7" ]; then
				bootbin=`find /boot/efi -iname "grub*.efi" | head -1`
				bootconf="$efidir/grub.cfg"
				boottype=grub2
			elif [ $dname = "debian" ] && [ $dver = "8" ]; then
				bootbin=`find /boot/efi -iname "grub*.efi" | head -1`
				bootconf="$efidir/grub.cfg"
				boottype=grub2
			else
				# Use syslinux.efi as the default boot loader ... but it doesn't work for now :-(
				FindSyslinux64EFI
				bootbin=$SYSLINUX64EFI
				bootconf="$efidir/syslinux.cfg"
			fi

			# Depending on the arch, the target boot file is different
			if [ "$ARCH" = "x86_64" ] ; then
				tgbin="BOOTX64.efi"
			elif [ "$ARCH" = "armv8" ]; then
				tgbin="BOOTAA64.efi"
			else
				# i?386
				tgbin="BOOTIA32"
			fi
		else
			# EFI
			efidir=$bootdir
			bootbin=`find /boot/efi -iname "elilo.efi" | head -1`
			tgbin=$bootbin
			boottype=elilo
			bootconf="$efidir/elilo.conf"
		fi
		LogAll "INFO: Found $boottype boot type"

		# Copy it so that CD-ROM menu entry is satisfied
		mountefi=0
		df -T | grep /boot/efi | grep -qE 'vfat'
		if [ $? -ne 0 ]; then
			mount /boot/efi
			if [ $? -ne 0 ]; then
				echo "ERROR: You have to mount your (U)EFI partition when using mindi"
				MindiExit -1
			fi
			mountefi=1
		fi
		mkdir -p $efidir
		cp $bootbin $efidir/$tgbin
		if [ $mountefi -eq 1 ]; then
			umount /boot/efi 2>&1 > /dev/null
		fi

		if [ $boottype = "syslinux" ]; then
			FindLdlinuxe64Binary
			if [ -e "$LDLINUXE64" ]; then
				LogFile "INFO: Copying $LDLINUXE64 to $efidir"
				cp $LDLINUXE64 $efidir 2>> $LOGFILE || Die "Cannot copy $LDLINUXE64 to $efidir). Did you run out of disk space?"
				cp $LDLINUXE64/../libutil.c32 $efidir 2>> $LOGFILE || Die "Cannot copy $LDLINUXE64 to $efidir). Did you run out of disk space?"
			fi
		fi
		# In all cases prepare syslinux content for BIOS mode
		# so that we can have multi boot mode media BIOS+UEFI
		if [ -e "$LDLINUXC32" ]; then
			LogFile "INFO: Copying $LDLINUXC32 to $bigdir/EFI"
			cp $LDLINUXC32 "$bigdir/EFI" 2>> $LOGFILE || Die "Cannot copy $LDLINUXC32 to $bigtdir/EFI. Did you run out of disk space?"
		fi
	else
		# Useful for syslinux 5.x
		if [ -e "$LDLINUXC32" ]; then
			LogFile "INFO: Copying $LDLINUXC32 to $bootdir"
			cp $LDLINUXC32 $bootdir 2>> $LOGFILE || Die "Cannot copy $LDLINUXC32 to $bootdir. Did you run out of disk space?"
		fi
	fi

	# Here we need to know the ramdisk_size
	size_of_all_tools=`du -sk $bigdir | cut -f1`
	export ramdisk_size=$(($size_of_all_tools+$EXTRA_SPACE))
	LogFile "INFO: Ramdisk will be $ramdisk_size KB"

	MakeBootConfFile $boottype > $bootconf
	LogFile "Boot Conf file $bootconf content is:"
	LogFile "------------------------------------"
	cat $bootconf >> $LOGFILE
	LogFile "------------------------------------"
	if [ "$BOOT_TYPE" = "UEFI" ]; then
		# Also generate the syslinux conf
		MakeBootConfFile syslinux > "$bigdir/EFI/syslinux.cfg"
		LogFile "Boot Conf file $bigdir/EFI/syslinux.cfg content is:"
		LogFile "---------------------------------------------------"
		cat $bootconf >> $LOGFILE
		LogFile "---------------------------------------------------"
	fi

	echo -en "INFO: Tarring and zipping the data content..."
	(cd "$bigdir" ; tar -b 4096 -cf - . 2>> $MINDI_TMP/$$.log | gzip -9 > $MINDI_CACHE/all.tar.gz || LogAll "ERROR: Problem creating all.tar.gz" $MINDI_TMP/$$.log)
	LogFile "Size of the data content"
	LogFile "------------------------"
	du -sk $MINDI_CACHE/*gz >> $LOGFILE
	LogFile "------------------------"
	echo -e "$DONE"

	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-[2-9].* | 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"
}


MakeBootInitFile() {
	local tgz_dir_fname rdz_fname tempfile nodes kernelsize res currsize not_copied j k s w needed_modules_path d thelink templog

	tgz_dir_fname=$1
	rdz_fname=$2
	kernelsize=$3
	tempfile=$MINDI_TMP/temp.rd
	res=0 
	templog=$MINDI_TMP/$$.log
	> $templog

	LogAll "INFO: Making Boot RAM Disk ($ramdisk_size KB)"
	dd if=/dev/zero of=$tempfile bs=1k count=$ramdisk_size &> /dev/null || Die "Not enough room for temporary ramdisk (MakeBootInitFile)"
	LogAll "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"
	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."

	# 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 -al $mountpoint >> $LOGFILE
	
	# Check files before copying to discover configuration issues or McAfee preventing mindi reading these files
	# copy from rootfs into mountpoint
	LogAll "INFO: Copying Mindi files onto $mountpoint"
	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 -af $f $mountpoint 2>&1 >> $LOGFILE
		fi
	done
	(cd $mountpoint/etc ; ln -sf bashrc profile ; ln -sf bashrc shrc ; ln -sf ../proc/mounts mtab ; ln -sf ../usr/sbin/init linuxrc)
	(cd $mountpoint ; ln -sf usr/sbin/init linuxrc)

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

	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 | (cd $mountpoint ; 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 -p $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 (which includes all busybox deps)
	echo -en "INFO: Gathering dependencies of required files..."
	rm -f $MINDI_TMP/minimal.lis $MINDI_TMP/minimal2.lis
	lines=`cat $DEPLIST_DIR/minimal.conf | grep -vE " *#.*|^#" | sort -u`
	noof_lines=`echo $lines | wc -w`
	progress=0
	for f in $lines; 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
		progress=$(($progress+1))
		LogProgress $progress $noof_lines
	done
	echo -e "$DONE"
	echo -en "INFO: Processing all dependencies links..."
	lines=`sort -u $MINDI_TMP/minimal.lis $MINDI_TMP/minimal2.lis`
	noof_lines=`echo $lines | tr ' ' '\n' | wc -l`
	progress=0
	for f in $lines; do
		mr-read-all-link $f >> $MINDI_TMP/minimal.lis
		progress=$(($progress+1))
		LogProgress $progress $noof_lines
	done
	echo -e "$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
			# Do not overwrite files already in destination (avoid using option -n of cp not portable)
			if [ ! -e "$mountpoint/$f" ]; then
				finallist="$finallist $f"
			fi
		fi
	done
	rm -f $MINDI_TMP/minimal.lis $MINDI_TMP/minimal2.lis

	fnllist=`echo $finallist | tr ' ' '\n' | sort -u | tr '\n' ' '`
	LogFile "INFO: Copy the minimal env with cp -a --parents $fnllist -t $mountpoint"
	cp -a --parents $fnllist -t $mountpoint 2> $templog || LogIt "WARNING: Problem in minimal analysis" $templog

	# In case target /bin dir still doesn't exist, create it before using it
	if [ ! -d $mountpoint/bin ]; then
		mkdir -p $mountpoint/bin
	fi

	# For older distributions expecting /sbin/init provides it
	if [ ! -e "$mountpoint/sbin/init" ]; then
		(cd $mountpoint/sbin ; ln -sf ../usr/sbin/init .)
	fi

	# To improve support for distribution scripts, we now prefer to use bash as the std shell. Also fixes #600
	(cd $mountpoint ; ln -sf /bin/bash bin/sh)
	LogFile "INFO: Using bash as default shell"

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

	# 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
		LogFile "INFO: udev device manager found"
		tar cf - -C / /etc/udev 2> $templog | (cd $mountpoint ; tar xf -)  || LogIt "ERROR: Problem in /etc/udev analysis" $templog
		# 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> $templog | (cd $mountpoint ; tar xf -)  || LogIt "ERROR: Problem in /lib64/udev analysis" $templog
		fi
		if [ -e "/lib32/udev" ] && [ ! -h "/lib32" ] && [  ! -h "/lib32/udev" ]; then
			tar cf - -C / /lib32/udev 2> $templog | (cd $mountpoint ; tar xf -)  || LogIt "ERROR: Problem in /lib32/udev analysis" $templog
		fi
		if [ -e "/lib/udev" ] && [ ! -h "/lib" ] && [  ! -h "/lib/udev" ]; then
			tar cf - -C / /lib/udev 2> $templog | (cd $mountpoint ; tar xf -)  || LogIt "ERROR: Problem in /lib/udev analysis" $templog
		fi
		if [ -e "/usr/lib/udev" ] && [ ! -h "/usr/lib" ] && [  ! -h "/usr/lib/udev" ]; then
			tar cf - -C / /usr/lib/udev 2> $templog | (cd $mountpoint ; tar xf -)  || LogIt "ERROR: Problem in /usr/lib/udev analysis" $templog
		fi
		if [ -x /sbin/udevd ] || [ -x /usr/bin/udevd ] || [ -x /usr/lib/systemd/systemd-udevd ] || [ -x /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 [ -d $i ]; then
					lis3="$lis3 $i"
				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
					# Do not overwrite files already in destination (avoid using option -n of cp not portable)
					if [ ! -e "$mountpoint/$f" ]; then
						finallist="$finallist $f"
					fi
				fi
			done
			# But adds the directory useful for udev in $lis3
			fnllist=`echo $finallist | tr ' ' '\n' | sort -u | tr '\n' ' '`
			LogFile "INFO: Copying udev related files with cp -a --parents $fnllist -t $mountpoint/"
			cp -a --parents $fnllist $lis3 -t $mountpoint/ 2> $templog  || LogIt "WARNING: Problem in udev.lis analysis" $templog
			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 $mountpoint
		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> $templog | (cd $mountpoint ; tar xf -) || LogIt "ERROR: Problem in tools.lis analysis" $templog
		fi
		if [ -f $MINDI_CACHE/mindi-rsthw ]; then
			mv -f $MINDI_CACHE/mindi-rsthw $mountpoint
			chmod 755 $mountpoint/mindi-rsthw
		fi
		rm -f $MINDI_TMP/tools.lis $MINDI_CACHE/tools.files
	fi

	# Management of perl scripts delivered needed at restore time
	LogAll "INFO: Analyzing perl modules dependencies..."
	mindi-get-perl-modules `cat $MINDI_CONF/perl-scripts` /usr/[s]*bin/mr-* 2> $templog > $MINDI_TMP/perl.lis || LogIt "ERROR: Problem in mindi-get-perl-modules" $templog
	LogFile "DBG4: Perl Modules found:"
	LogFile "-------------------------"
	cat $MINDI_TMP/perl.lis >> $LOGFILE
	LogFile "-------------------------"
	tar cf - `cat $MINDI_TMP/perl.lis` 2> $templog | (cd $mountpoint ; tar xf -) || LogIt "ERROR: Problem in perl scripts analysis" $templog

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

	tar cf - -C / /dev/fd0*[1,2][4,7,8]* 2> $templog | (cd $mountpoint ; tar xf -) || LogIt "ERROR: Problem in fd dev analysis" $templog

	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."
	LogAll "INFO: Analyzing kernel modules dependencies..."
	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> $templog || LogIt "ERROR: Unable to copy modules to $mountpoint" $templog

	# 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> $templog | (cd "$mountpoint" ; tar xf -) || LogIt "ERROR: Unable to copy modules.* to $mountpoint" $templog

	# 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
			tar cf - $lis -C /  `sort -u $MINDI_TMP/obdr.lis` 2> $templog | (cd $mountpoint ; tar xf -) || LogIt "ERROR: Problem in obdr.lis analysis" $templog
			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" ]; then
		LogFile "INFO: Deleting devfsd daemon from ramdisk"
		[ ! -e "/sbin/devfsd" ] && LogFile "      ...because /sbin/devfsd not found"
		rm -f $mountpoint/sbin/devfsd
	fi
	[ "$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 "Size of initial ramdisk:"
	LogFile "---------------------------"
	(cd "$mountpoint" ; du -sh .) >> $LOGFILE
	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
		sync
		umount $mountpoint || Die "Cannot unmount $tempfile"
		dd if=$tempfile bs=1k of=${rdz_fname}.tmp > /dev/null 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
	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."
		# kernel expects init in cpio filesystem
		(cd "$mountpoint" ; ln -sf usr/sbin/init init)
		# create cpio image file and unmount loop filesystem
		(cd "$mountpoint" ; find . -print | cpio -o -H newc 2> /dev/null | gzip -9 > $rdz_fname)
		sync
		umount $mountpoint || Die "Cannot unmount $tempfile"
		# log that we are done
	else
		Die "Filesystem $gvFileSystem not supported for initrd image. Terminating."
	fi

	if [ "$res" -eq "0" ] ; then
		LogAll "INFO: MakeBootInitFile finished without error."
	else
		LogAll "WARNING: MakeBootInitFile exits WITH ERRORS."
	fi
	return 0
}


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

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

# --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 "-----------------------------"
LogFile "Start date : `date`"
LogFile "-----------------------------"
LogFile "$ARCH architecture detected"
LogFile "mindi called with the following arguments:"
echo "$@">> $LOGFILE
LogFile "-----------------------------"
LogFile "pbdistrocheck results:"
pbdistrocheck >> $LOGFILE
LogFile "-----------------------------"

# 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"
# Purge from potential old run
if [ _"$MINDI_CACHE" = _"" ]; then
	Die "MINDI_CACHE undefined"
else
	LogFile "MINDI_CACHE = $MINDI_CACHE"
fi

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

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
if [ -d /boot/efi ]; then
	gcf=`find /boot/efi -name 'grub.c*'`
	if [ _"$gcf" = _"" ]; then
		LogFile "Found a /boot/efi directory without a grub config file in it"
	else
		LogFile "-------------"
		LogFile "INFO: $gcf content"
		LogFile "-------------"
		cat $gcf >> $LOGFILE
		LogFile "-------------"
	fi
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

#
# 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" = "--makebcf" ] ; then
		[ ! "$2" ] && Die "Please specify the boot loader to check (syslinux, grub, grub2)"
		MakeBootConfFile $2
		MindiExit 0
	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
		LogFile "MINDI_CACHE = $MINDI_CACHE"

		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 "INFO: 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}"
		USE_LZMA="${21}"
		NOT_BOOT="${22}"
		BOOT_TYPE="${23}"
		[ "$USE_COMP" = "" ] && USE_COMP=yes
		[ "$USE_GZIP" = "" ] && USE_GZIP=no
		[ "$USE_LZMA" = "" ] && USE_LZMA=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 v$MINDI_VERSION to make boot+data disks"
fi
if [ -f $MINDI_LIB/rootfs/usr/bin/busybox ]; then
	LogIt "INFO: You are using 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

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 "\nDo 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

MakeBootInitFile $MINDI_LIB/rootfs $MINDI_TMP/initrd.img `du -sk $kernelpath | cut -f1` || Die "Could not create initrd.img"

[ -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
	OfferToMakeBootableISO
	if [ "$PROMPT_MAKE_USB_IMAGE" = "yes" ]; then
		OfferToMakeBootableUSB
	fi
	LogAll "INFO: Mindi 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

if [ -f $MINDI_TMP/$MRCFG ]; then
	LogFile "INFO: Your $MRCFG file is:"
	LogFile "--------------------------"
	cat $MINDI_TMP/$MRCFG >> $LOGFILE
	LogFile "--------------------------"
else
	if [ _"$MONDO_SHARE" != _"" ] ; then
		LogIt "ERROR: You don't have a $MRCFG file !"
	fi
fi
# cleanup
MindiExit 0
