#!/bin/sh

MINDI_VER=0.58
LILO_OPTIONS=""           ; # change to "-c" if your BIOS is really groovy
EXTRA_SPACE=8192          ; # increase if you run out of ramdisk space
TMP_ROOT=/tmp



#-----------------------------------------------------------------------------
# mindi - mini-Linux distro based on the user's filesystem & distribution
#
# Mindi can create a multi-floppy boot/root kit. The first floppy is the boot
# disk: it contains a kernel, a ramdisk etc. The second disk is data disk #1;
# the third disk is data disk #2; and so it goes.
#
# See http://www.microwerks.net/~hugo/mindi/ for details.
#-----------------------------------------------------------------------------


MY_FSTAB=/etc/fstab
FLOPPY_MODS="ide-floppy floppy"
SCSI_MODS="3w-xxxx 53c7,8xx 3c59x gdth a100u2w advansys aha152x aha1542 aha1740 aic7xxx aic7xxx_mod BusLogic dtc eata_dma eata eata_pio fdomain ide-scsi imm initio ips iscsi scsi-cd scsi scsi_mod sd sd_mod seagate sr st sym53c8xx ht ftape wd7000"; # backup the modules (of this list) which are actually already present/loaded at run-time
CDROM_MODS="$FLOPPY_MODS cdrom isofs inflate_fs ide-cd nls_iso8859-1 nls_cp437 sg sr_mod"
EXTRA_MODS="$CDROM_MODS vfat fat loop linear raid0 raid1 raid5 lvm-mod jfs xfs xfs_support pagebuf reiserfs ext2 ext3 minix nfs nfsd lockd sunrpc"
LOGFILE=/var/log/mindi.log
FDDEVICE=/dev/fd0             ; # 1.44MB floppy #0
FAILSAFE_KVER=2.4.12-xfs

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





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




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

    diskno=$noof_disks
    mkdir -p $minidir_root/$diskno
    [ "$LAST_COMPRESSED_SIZE" = "" ] && LAST_COMPRESSED_SIZE=0
    if [ ! -e "$filename" ] ; then
	if [ -h "$filename" ] ; then
#	    LogIt "HL $filename to disk $diskno"
	    cp --parents -pRdf $filename $minidir_root/$diskno
	    return $noof_disks
	else
	    echo -en "\nAddFileToDir asked me to add $filename, which does not exist.\n"
	    Die "Oops!"
	    #return $noof_disks
	fi
    fi
# move to the disk that has room on it (or end up using the last, if all full)
    while [ "$diskno" -lt "20" ] ; do
#	echo "diskno=$diskno"
	mkdir -p $minidir_root/$diskno
        filesize=`du -sk $filename | cut -f1`
	cp --parents -Rdf $filename $minidir_root/$diskno
	BIG_CLUNKY_SIZE_COUNTER=$(($BIG_CLUNKY_SIZE_COUNTER+$filesize))
        disksize=`du -sk $minidir_root/$diskno | cut -f1`
        would_occupy=$(($filesize+$disksize))
	[ "$would_occupy" -le "$MAX_COMPRESSED_SIZE" ] && return $diskno
	if [ "$LAST_COMPRESSED_SIZE" -le "$(($MAX_COMPRESSED_SIZE-200))" ] ; then
	    cutoff=100
	    complevel=1
	elif [ "$LAST_COMPRESSED_SIZE" -le "$(($MAX_COMPRESSED_SIZE-130))" ] ; then
	    cutoff=60
	    complevel=3
	else
	    cutoff=30
	    complevel=5
	fi
	[ "$BIG_CLUNKY_SIZE_COUNTER" -le "$cutoff" ] && return $diskno
	BIG_CLUNKY_SIZE_COUNTER=0;  # yyy
	tar -c $minidir_root/$diskno -f- 2> /dev/null | gzip -$complevel > $TMP_ROOT/$$.tgz 2> /dev/null
	LAST_COMPRESSED_SIZE=`du -sk $TMP_ROOT/$$.tgz | cut -f1`
	rm -f $TMP_ROOT/$$.tgz
	echo "disk=$diskno cut=$cutoff cl=$complevel siz=$LAST_COMPRESSED_SIZE" >> $LOGFILE
	[ "$LAST_COMPRESSED_SIZE" -le "$MAX_COMPRESSED_SIZE" ] &&return $diskno
	LAST_COMPRESSED_SIZE=0
	rm -f $minidir_root/$diskno/$filename
        diskno=$(($diskno+1))
    done
    return 0 ; # failed
}




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

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





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

#    echo "big#$biggienumber -- Chopping $filename" >> $LOGFILE
    [ -d "$filename" ] && Die "Cannot chop up $filename: it's a directory"
# record filename and its size
    mkdir -p $outdir
# chop up file; copy its slices

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



CopyBootBFile() {
    local copy_to copy_from possible_locations
    copy_to=$1
    copy_from=/boot/boot.b
    while [ ! -e "$copy_from" ] ; do
	possible_locations=`find /boot -type f | grep "boot\.b" | grep -v graphic | grep -v "\.old"`
	echo "Which boot.b file do you want to use?"
	echo "$possible_locations" | sed s/' '/' #'/ | tr ' ' '\n' | tr '#' '\t'
	echo -en "--> "
	read copy_from
    done
    cp -f $copy_from $copy_to || Die "CBBF -- cannot copy $copy_from to $copy_to"
}




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



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





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






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

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



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

    mountpoint=$TMP_ROOT/mointpoint.$$
    mkdir -p $mountpoint
    dd if=/dev/zero of=$imagefile bs=1k count=1440 > /dev/null 2> /dev/null || LogIt "Cannot dd (CODI)\n"
    mke2fs -N 12 -F $imagefile > /tmp/mke2fs.$$ 2>> /tmp/mke2fs.$$
    [ "$?" -ne "0" ] && cat /tmp/mke2fs.$$
    rm -f /tmp/mke2fs.$$
    mount -t ext2 -o loop $imagefile $mountpoint || Die "Can't loopmount $mountpoint"
    mv $tarball $mountpoint/
    if [ "$?" -ne "0" ] ; then
	umount $mountpoint
	Die "Tarball $tarball is too big for disk! (CODI)\nTell Hugo to adjust MAX_COMPRESSED_SIZE"
    fi
    [ "$diskno" -eq "$noof_disks" ] && echo "This is the last disk ($diskno=$noof_disks)" >> $mountpoint/LAST-DISK
    umount $mountpoint || LogIt "Cannot umount (CODI)\n"
    rmdir $mountpoint || LogIt "Cannot rmdir (CODI)\n"
}



DidMondoCallMe() {
    ps ax | grep "mondo.*archive" | grep -v "grep mondo.*archive"
}




Die() {
    local my_partitions i
    echo "MINDI_VER=$MINDI_VER" >> $LOGFILE
    if [ "$1" = "" ] ; then
	LogIt "Fatal error\n"
    else
	LogIt "Fatal error. $1\n"
    fi
    sync
    cd /
    my_partitions=`mount | grep $$ | cut -f1 -d' '`
    [ "$my_partitions" != "" ] && umount $my_partitions
    [ "$TMP_ROOT" != "/tmp" ] && rm -Rf $TMP_ROOT
    cd /tmp
    mkdir -p mindi.err
    for i in /tmp/mindi-needlist.txt /etc/fstab /etc/lilo.conf /etc/raidtab $LOGFILE /var/log/mondo-archive.log /tmp/mountlist.txt.$$ ; do
	[ -e "$i" ] && cp -f $i mindi.err/
    done
    rm -f mindi.err.*.tgz
    tar -c mindi.err -f- | gzip -9 > mindi.err.$$.tgz
    cd /
    rm -Rf mindi.err /tmp/mountlist.txt.$$
    LogIt "Please e-mail a copy of /tmp/mindi.err.$$.tgz to the author at"
    LogIt "hugo@firstlinux.net; author can and will render assistance only to"
    LogIt "users who supply the above file or a copy of $LOGFILE."
    LogIt "Please make sure you have read the FAQ, the manual, the log itself"
    LogIt "and preferably the mailing list before you seek assistance."
    exit 1
}




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

    list_of_optimized_libraries=`cat $filelist | grep "lib/i[5-7]86/"`
    if [ "$list_of_optimized_libraries" = "" ] ; then
	return 0
    fi
    echo -en "Dropping i686-optimized libraries if appropriate"
    for optimized_lib_name in $list_of_optimized_libraries ; do
	echo -en "."
	reason=""
	vanilla_lib_name=`echo "$optimized_lib_name" | sed s/i[5-7]86// | tr -s '/' '/'`
	echo "$vanilla_lib_name" >> $filelist
	resolved=$vanilla_lib_name
	echo "Adding $resolved to filelist" >> $LOGFILE
	while [ -h "$resolved" ] ; do
	    resolved=`ls $resolved -l | tr -s ' ' '\t' | cut -f11`
	    LocateFile $resolved >> $filelist
	    echo "Adding $resolved to filelist" >> $LOGFILE
	done
	mkdir -p $outdir$optimized_lib_name > /dev/null 2> /dev/null
	rmdir $outdir$optimized_lib_name > /dev/null 2> /dev/null
	ln -sf $vanilla_lib_name $outdir$optimized_lib_name
	echo "Excluding $optimized_lib_name" >> $LOGFILE
	cat $filelist | grep -vx "$optimized_lib_name" > $filelist.tmp
	echo "Replacing it with $vanilla_lib_name" >> $LOGFILE
	echo "$vanilla_lib_name" >> $filelist.tmp
	mv -f $filelist.tmp $filelist
    done
    cat $filelist | sort | gawk '{ print $1; }' | uniq > $filelist.tmp
    mv -f $filelist.tmp $filelist
#    cp $filelist /tmp/what-we-need.txt
    echo -e "$DONE"
}

FindAndAddUserKeyboardMappingFile() {
    local r res mapfile mappath included_item included_list keyfile mp locale
    LogIt "Analyzing your keyboard's configuration."
    KEYDIR=/lib/kbd
    [ ! -e "$KEYDIR" ] && KEYDIR=/usr/lib/kbd
    if [ ! -e "$KEYDIR" ] ; then
	LogIt "Keyboard mapping directory not found. I shall use default map at boot-time."
	return 0
    fi
    if [ -e "/etc/sysconfig/keyboard" ] ; then
	echo "Red Hat-style config detected." >> $LOGFILE
	keyfile=/etc/sysconfig/keyboard
    elif [ -e "/etc/rc.config" ] ; then
        echo "Debian-style config detected." >> $LOGFILE
	keyfile=/etc/rc.config
    else
	echo -en "Searching for rc.config ..."
	keyfile=`find /etc -name rc.config | head -n1`
	if [ "$keyfile" = "" ] || [ ! -e "$keyfile" ] ; then
	    LogIt "Unknown config detected. Default keyboard map will be used."
	    return
	else
	    echo "Found $keyfile" >> $LOGFILE
	fi
    fi
    if [ ! -e "$KEYDIR/keymaps" ] ; then
        LogIt "Keyboard mapping directory not found. Default keyboard map will be used."
        return
    fi
    echo "keyfile=$keyfile" >> $LOGFILE
    locale=`cat "$keyfile" |grep KEYTABLE |sed s/'"'// |sed s/'"'// |cut -d'=' -f2`
    echo "locale=$locale" >> $LOGFILE
    mp=`find $KEYDIR/keymaps | grep "i[3-8]86" | grep "$locale\." | grep -vx "#.*"`
    [ ! "$mp" ] && mp=`find $KEYDIR/keymaps | grep "i[3-8]86" | grep "$locale[^r][^/]" | grep -vx "#.*"`
    for i in $mp ; do
        mappath=$i
        [ -e "$i" ] && [ ! -d "$i" ] && break
    done
# patch by Claude Mah
    if [ ! -e "$mappath" ] || [ -d "$mappath" ] ; then
       mappath=$(locate */kbd/keymaps/*/$locale)
    fi
# end of patch
    echo "mappath = $mappath" >> $LOGFILE
    if [ ! -e "$mappath" ] || [ -d "$mappath" ] ; then
	LogIt "Keyboard mapping file not found. Default keyboard map will be used."
	return
    fi
    echo -en "Adding the following keyboard mapping tables: "
    mkdir -p $bigdir/tmp
    echo "$mappath" > $bigdir/tmp/KEYMAP-LIVES-HERE
KBDEPTH=0
    AddKeyboardMappingFile $mappath
    echo -e "$DONE"
    return 0
}





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



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
    files_found=`echo "$files_found" | tr ' ' '\n' | sort | uniq | grep -xv "" | tr '\n' ' '`
    echo "$files_found"
}



GenerateGiantDependencyList() {
    local incoming loc fname list_of_files i tempfile outfile progress filelist res r mapfile mappath included_list included_item old_pwd
    echo -en "Generating list of dependency files"
    outfile=$1
    tempfile=$TMP_ROOT/$$.txt
    incoming=`ReadLine`
    > $tempfile
    progress=0
    res=0
    while [ "$incoming" != "" ] ; do
	if [ "`echo "$incoming" | grep "#"`" != "" ] ; then
	    incoming=`ReadLine`
	    continue
	fi
        filelist=`GenerateListForFile "$incoming"`
        r=$?
        [ "$r" -ne "0" ] && LogIt "$incoming not found\n"
        res=$(($res+$r))
        for fname in $filelist ; do
            [ "$fname" != "" ] && echo "$fname" >> $tempfile
            progress=$(($progress+1))
            [ "$progress" -ge "4" ] && progress=0
	    [ "$progress" -eq "0" ] && echo -en "\r\t\t\t\t\t\t\t\t\t/"
            [ "$progress" -eq "1" ] && echo -en "\r\t\t\t\t\t\t\t\t\t-"
            [ "$progress" -eq "2" ] && echo -en "\r\t\t\t\t\t\t\t\t\t\\"
            [ "$progress" -eq "3" ] && echo -en "\r\t\t\t\t\t\t\t\t\t|"
        done
        incoming=`ReadLine`
    done
    > $outfile.pre
    for fname in `cat $tempfile | tr '/' '/' -s | sort | uniq` ; do
	echo "$fname" >> $outfile.pre
	LocateDeps $fname >> $outfile.pre
	progress=$(($progress+1))
        [ "$progress" -ge "4" ] && progress=0
        [ "$progress" -eq "0" ] && echo -en "\r\t\t\t\t\t\t\t\t\t/"
        [ "$progress" -eq "1" ] && echo -en "\r\t\t\t\t\t\t\t\t\t-"
        [ "$progress" -eq "2" ] && echo -en "\r\t\t\t\t\t\t\t\t\t\\"
        [ "$progress" -eq "3" ] && echo -en "\r\t\t\t\t\t\t\t\t\t|"
    done
    if [ "`DidMondoCallMe`" ] ; then
	mkdir -p $bigdir/tmp
	mkdir -p $bigdir/sbin
	if [ -e "$MONDO_TMP/post-nuke.tgz" ] ; then
	    LogIt "\nIncorporating post-nuke tarball"
	    old_pwd=`pwd`
	    cd $bigdir
	    tar -zxf $MONDO_TMP/post-nuke.tgz || LogIt "Error occurred when untarring post-nuke tarball"
	    cd $old_pwd
	fi
 	if cp -f $MONDO_TMP/mondo*restore $bigdir/usr/bin ; then
            LocateDeps $bigdir/usr/bin/mondo*restore >> $outfile.pre
	else
	    LogIt "Cannot find mondo*restore in mondo's tempdir, $MONDO_TMP"
            LogIt "If Mindi was called by Mondo then send me a bug report."
            LogIt "It not, type 'ps ax' to see which Mondo-related process is still running;"
            LogIt "then kill it. :-) Finally, run Mindi again."
            Die "Odd."
        fi
        cp -f $MONDO_TMP/BOOTLOADER.* $bigdir 2> /dev/null || LogIt "\nMondo v1.2x defaults to LILO as the bootloader, BTW."
	if [ -e "$MONDO_TMP/start-nfs" ] ; then
	    LogIt "Incorporating NFS-related settings"
	    cp -f $MONDO_TMP/start-nfs $bigdir/sbin || Die "Cannot find start-nfs"
	    for r in NFS-SERVER-MOUNT NFS-SERVER-PATH NFS-DEV NFS-CLIENT-IPADDR NFS-SERVER-IPADDR ; do
		cp -f $MONDO_TMP/$r $bigdir/tmp || Die "Cannot copy $r"
                echo "Copying $r to ramdisk" >> $LOGFILE
	    done
	fi
    fi
    cat $outfile.pre | tr ' ' '\n' | tr '/' '/' -s | grep -vx "" | sort | uniq | grep -v "/libX11" | grep -v "/libXext" | grep -v "/libXi" | grep -v "/libgtk" | grep -v "/libgdk" > $outfile
    rm -f $tempfile $outfile.pre
    [ "$res" -eq "0" ] && echo -e "$DONE" || echo "\nFailed."
    return $res
}





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



GetHomeDir() {
    local res loc
    loc=`which $1`
    res=`file $loc | gawk '{print $NF;}'`
    dirname $res
}






HackAwk() {
    local pathname filename dir old_pwd new_fname
    pathname=$1
    filename=$2
    dir=`echo "$pathname" | sed s/$filename//`
    old_pwd=`pwd`
    cd $dir
    [ -f "$filename" ] || Die "Can't find $filename at $dir"
    new_fname="an.icky.icky.spider.ewww"
    [ "$filename" = "gawk" ] && new_fname="awk"
    [ "$filename" = "awk" ] && new_fname="gawk"
    ln -s $filename $new_fname
    cd $old_pwd
}




HackMountlist() {
    local scratchdir outfile partlist pst partstr \
res partition swapsize
    scratchdir=$TMP_ROOT
    outfile=$1

    mkdir -p $outfile
    rm -Rf $outfile
    > $outfile
    partlist=`mount | cut -d' ' -f1,3,5 \
| grep -v "none " \
| grep -v "/tmp " | grep -v "/ISOs " | grep -v "/proc " \
| grep -v "/dev/root " \
| grep -v "/mnt/" \
| tr ' ' '|'`

    echo -n "Modifying mountlist..."

    if [ ! -f "/mountlist.hacked" ] ; then
        Die "Can't find modified mountlist.hacked!"
    else
        cp /mountlist.hacked "$outfile"
        LogIt "Done. (Created by auto-archive, I assume?)\n"
    fi
}




HackPathsToFailsafe() {
    local incoming newpath kver stub i pwd
    kver=`uname -r`
    incoming=`ReadLine`
    pwd=`pwd`
    cd $TMP_ROOT
    while [ "$incoming" != "" ] ; do
	stub=`basename $incoming`
	newpath=`FindSpecificModuleInPath lib/modules/$FAILSAFE_KVER $stub`
	for i in $newpath ; do
	    echo "$i"
# | gawk '{print substr($0,3);}'
	done
	read incoming
    done
    cd $pwd
}



ListAllPartitions() {
    local res currline partition
    for currline in `grep -v "|" $MY_FSTAB | tr -s ' ' '\t' | tr '\t' '|'`; do
	if [ "`echo "$currline" | tr ' ' '#' --squeeze-repeats | cut -d'#' -f1`" = "" ] ; then
	    LogIt "I'm skipping fstab line '$currline'\n" 9
	else
	    partition=`echo $currline | cut -d'|' -f1`
	    [ "$partition" != "none" ] && [ "`echo $partition | grep mnt`" = "" ] && echo "$partition"
	fi
    done
    [ -e "/etc/raidtab" ] && cat /etc/raidtab | grep device | sed s/device/\|/ | cut -d'|' -f2 | tr -s ' ' '\t' | cut -f2
}


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



ListKernelModulePaths() {
    local module_list module fname oss
    oss="/root/oss/modules"
    module_list=`ListKernelModules`
    for module in $EXTRA_MODS $module_list ; do
        find /lib/modules/`uname -r`/* -type f | grep "$module\.o"
	[ -f "$oss" ] && find $oss | grep $module
    done
    find /lib/modules/`uname -r`/modules.* -type f 2> /dev/null
    [ -f "$oss" ] && find $oss.* 2> /dev/null
}



ListKernelModules() {
# My version
#    lsmod | grep -v -i "Used by" | cut -d' ' -f1

# Steve Pitts' version (as I recall)
    lsmod | sed -n '2,$s/ .*//p'
}



LocateDeps() {
    local incoming fname deps
    incoming="$1"
    for fname in $incoming ; do
        if [ ! -e "$fname" ] ; then
            Die "$fname does not exist; cannot be LDD'd."
        else
            ldd $fname 2> /dev/null | ProcessLDD $fname
        fi
    done
}





LocateFile() {
    local i path fname_to_find location output resolved tmp stub cache_id loclist
    fname_to_find="$1"
    touch $FILE_CACHE
# patch by Jean-David Marrow
    output=""; cache_id=`echo $fname_to_find | md5sum`
    output=`sed -n -e "s/^$cache_id //p" $FILE_CACHE`
    if [ ! "$output" = "" ] ; then
	echo "$output"
#	echo -ne "*" > /dev/stderr
	return 0
    fi
# end of patch by JDM
    output=""
    for path in / /etc /usr /usr/bin /usr/sbin /bin /usr/X11R6/bin /sbin /usr/local/bin /usr/local/sbin /usr/lib /lib /usr/local/lib /usr/X11R6/lib ; do
	location=`echo "$path/$fname_to_find" | tr '/' '/' --squeeze-repeats`
	if [ "`echo "$location" | grep "lib/lib"`" != "" ] ; then
	    loclist=`find $path -maxdepth 1 | grep "$fname_to_find"`
	else
	    loclist=$location
	fi
	for location in $loclist ; do
	    [ ! -e "$location" ] && continue
	    output="$location $output"
	    copies_found=$(($copies_found+1))
	    if [ -h "$location" ] ; then
		resolved=`ls -l $location |tr -s ' ' '\t' | cut -f11`
		if [ "`echo "$resolved" | grep "/"`" = "" ] ; then
		    stub=`echo "$location" | $AWK -F '/' '{ for(i=1;i<NF;i++) {printf("/%s",$i);};};'`
		    output="/$stub/$resolved $output"
		fi
	    fi
	done
    done
    [ "$output" = "" ] && return 1
    echo "$output"
# patch by Jean-David Marrow
    echo -ne "$cache_id $output\n" >> $FILE_CACHE
# end of patch by JDM
    return 0
}



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





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


# Called by TurnTgzIntoRdz, to make /tmp/mondo-restore.cfg

MakeMondoConfigFile() {
    local outfile use_lzo
    outfile=$1
    > $outfile
    [ "$TAPESIZE" ]		&& echo "tapesize $TAPESIZE" >> $outfile
    [ "$TAPEDEV" ]	        && echo "tapedev $TAPEDEV" >> $outfile
    [ "$FILES_IN_FILELIST" ]	&& echo "files-in-filelist $FILES_IN_FILELIST" >> $outfile
    [ "$LAST_FILELIST_NUMBER" ]	&& echo "last-filelist-number $LAST_FILELIST_NUMBER" >> $outfile
    use_lzo=$USE_LZO; [ "$use_lzo" = "" ] && use_lzo="no"
    echo "use-lzo $use_lzo" >> $outfile
    [ "$ESTIMATED_TOTAL_NOOF_SLICES" ] && echo "total-slices $ESTIMATED_TOTAL_NOOF_SLICES" >> $outfile
   AddFileToCfgIfExists $MONDO_TMP/NFS-CLIENT-IPADDR nfs-client-ipaddr $outfile
   AddFileToCfgIfExists $MONDO_TMP/NFS-SERVER-MOUNT  nfs-server-mount  $outfile
   AddFileToCfgIfExists $MONDO_TMP/NFS-SERVER-PATH   nfs-server-path   $outfile
   AddFileToCfgIfExists $MONDO_TMP/NFS-DEV           nfs-dev           $outfile
   AddFileToCfgIfExists $MONDO_TMP/NFS-SERVER-IPADDR nfs-server-ipaddr $outfile
   AddFileToCfgIfExists $MONDO_TMP/BOOTLOADER.DEVICE bootloader.device $outfile
   AddFileToCfgIfExists $MONDO_TMP/BOOTLOADER.NAME   bootloader.name   $outfile
   AddFileToCfgIfExists $MONDO_TMP/KEYMAP-LIVES-HERE keymap-lives-here $outfile
   AddFileToCfgIfExists $MONDO_TMP/TAPEDEV-HAS-DATA-DISKS tapedev-has-data-disks $outfile
   AddFileToCfgIfExists $MONDO_TMP/USING-CDSTREAM    using-cdstream    $outfile
}





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

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

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

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

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

    rm -f $mountlist
    mkdir -p $mountlist
    LogIt "exclude_dirs = $EXCLUDE_DEVS\n"
    rm -Rf $mountlist
    > $mountlist
    echo -en "\rHang on...\r"
    all_partitions=`ListAllPartitions 2> /dev/null`
#    echo "all partitions = $all_partitions" >> $LOGFILE
    if [ -d "/proc/lvm" ] ; then
	echo -en "\rAnalyzing LVM...\r"
	all_partitions="$all_partitions `analyze-my-lvm | grep ">>>" | cut -d' ' -f2-32`"
    fi
    for i in $IMAGE_DEVS ; do
      mount | grep "$i " > /dev/null 2> /dev/null && Die "Sorry, $i is already mounted! CANNOT DO IMAGEDEV"
    done
    [ "$IMAGE_DEVS" != "" ] && all_partitions="`echo "$all_partitions $IMAGE_DEVS" | tr ' ' '\n' | sort | uniq | tr '\n ' ' '`"
    printf "        %-15s %-15s %-15s %-15s\n" DEVICE MOUNTPOINT FORMAT "SIZE (MB)"
    for c_p in $all_partitions ; do
	[ "`echo "/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" | grep "$c_p"`" != "" ] || [ "`echo "$c_p" | grep "/dev/scd"`" != "" ] || [ "`echo "$c_p" | grep "/dev/ram"`" != "" ] || [ "`echo "$c_p" | grep ":"`" != "" ] || [ "`echo "$c_p" | grep ":/"`" != "" ] && continue
        [ "`echo "/dev/scd0 /dev/scd1 /dev/sr0 /dev/sr1 /dev/cdrom /dev/cdrom1" | grep "$c_p"`" ] && continue
# used to be 'if [ -h "$c_p" ] ; then'; kludged to work with devfsd
	if [ -h "$c_p" ] && [ "`echo "$c_p" | grep "/dev/hd"`" = "" ] && [ "`echo "$c_p" | grep "/dev/sd"`" = "" ] && [ "`echo "$c_p" | grep "/dev/md"`" = "" ] ; then
	    current_partition=`ls -l "$c_p" |sed s/' -> '/'|'/ |cut -d'|' -f2`
    	    [ "`echo "/dev/scd0 /dev/scd1 /dev/sr0 /dev/sr1 /dev/cdrom /dev/cdrom1" | grep "$current_partition"`" ] && continue
	    if [ "`echo "$current_partition" | grep "/dev/"`" = "" ] ; then
		current_partition="/dev/$current_partition"
	    fi
	else
	    current_partition="$c_p"
	fi
	[ "$c_p" = "none" ] && continue
	if [ "`echo "$current_partition" | grep -i "LABEL="`" != "" ] ; then
	    str_to_find_fmt_with=$current_partition
	    redhat_label=`echo "$current_partition" | cut -d'=' -f2`
	    actual_dev=`mount | grep "on $redhat_label " | cut -d' ' -f1`
	    partition_mountpt=$redhat_label
	    current_partition=$actual_dev
	else
	    partition_mountpt=`grep -w "$current_partition" $MY_FSTAB | grep -v "#" | $AWK '{print $2}'`
	    str_to_find_fmt_with=$current_partition
	fi
	partition_format=`$AWK '$1 == "'"$str_to_find_fmt_with"'" {print $3}' $MY_FSTAB`
	if [ -d "/proc/lvm" ] && [ "`lvdisplay $current_partition 2> /dev/null`" != "" ] ; then
	    partition_size="lvm"
	else
	    partition_size=`SizeOfPartition $current_partition`
	    [ "`echo "$current_partition" | grep "[0-9]"`" = "" ] && continue
	    [ "`echo "$current_partition" | grep -c "^/"`" -ne "1" ] && continue
#-- Dunno what these lines are for --------------------------- Hugo, 09/22/2001
#	partition_number=`echo "$current_partition" | tr '[:alpha:]' ' ' | tr -s '/' ' ' | gawk '{print $NF;}'`
#	MakeSureNumberIsInteger $partition_number
#-- so I've disabled them -----------------------------------------------------
	    if [ "$partition_format" = "swap" ] ; then
		partition_size=`grep -v "Priority" /proc/swaps | tr '\t' ' ' --squeeze-repeats | grep "$current_partition" | $AWK '{print $3}'`
		[ "$partition_mountpt" != "swap" ] && partition_mountpt="swap"
		if [ "$partition_size" = "" ] ; then
		    totalsize=0
		    items=0
		    for i in `cat /proc/swaps | tr -s ' ' '\t' | grep -v "Filename" | cut -f3` ; do
			totalsize=$(($totalsize+$i))
			items=$(($items+1))
		    done
		    partition_size=$(($totalsize/$items))
		    [ "$partition_size" -lt "125000" ] && partition_size=125000
		    echo "I'm guessing $c_p is $(($partition_size/1024))MB" >> $LOGFILE
		fi
	    fi
	fi
	[ "$partition_mountpt" = "swap" ] && partition_format="swap"
	if [ "$partition_mountpt" = "" ] && [ "`pvdisplay $current_partition 2> /dev/null`" != "" ] ; then
#	    lvm_dev="`pvdisplay $current_partition | grep -i "VG N" | head -n1 | tr -s ' ' ' ' | cut -d' ' -f3`"
	    partition_mountpt="lvm"
	    partition_format="lvm"
#	    partition_format=`cat $MY_FSTAB | grep $lvm_dev | gawk '{print $3;}'`
	fi
	psz=$partition_size
	echo "Examining $current_partition (mount=$partition_mountpt fmt=$partition_format psz=$psz)" >> $LOGFILE
	[ "$psz" != "lvm" ] && psz=$(($psz/1024))
	if [ "`echo " $IMAGE_DEVS " | grep " $current_partition "`" != "" ] ; then
	    partition_mountpt="image"
	    partition_format="`fdisk -l | tr -s '\t' ' ' | grep "$current_partition " | gawk '{print $(NF-1);}'`"
	    partition_size=$(($partition_size+1)); # just in case
	fi
        if [ "$EXCLUDE_DEVS" ] && [ "`echo " $EXCLUDE_DEVS " | grep " $current_partition "`" ] || [ "`echo " $EXCLUDE_DEVS " | grep " $current_partition "`" ] ; then
            echo "Excluding $current_partition from mountlist" >> $LOGFILE
            continue
        fi
	unofficial_outstring=`printf "\t%-15s %-15s %-15s %7s\n" $current_partition $partition_mountpt $partition_format $psz`
	if [ "$current_partition" = "" ] ; then
	    echo "Unknown partition (outstring = $unofficial_outstring)" >> $LOGFILE
	elif [ "$partition_mountpt" = "" ] ; then
	    if [ "`cat /etc/raidtab | grep device | grep $current_partition`" ] ; then
		partition_mountpt=raid
		partition_format=raid
	    else
		echo "Unknown mountpoint (outstring = $unofficial_outstring)" >> $LOGFILE
	    fi
        elif [ "$partition_format" = "" ] ; then
	    echo "Unknown format (outstring = $unofficial_outstring)" >> $LOGFILE
	elif [ "$partition_size" = "" ] ; then
	    echo "Unknown partition size (outstring = $unofficial_outstring)" >> $LOGFILE
	else
	    printf "\t%-15s %-15s %-15s %7s\n" $current_partition $partition_mountpt $partition_format $psz
	    printf "%s %s %s %s\n" $current_partition $partition_mountpt $partition_format $partition_size >> $mountlist
	fi
    done
}





MakeModuleLoadingScript() {
    local module fname params modpath kver outerloop i modpaths kver searchpath
    outfile=$1
    > $outfile || Die "Cannot create empty $outfile"
    echo "echo -en \"Loading your modules...\"" >> $outfile
    if [ "$YOUR_KERNEL_SUCKS" ] ; then
	kver=$FAILSAFE_KVER
	cd $TMP_ROOT
	searchpath=lib/modules/$kver
    else
	kver=`uname -r`
	searchpath=/lib/modules/$kver
    fi
    for outerloop in 1 2 3 4 5 ; do
	for module in $EXTRA_MODS `ListKernelModules` ; do
	    params=`sed -n "s/^options \\+$module \\+//p" /etc/modules.conf`
	    modpaths=`FindSpecificModuleInPath $searchpath $module`
	    for i in $modpaths ; do
		echo "[ -e $i ] && insmod $i $params > /dev/null 2> /dev/null" | tr '.' '#' | sed s/#o#gz/#o/ | sed s/#o#gz/#o/ | tr '#' '.' >> $outfile
	    done
	done
    done
    echo "echo \"Done.\"" >> $outfile
    chmod +x $outfile
    cd /
}
	    




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



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

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

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



OfferToCopyImagesToDisks() {
    local imagesdir i imagename dev count boot_dev data_dev
    imagesdir=$1
    boot_dev=$2
    data_dev=$3
    echo -en "Would you like to create boot+data floppy disks now (y/n) ?"
    read i
    [ "$i" != "y" ] && [ "$i" != "Y" ] && return
    echo "WARNING! THIS WILL ERASE YOUR FLOPPY DISKS."
    [ ! -e "$boot_dev" ] && Die "Cannot find $boot_dev"
    [ ! -e "$data_dev" ] && Die "Cannot find $data_dev"
    CopyImageToDisk `find $imagesdir | grep mindi | grep boot | grep -v 2880` $boot_dev "boot disk"
    count=1
    for i in `find $imagesdir | grep mindi-data` ; do
        CopyImageToDisk $i $data_dev "data disk #$count"
        count=$(($count+1))
    done
}




OfferToMakeBootableISO() {
    local i old_pwd
    if [ ! "`DidMondoCallMe`" ] ; then
        echo -en "Shall I make a bootable CD image? (y/n) "
        read i
        [ "$i" != "y" ] && [ "$i" != "Y" ] && return 0
    fi
    rm -Rf $TMP_ROOT/iso
    mkdir -p $TMP_ROOT/iso/{images,archives}
    cp $1/{*.img,*.gz} $TMP_ROOT/iso/images || LogIt "[line 857] cannot copy $i to $TMP_ROOT/iso/images"
    old_pwd=`pwd`
    cd $TMP_ROOT/iso
    mkisofs -b images/mindi-boot.2880.img -c boot.cat -r . > $imagesdir/mindi.iso 2> /tmp/$$.mk
    if [ "$?" -ne "0" ] ; then
	echo "----------- mkisofs's errors --------------" >> $LOGFILE
	cat /tmp/$$.mk >> $LOGFILE
	echo "mkisofs returned the following errors:-"
	cat /tmp/$$.mk
	LogIt "Failed to create ISO image."
    else
	echo "Created bootable ISO image at $imagesdir/mindi.iso" >> $LOGFILE
    fi
    rm -f /tmp/$$.mk
    cd $old_pwd
}



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



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

    retval=0
    [ ! -e "$kernelpath" ] && Die "PBDI - cannot find $kernelpath kernel"
    echo -en "Making "$disksize"KB boot disk..."
    TurnTgzIntoRdz $MINDI_HOME/rootfs.tgz $TMP_ROOT/mindi.rdz $ramdisksize $disksize `du -sk $kernelpath | cut -f1` || Die "Could not turn rootfs.tgz into mindi.rdz; are you SURE your kernel supports loopfs?"
    [ "$disksize" != "1722" ] && [ "$disksize" != "2880" ] && Die "PDBI - disksize is $disksize - bad size"
    echo -en "..."
    imagefile=$imagesdir/mindi-boot.$disksize.img
    mountpoint=$TMP_ROOT/mointpoint.$$
    mkdir -p $mountpoint
    dd if=/dev/zero of=$imagefile bs=1k count=$disksize > /dev/null 2> /dev/null || Die "Cannot dd blank file"
    mke2fs -N 26 -m 0 -F $imagefile > /tmp/mke2fs.$$ 2>> /tmp/mke2fs.$$
    [ "$?" -ne "0" ] && cat /tmp/mke2fs.$$
    rm -f /tmp/mke2fs.$$
    mount -t ext2 -o loop $imagefile $mountpoint || LogIt "Cannot mount (PBDI)\n"
# copy Mindi's skeleton fs & lilo/syslinux/whatever stuff into it
    > $mountpoint/lilo.conf
    old_pwd=`pwd`
    cd $mountpoint
    tar -zxf $MINDI_HOME/dev.tgz || LogIt "Cannot untar dev.tgz"
    cd $old_pwd
    losetup /dev/loop0 > /dev/null 2> /dev/null
    [ "$?" -eq "0" ] || losetup /dev/loop2 -d || Die "Please free up /dev/loop0 by typing 'losetup /dev/loop0 -d'.\nReboot if necessary.\n"
    echo -en "boot=/dev/loop0\ndisk=/dev/loop0\n" >> $mountpoint/lilo.conf
    CopyBootBFile $mountpoint/boot.b
    if [ "$disksize" -eq "2880" ] ; then
	echo -en "bios=0x00\nsectors=36\nheads=2\ncylinders=80\n" >> $mountpoint/lilo.conf
    else
	echo -en "bios=0x00\nsectors=21\nheads=2\ncylinders=82\n" >> $mountpoint/lilo.conf
    fi
    echo -en "\
install=/boot.b\n\
map=/boot.map\n" >> $mountpoint/lilo.conf
    if [ "$disksize" -eq "2880" ] && [ "`DidMondoCallMe`" ] ; then
	if [ "$CDRECOVERY" = "yes" ] ; then
	    echo -en "default=RESTORE\n" >> $mountpoint/lilo.conf
	elif [ -e "$MONDO_TMP/start-nfs" ] ; then
	    echo -en "default=iso\n" >> $mountpoint/lilo.conf
	else
	    echo -en "default=interactive\n" >> $mountpoint/lilo.conf
	fi
    else
	echo -en "default=expert\n" >> $mountpoint/lilo.conf
    fi
    if [ "$CDRECOVERY" = "yes" ] ; then
	echo -en "vga=normal\nprompt\nbackup=/dev/null\nmessage=/message\n" >> $mountpoint/lilo.conf
    else
	echo -en "vga=normal\nprompt\nbackup=/dev/null\ntimeout=300\nmessage=/message\n" >> $mountpoint/lilo.conf
    fi
    echo -en "..."
    if [ "$disksize" -eq "2880" ] ; then
	if [ "$CDRECOVERY" = "yes" ] ; then
	    options="RESTORE"
        elif [ "`DidMondoCallMe`" ] ; then
            if [ -e "$MONDO_TMP/start-nfs" ] ; then
                options="iso"
            else
                options="interactive expert compare iso nuke"
# hda hdb hdc hdd"
            fi
        else
            options="expert"
	fi
    else
	options="expert"
    fi
    for i in $options ; do
	ooo=$i
	[ "$ooo" = "RESTORE" ] && ooo="nuke"
	outstr="image=vmlinuz\n\tlabel=$i\n\troot=/dev/ram0\n\tinitrd=/mindi.rdz\n\tappend=\" ramdisk=$ramdisksize ramdisk_size=$ramdisksize "
#        [ "`echo "$i" | grep \"hd[a-d]\"`" ] && outstr="$oustr append=\"$i=ide-scsi\" "
#	[ "`ps ax| grep devfs| grep -v grep`" ] &&outstr=$outstr" devfs=mount"
	outstr=$outstr"$ooo"_mode
	outstr=$outstr"\"\n"
#	[ "$CDRECOVERY" = "yes" ] && outstr=$outstr" alias=RESTORE\n"
	echo -en "$outstr" >> $mountpoint/lilo.conf
    done
#    cp -f $mountpoint/lilo.conf /tmp || LogIt "[line 953] cannot copy $mountpoint/lilo.conf to /tmp"
    cp -f $TMP_ROOT/mindi.rdz $mountpoint
    if [ "$?" -ne "0" ] ; then
	LogIt "Failed to copy $TMP_ROOT/mindi.rdz to $mountpoint"
	cat $TMP_ROOT/mtpt.$$ >> $LOGFILE
	LogIt "Please unload some of your modules and try again."
	rm -f $TMP_ROOT/mtpt.$$
	Die "Cannot incorporate mindi.rdz in bootdisk (kernel / modules too big?)"
    fi
    cat $MINDI_HOME/msg-txt | sed s/ZZZZZ/$MINDI_VER/ | sed s/YYYYY/"Mondo Rescue"/ | sed s/XXXXX/"a cousin of"/ | sed s/DDDDD/"`cat /etc/issue.net | grep -i "linux" | head -n1 | tr ' ' ' ' --squeeze-repeats`"/ | sed s/KKKKK/"`cat /etc/issue.net | grep -i "kernel" | head -n1 | tr ' ' ' ' --squeeze-repeats`"/ | sed s/TTTTT/"`LC_TIME=C date`"/ | sed s/' 'r' 'on' 'an' 'm/' '`uname -r`' 'on' 'an' '`uname -m`/ > $mountpoint/message
#    cp -f $mountpoint/message /tmp
    if [ "$disksize" -eq "2880" ] ; then
	if [ "`DidMondoCallMe`" ] ; then
	    if [ "$CDRECOVERY" = "no" ] ; then
                if [ -e "$MONDO_TMP/start-nfs" ] ; then
                    echo -en "Press <enter> to continue.\n" >> $mountpoint/message
                else
                    echo -en "\
To format and restore all files automatically, type 'nuke' <enter>.\n\
To restore some/all files interactively, type 'interactive' <enter>.\n\
To compare the archives with your filesystem, type 'compare' <enter>.\n\
To boot to a command-line prompt (expert mode), type 'expert' <enter>.\n" >> $mountpoint/message
                fi
	    else
		echo -en "\
To restore your disk to factory defaults, type 'RESTORE' <enter>.\n\
CAUTION: THIS WILL ERASE YOUR WHOLE DISK !!!\n" >> $mountpoint/message
	    fi
	fi
    fi
    echo -en "\n\n\n" >> $mountpoint/message
# copy the kernel across
    rm -Rf $mountpoint/lost+found
    dd if=/dev/zero of=$mountpoint/zero bs=1k count=16 > /dev/null 2> /dev/null
    free_space=`df -k $mountpoint | tail -n1 | tr -s ' ' '\t' | cut -f4`
    cp -f $kernelpath $mountpoint/vmlinuz > /dev/null 2> /dev/null
    if [ "$?" -ne "0" ] ; then
	echo "Files at mountpoint ($mountpoint) :-" >> $LOGFILE
	find $mountpoint >> $LOGFILE
	echo "--- end of list of files ---" >> $LOGFILE
	LogIt "Kernel size = `du -sk $kernelpath | cut -f1` K\nRamdisk free = $free_space K\n\
Sorry, your kernel is too big.\nEither recompile it to reduce its size, or use Mindi's failsafe kernel.\n\
For instructions on using Mindi's failsafe kernel, read the manual.\n"
	retval=$(($retval+1))
    fi
    free_space=`df -k $mountpoint | tail -n1 | tr -s ' ' '\t' | cut -f4`
    max_kernel_size=$(($free_space+`du -sk $kernelpath | cut -f1`))
    echo "Free space left on floppy = $free_space KB" >> $LOGFILE
    echo "Max kernel size on $disksize KB floppy (est'd) = $max_kernel_size K" >> $LOGFILE
# make it bootable
    rm -f $mountpoint/zero
    mkdir -p $mountpoint/etc
    mv $mountpoint/lilo.conf $mountpoint/etc
    if [ "$disksize" -eq "2880" ] ; then
	$LILO_EXE $LILO_OPTIONS -r $mountpoint >> $LOGFILE 2>> $LOGFILE
    else
# 12/28/2001 - if 1.72MB floppy then don't use LILO's optimizations at all
	$LILO_EXE -r $mountpoint >> $LOGFILE 2>> $LOGFILE
    fi
    if [ $? -ne "0" ] ; then
	if [ "`cat $LOGFILE | grep "/tmp/dev\.0"`" ] ; then
	    LogIt "The '/tmp/dev.0' error is NOT Mindi's fault. It is LILO's."
	    LogIt "Please reboot your PC as a workaround."
	    Die "LILO sneezed and Mindo caught a cold. Please read the README / FAQ."
	fi
	LogIt "Cannot run lilo on $mountpoint"
	retval=$(($retval+1))
    fi
    umount $mountpoint || Die "Cannot unmount mountpoint ($mountpoint)"
    echo -en "..."
    rmdir $mountpoint || LogIt "Cannot rmdir (PBDI)\n"
    if [ "$retval" -eq "0" ] ; then
	echo -en "...$DONE\r"
	LogIt $disksize"KB boot disk was created OK\r"
    else
	echo -en "...failed\r"
	LogIt $disksize"KB boot disk was NOT created\r"
	rm -f $imagefile
    fi
    [ "$retval" -ne "0" ] && LogIt "PrepareBootDiskImage() is returning nonzero"
    return $retval
}




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

    imagesdir=$1
    rm -f $imagesdir/mindi-*.img $imagesdir/[0-9]*.tar.gz $imagesdir/mindi.iso
    needlist=$TMP_ROOT/what-we-need.txt
    bigdir=$TMP_ROOT/bigdir
    minidir_root=$TMP_ROOT/minidir
    mkdir -p $minidir_root
    mkdir -p $bigdir/usr/bin
    tardir=$TMP_ROOT/tardir
#LogIt "Bah"
    GenerateGiantDependencyList < $MINDI_CONF/deplist.txt $needlist
    res=$?
    if [ "$YOUR_KERNEL_SUCKS" ]; then
	pwd=`pwd`
	cd $TMP_ROOT
        for i in `ListKernelModulePaths | HackPathsToFailsafe` ; do
	    cp --parents -pRdf ./$i $bigdir || Die "PDDI can't cp $i->$bigdir"
	    if [ "`du -sk $i | cut -f1`" -lt "$CHOPSIZE" ] ; then
		cp --parents -pRdf $i $bigdir
	    else
		ChopUpAndCopyFile $i $bigdir $CHOPSIZE $BIGNO
		BIGNO=$(($BIGNO+1))
	    fi
	done
	for i in $EXTRA_MODS ; do
# don't include xfs support unless user has at least one xfs partition;
# xfs module is 4MB in size...
#	    if [ "$i" = "xfs" ] ; then
#		[ "`mount | grep xfs`" = "" ] && continue
#		LogIt "Adding XFS as a module."
#	    fi
	    j=`find lib/modules/$FAILSAFE_KVER -name $i.o 2> /dev/null`
	    [ ! "$j" ] && echo "Warning - cannot find failsafe module $i.o" >> $LOGFILE
	    for k in $j ; do
		if [ "`du -sk $k | cut -f1`" -lt "$CHOPSIZE" ] ; then
		    cp --parents -pRdf $k $bigdir
		else
		    ChopUpAndCopyFile $k $bigdir $CHOPSIZE $BIGNO
		    BIGNO=$(($BIGNO+1))
		fi
		echo "Added failsafe module $k to ramdisk" >> $LOGFILE
	    done
	done
	cd $pwd
    else
	ListKernelModulePaths >> $needlist
    fi
    if [ "$res" -ne "0" ] ; then
	rm -f /tmp/mindi-needlist.txt
	Die "You have $res file`PluralOrNot $res` present in dependency list\nbut absent from filesystem."
    fi
    FindAndAddUserKeyboardMappingFile
#LogIt "Humbug"
#exit 1
    mkdir -p $bigdir/tmp
    MakeMondoConfigFile $bigdir/tmp/mondo-restore.cfg
    DropOptimizedLibraries $needlist $bigdir
    echo -en "Assembling dependency files"
    CopyDependenciesToDirectory < $needlist $bigdir

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

# more stuff
    cp -f $MINDI_HOME/embleer* $bigdir
    old_pwd=`pwd`
    cd $bigdir

    [ -e "$MINDI_HOME/aux-tools.tgz" ] && tar -zxf $MINDI_HOME/aux-tools.tgz || Die "Error unzipping aux-tools.tgz"
    if [ -e "$MONDO_HOME/restore-scripts.tgz" ] ; then
        tar -zxf $MONDO_HOME/restore-scripts.tgz
        [ "$?" -ne "0" ] && [ "`DidMondoCallMe`" ] && Die "Cannot find/install $MINDI_HOME/restore-scripts.tgz"
    fi
    [ -d "/lib/dev-state" ] && cp --parents -pRdf /lib/dev-state .
    cd $old_pwd
    echo -e "$DONE"
    TOTAL_BIGDIR_SIZE=`du -sk $bigdir | cut -f1`
    SplitDirectoryIntoMinidirs $bigdir $minidir_root
    noof_disks=$?
    [ "$noof_disks" -eq "0" ] && Die "Too much stuff!"
    MakeMountlist $minidir_root/$noof_disks/tmp/mountlist.txt
    [ "`DidMondoCallMe`" ] && cp -f $minidir_root/$noof_disks/tmp/mountlist.txt $MONDO_TMP/.
    [ -d "/proc/lvm" ] && $MINDI_HOME/analyze-my-lvm > $minidir_root/$noof_disks/tmp/i-want-my-lvm
    cat $minidir_root/$noof_disks/tmp/mountlist.txt >> $LOGFILE
    ZipMinidirsIntoTarballs $minidir_root $tardir $noof_disks
    CreateDataDiskImagesFromTarballs $tardir $imagesdir $noof_disks
    FRIENDLY_OUTSTRING="One 1.72MB boot disk, one 2.88MB boot disk and $noof_disks data disks were created."
    rmdir $tardir $bigdir
    rm -f $needlist
    return $noof_disks
}


ProcessLDD() {
    local main_fname incoming j i fname f newf
    main_fname=$1
    read incoming
    while [ "$incoming" != "" ] ; do
	incoming=`echo "$incoming" | tr -s ' ' '\t'`
	i=`echo "$incoming" | cut -f2`
	if [ "$i" = "=>" ] ; then
	    for fname in `echo "$incoming" | cut -f1,3` ; do
		fname=`LocateFile $fname`
		for f in $fname ; do
		    echo $f
		done
	    done
	fi
	read incoming
    done
}



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



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



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

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


    cd $old_pwd
    return



# do some awk/gawk stuff
    cd $minidir_root
    awk_loc=`find -name awk`
    gawk_loc=`find -name gawk`
#    echo "awk_loc = $awk_loc"
#    echo "gawk_loc= $gawk_loc"
    if [ "$awk_loc" = "" ] && [ "$gawk_loc" != "" ] ; then
        for i in $gawk_loc ; do HackAwk $i gawk ; done
    elif [ "$gawk_loc" = "" ] && [ "$awk_loc" != "" ] ; then
        for i in $awk_loc ; do HackAwk $i awk ; done
    elif [ "$gawk_loc" != "" ] && [ "$awk_loc" != "" ] ; then
        echo -en "Gawk/awk found. Good.\r"
    else
        Die "Look, I don't want to come across as having an attitude, but you need either awk or gawk. Get a distro that doesn't suck, okay? :-)"
    fi
    cd $old_pwd
}



SizeOfPartition() {
    local devpath drive res stub
    device=$1
    if [ "`echo "$device" | grep "/dev/md"`" != "" ] ; then
	res=`cat /etc/raidtab | grep -v "#" | SizeOfRaidPartition $device`
	[ "$res" = "" ] && Die "Cannot find $device's size - is your /etc/raidtab sane?"
	echo "$res"
	return 0
    fi
    res=`fdisk -l | grep -w "$device" | tr '*' ' ' | tr -s '\t' '|' | tr -s ' ' ' ' | cut -d' ' -f4 | sed s/+//`
    [ "$res" = "" ] && res=`df -k -x supermount | tr -s '\t' ' ' | grep "$device " | cut -d' ' -f2`
    [ "$res" = "" ] && res="-1"
    echo $res
    return 0
}


SizeOfRaidPartition() {
    local incoming md_dev real_devs this_device tmp smallest_size silly
    md_dev=$1
    real_devs=""
    silly=999999999
    smallest_size=$silly
    incoming=`ReadLine`

# find the "raiddev" line
    while [ "$incoming" != "" ] && [ "`echo "$incoming" | grep "$1"`" = "" ] ; do
	incoming=`ReadLine`
    done
    [ "$incoming" = "" ] && return 1
    incoming=`ReadLine`
    while [ "$incoming" != "" ] && [ "`echo "$incoming" | grep "raiddev"`" = "" ] ; do
	if [ "`echo "$incoming" | grep "device"`" != "" ] ; then
	    this_device=`echo "$incoming" | sed s/device// | tr -s '\t' ' ' | cut -d' ' -f2`
	    real_devs="$real_devs $this_device"
	    tmp=`SizeOfPartition $this_device`
	    [ "$tmp" -lt "$smallest_size" ] && smallest_size=$tmp
	fi
	incoming=`ReadLine`
    done
#    echo "Partitions found that are part of RAID $md_dev: '$real_devs'"
#    echo "Smallest one = $smallest_size"
    if [ "$smallest_size" = "$silly" ] ; then
	echo "-1"
	return 1
    else
	echo "$smallest_size"
	return 0
    fi
}


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




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






SplitDirectoryIntoMinidirs() {
    local bigdir minidir_root i noof_disks old_pwd res
    bigdir=$1
    minidir_root=$2
    rm -Rf $minidir_root/*

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



TryToFindKernelPath() {
    local fname incoming res fkern_ver we_want_version possible_kernels noof_kernels kernelpath kdate
    we_want_version=`uname -r`
    possible_kernels=""
#    for fname in `find /.plomb/boot /boot /linux / -maxdepth 1 2> /dev/null` ; do
    for fname in `find / -maxdepth 2 -type f | grep lin | grep -v /proc/` ; do
	[ ! -e "$fname" ] && continue
        fkern_ver=`strings $fname | grep "[2-9]+*[.][0-9]+*[.][0-9]+*[^\@]*@"`
        [ "$fkern_ver" = "" ] && continue
        [ "`echo "$fkern_ver" |grep "$we_want_version "`" = "" ] && continue
	[ -f "$fname" ] || continue
	[ -h "$fname" ] && continue
	kdate=`uname -v`
	if [ "`strings $fname | grep "$kdate"`" = "" ] ; then
	    LogIt "Have you recompiled your kernel w/o rebooting? Naughty but I'll allow it..."
#	    continue
	fi
	[ "`echo "$fname" | grep "vmlinux"`" ] && continue
        possible_kernels="$fname $possible_kernels"
    done
    possible_kernels=`echo "$possible_kernels" | tr -s ' ' '\n' | sort | uniq | tr '\n' ' '`
    noof_kernels=`CountItemsIn "$possible_kernels"`
    if [ "$noof_kernels" -eq "0" ] ; then
        LogIt "Could not find your kernel.\n"
        echo ""
    elif [ "$noof_kernels" -eq "1" ] ; then
        kernelpath=`echo "$possible_kernels" | sed s/' '//`
        LogIt "Your kernel is $kernelpath (v`uname -r`)"
        echo "$kernelpath"
    else
        LogIt "Two or more possible kernels found. You may specify any one of them and the "
	LogIt "boot disks will still work, probably. If one does not work, try another."
        LogIt "$possible_kernels\n"
        echo ""
    fi
}




TryToFitDataIntoSeveralDirs() {
    local bigdir minidir_root noof_disks diskno list_of_files filename old_pwd progress
    local i retval noof_disks total_files list_of_devs
    bigdir=$1
    minidir_root=$2
    BIG_CLUNKY_SIZE_COUNTER=0
    retval=0
    noof_disks=1

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


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


#WhichOfTheseModulesAreLoaded "$@"
#exit 0

TurnTgzIntoRdz() {
    local tgz_fname rdz_fname ramdisksize tempfile mountpoint old_pwd nodes disksize kernelsize maxsize res currsize not_copied j k floppy_modules
    tgz_fname=$1
    rdz_fname=$2
    ramdisksize=$3
    disksize=$4
    kernelsize=$5
    maxsize=$(($disksize-$kernelsize))
    maxsize=$(($maxsize*2)); # to allow for compression of 50%
    tempfile=$TMP_ROOT/temp.rd
    mountpoint=$TMP_ROOT/mnt1
    res=0
    echo -en "..."
    dd if=/dev/zero of=$tempfile bs=1k count=$ramdisksize > /dev/null 2> /dev/null || Die "Not enough room for temporary ramdisk (TurnTgzIntoRdz)"
    echo -en "..."
# ---------- used to be $LOOPDEVICE that was formatted.. but newer kernels
# don't like that, so I've changed it to $imagefile
# -i 1024
    mke2fs -i 1024 -m 0 -F $tempfile > /tmp/mke2fs.$$ 2> /tmp/mke2fs.$$
    [ "$?" -ne "0" ] && cat /tmp/mke2fs.$$
    rm -f /tmp/mke2fs.$$
    echo -en "..."
    mkdir -p $mountpoint
    mount -t ext2 -o loop $tempfile $mountpoint || Die "Cannot loopmount $tempfile to $mountpoint"
    echo -en "..."
    old_pwd=`pwd`
    cd $mountpoint
    tar -zxf $tgz_fname 2> $TMP_ROOT/tar-err.txt
#    res=$(($res+$?))
#    if [ "$res" -ne "0" ] ; then
#	cd /
#	umount $mountpoint || LogIt "Warning - unable to unmount loopfs (does your kernel support loopfs?)"
#	cat $TMP_ROOT/tar-err.txt
#	Die "Failed to extract $tgz_fname to $mountpoint"
#    fi
    cp --parents -Rdf /dev/fd0*[1,2][4,7,8]* .
    cd $old_pwd
    echo -en "..."
    MakeModuleLoadingScript $mountpoint/sbin/insert-all-my-modules
    cp -f $mountpoint/sbin/insert-all-my-modules /tmp/IAMM
    echo -en "..."
    old_pwd=`pwd`
    if [ "$YOUR_KERNEL_SUCKS" ] ; then
	cd $TMP_ROOT
#	tar -x --use-compress-program bzip2 -f- < $MINDI_HOME/lib.tar.bz2
	floppy_modules_path=lib/modules/$FAILSAFE_KVER
    else
	cd /
	floppy_modules_path=lib/modules/`uname -r`
    fi
    floppy_modules=""
    if [ "$disksize" -eq "2880" ] ; then
	list_of_groovy_mods="$CDROM_MODS `WhichOfTheseModulesAreLoaded "$SCSI_MODS"`"
    else
# was just "$FLOPPY_MODS" before v0.51; at v0.51, I added .. well, you can
# see what :) so that I can access tape after booting from first floppy.
	list_of_groovy_mods="$FLOPPY_MODS `WhichOfTheseModulesAreLoaded "$SCSI_MODS"`"
    fi
    [ -e "$floppy_modules_path" ] || Die "path $floppy_modules_path does not exist"
    for i in $list_of_groovy_mods ; do
	floppy_modules="$floppy_modules `FindSpecificModuleInPath $floppy_modules_path $i`"
    done
#    LogIt "Copying '$floppy_modules' to initrd ramdisk (bound for $disksize KB floppy)"
    for i in $floppy_modules ; do
	[ "$YOUR_KERNEL_SUCKS" ] && i=$TMP_ROOT/$i
	echo "Adding $i to the rootfs" >> $LOGFILE
	cp -df $i $mountpoint/ || LogIt "Unable to copy $i to $mountpoint"
	[ "`echo "$i" | grep "\.gz"`" ] && gunzip -f $mountpoint/`basename $i`
    done
#    if [ -e "/sbin/devfsd" ] ; then
#	echo "Copying devfs stuff to ramdisk" >> $LOGFILE
#	for i in /etc/devfsd.conf /etc/modules.devfs /lib/dev-state /sbin/devfsd ; do
#	    cp --parents -pRdf $i $mountpoint/
#	done
#    fi
    cd $old_pwd
    [ "$TAPEDEV" ] && echo -en "$TAPEDEV" > $mountpoint/tmp/TAPEDEV-LIVES-HERE
    [ "$TAPESIZE" ]&& echo -en "$TAPESIZE"> $mountpoint/tmp/TAPESIZE
    echo -en "$FILES_IN_FILELIST" > $mountpoint/tmp/FILES-IN-FILELIST
    echo -en "$LAST_FILELIST_NUMBER" > $mountpoint/tmp/LAST-FILELIST-NUMBER
    [ "$USE_LZO" = "yes" ] && echo -en "Pras 4 Pres 2004" >> $mountpoint/tmp/USING-LZO
    dd if=/dev/zero of=$mountpoint/zero > /dev/null 2> /dev/null
    rm -f $mountpoint/zero
    MakeMondoConfigFile $mountpoint/tmp/mondo-restore.cfg
    [ "`DidMondoCallMe`" ] && cp -f $mountpoint/tmp/mondo-restore.cfg $MONDO_TMP
    umount $mountpoint || Die "Cannot unmount $tempfile"
    gzip -9 $tempfile
    mv $tempfile.gz $rdz_fname
    if [ "$res" -eq "0" ] ; then
        echo -en "..."
    else
        echo -en "\rMade an rdz WITH ERRORS.           \n"
    fi
#    return $res
    return 0
}



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

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




##############################################################################
#----------------------------------- main -----------------------------------#
##############################################################################

> $LOGFILE
MINDI_HOME=`GetHomeDir mindi 2> /dev/null`
[ ! -e "$MINDI_HOME" ] && MINDI_HOME=`find /usr/{local,share} -type d -name mindi -maxdepth 2 | grep -v "1\.[2-9]x" | head -n1`
MONDO_HOME=`GetHomeDir mondoarchive 2> /dev/null`
[ ! -e "$MONDO_HOME/restore-scripts.tgz" ] && MONDO_HOME=`find /usr/{local,share} -type d -name mondo -maxdepth 2 | grep -v "1\.[2-9]x" | head -n1`
[ ! -e "$MINDI_HOME" ] && MINDI_HOME=`find /usr/{local,share} -type d -name mindi -maxdepth 2 | grep -v "1\.[2-9]x" |  grep -v "/doc" | head -n1`
[ ! -e "$MONDO_HOME/restore-scripts.tgz" ] && MONDO_HOME=`find /{opt,usr} -type d -name mondo -maxdepth 2 2> /dev/null | grep -v "1\.[2-9]x" | grep -v "/doc/" | head -n1`
[ ! -e "$MONDO_HOME/restore-scripts.tgz" ] && MONDO_HOME=`find /{opt,usr} -type d -name mondo -maxdepth 2 2> /dev/null | grep -v "1\.[2-9]x" | grep -v "/doc/" | tail -n1`
[ ! -e "$MONDO_HOME/restore-scripts.tgz" ] && MONDO_HOME=""
[ ! -e "$MINDI_HOME/aux-tools.tgz" ] && Die "Cannot find aux-tools.tgz"
echo "MINDI_HOME = $MINDI_HOME" >> $LOGFILE
echo "MONDO_HOME = $MONDO_HOME" >> $LOGFILE
[ -e "/etc/mindi" ] && MINDI_CONF=/etc/mindi || MINDI_CONF=$MINDI_HOME

which which > /dev/null 2> /dev/null || Die "Please install 'which'."
if [ ! "`which mke2fs > /dev/null 2> /dev/null`" ] ; then
    PATH=$PATH:/sbin:/usr/sbin
    export PATH
    echo "Your PATH did not include /sbin or /usr/sbin. I have fixed that, temporarily." >> $LOGFILE
    echo "However, you may wish to ask your vendor to provide a permanent fix..." >> $LOGFILE
fi
[ "`uname -r | grep "2.4.[0-6]" | grep -v "2.4.[0-9][0-9]"`" != "" ] &&  echo "WARNING! Your kernel may have buggy loopfs code. Consider upgrading to 2.4.7"
[ ! -e "/etc/modules.conf" ] && Die "/etc/modules.conf not found; you may have to create a softlink from /etc/conf.modules to /etc/modules.conf; of course, all good distros use modules.conf anyway..."
which strings > /dev/null 2> /dev/null || Die "Please install binutils and libbinutils; you have no 'strings' executable."
which awk > /dev/null 2> /dev/null && AWK=`which awk` || AWK=`which gawk`
which mke2fs > /dev/null 2> /dev/null || Die "Please put mkfs.ext2 in system path"
which afio > /dev/null 2> /dev/null || LogIt "afio not found... mindi doesn't need afio but Mondo does... Be aware...\n"
if which lilo.real > /dev/null 2> /dev/null ; then
    LILO_EXE=lilo.real
    LogIt "lilo.real found; will be used instead of lilo (*grumble* *mutter*)"
else
    LILO_EXE=lilo
fi
$LILO_EXE -V | grep "21\.6" > /dev/null && Die "Please upgrade LILO."
cat /proc/mounts | grep " $TMP_ROOT " | grep tmps > /dev/null 2> /dev/null && TMP_ROOT=/home && LogIt "Changing TMP_ROOT to $TMP_ROOT because you're using tmpfs for /tmp" ; # tmpfs doesn't like Mindi, for some reason
rm -f /tmp/mindi_lo
trap "Aborted" SIGTERM
DONE="\r\t\t\t\t\t\t\t\t\tDone."
CHOPSIZE=200
BIGNO=0
MAX_COMPRESSED_SIZE=1400; # if >1410 then some users get weird errors
imagesdir=/root/images/mindi
mkdir -p $imagesdir
kernelpath=""

if [ "$#" -ne "0" ] ; then
    if [ "$#" -ge "9" ] && [ "$1" = "--custom" ] ; then
#	TMP_ROOT=$2
	MONDO_TMP=$2
	imagesdir=$3
	kernelpath=$4; [ "$kernelpath" = "(null)" ] && kernelpath=""
	TAPEDEV=$5
	TAPESIZE=$6
	FILES_IN_FILELIST=$7
	USE_LZO=$8
	CDRECOVERY=$9
        if [ "${10}" = "(null)" ] || [ "${10}" = "" ] ; then
            IMAGE_DEVS=""
        else
            IMAGE_DEVS="`echo "${10}" | tr '|' ' '`"
        fi
	if [ "${11}" ] ; then
	    LILO_OPTIONS=""
	    LogIt "LILO will use conservative settings, to be compatible with older BIOSes."
#	else
#	    LogIt "LILO will merge sector-seeks. I assume your BIOS is <2 years old."
	fi
	LAST_FILELIST_NUMBER=${12}
        ESTIMATED_TOTAL_NOOF_SLICES=${13}
        EXCLUDE_DEVS="${14}"
#        LogIt "IMAGE_DEVS = '$IMAGE_DEVS'"
	[ "$TAPEDEV" ] && LogIt "This is a tape-based backup. Fine."
	[ "$kernelpath" = "" ] && kernelpath=`TryToFindKernelPath`
	[ "$CDRECOVERY" = "yes" ] && [ "$TAPEDEV" != "" ] && Die "Sorry, you can't use --cd-recovery and --write-tapes at the same time"
    else
	echo "Syntax: mindi (--custom <temp path> <dest path> <kernel path> <tapedev | ''> <tapesize | ''> <files in filelist> <use_lzo> <cdrecovery>" >> /dev/stderr
	exit 1
    fi
fi
rm -Rf $TMP_ROOT/mindilinux/*
TMP_ROOT=$TMP_ROOT/mindilinux/$$
mkdir -p $TMP_ROOT
mkdir -p $imagesdir
if [ ! "`DidMondoCallMe`" ] ; then
    LogIt "Mindi Linux mini-distro generator v$MINDI_VER by HRabson <hugo@firstlinux.net>"
    LogIt "------------------------------------------------------------------------------"
else
    echo "You are using Mindi-Linux v$MINDI_VER to make boot+data disks" >> /var/log/mondo-archive.log
fi
FILE_CACHE=$TMP_ROOT/mindi-file-loc-cache

if [ "$kernelpath" = "" ] ; then
    [ "`DidMondoCallMe`" ] && Die "Please use -k <path> or --my-kernel <path> to specify kernel."
    echo -en "Do you want to use your own kernel to build the boot disk (y/n) ?"
    read ch
    if [ "$ch" != "n" ] && [ "$ch" != "N" ] ; then
	YOUR_KERNEL_SUCKS=""
	kernelpath=`TryToFindKernelPath`
	if [ "$kernelpath" = "" ] ; then
	    echo -n "Please enter kernel path : "
	    read kernelpath
	fi
    else
	YOUR_KERNEL_SUCKS="That's why you're using mine, dude. :-)"
    fi
fi
if [ "$YOUR_KERNEL_SUCKS" != "" ] || [ "$kernelpath" = "" ] || [ "$kernelpath" = "SUCKS" ] || [ "$kernelpath" = "FAILSAFE" ] ; then
    kernelpath=$MINDI_HOME/vmlinuz
    LogIt "I shall include Mindi's failsafe kernel, not your kernel, in the boot disks."
    LogIt "However, you are still running your kernel. If Mindi fails to create your"
    LogIt "disks then it may still be a result of a problem with your kernel."
    pwd=`pwd`
    cd $TMP_ROOT
#    tar -x --use-compress-program bzip2 -f- < $MINDI_HOME/lib.tar.bz2 || Die "Cannot unzip lib.tar.bz2"
#    tar -x --use-compress-program bzip2 -f $MINDI_HOME/lib.tar.bz2 || Die "Cannot unzip lib.tar.bz2"
    bzip2 -dc $MINDI_HOME/lib.tar.bz2 | tar -x || Die "Cannot unzip lib.tar.bz2"
    cd $pwd
    YOUR_KERNEL_SUCKS="Your kernel sucks"
fi
echo -e "Mindi's temp dir = $TMP_ROOT \nMindi's output dir=$imagesdir" >> $LOGFILE
[ "$(($RANDOM%64))" -eq "0" ] && LogIt "Dude, I've looked inside your computer and it's really dusty..."
rm -f /tmp/mindi.err.*.tgz
PrepareDataDiskImages $imagesdir
noof_disks=$?
ramdisk_size=$(($size_of_all_tools+$TOTAL_BIGDIR_SIZE+EXTRA_SPACE))
echo "Ramdisk will be $ramdisk_size KB" >> $LOGFILE
PrepareBootDiskImage $imagesdir 1722 $kernelpath $ramdisk_size || LogIt "Warning! Failed to create 1.72MB boot image. Please reduce your kernel's size if you want to make a 1.72MB floppy floppy disk. This error is non-fatal if you are backing up to CD or NFS."
PrepareBootDiskImage $imagesdir 2880 $kernelpath $ramdisk_size || Die "Failed to create 2.88MB floppy disk image."
if [ ! "`DidMondoCallMe`" ] ; then
    ListImagesForUser $imagesdir
    boot_dev=/dev/fd0u1722
    [ ! -e "$boot_dev" ] && mknod $boot_dev b 2 60
    [ ! -e "$boot_dev" ] && boot_dev=/dev/fd0H1722
    [ ! -e "$boot_dev" ] && Die "Oh Lord, will you PLEASE tell the vendor to create the 1.72MB devices in /dev?"
    OfferToCopyImagesToDisks $imagesdir $boot_dev $FDDEVICE
    OfferToMakeBootableISO $imagesdir
    LogIt "Finished.\n"
elif [ "$TAPEDEV" ] ; then
    mkdir -p /root/images/mindi
    rm -f /root/images/mindi/{*img,*gz,*iso}
#    LogIt "You may 'dd' the boot+data disks from /root/images/mindi at your leisure."
#    LogIt "... e.g. # dd if=/root/images/mindi/mindi-boot.1440.img of=$FDDEVICE"
#    OfferToCopyImagesToDisks $imagesdir /dev/fd0u1722 $FDDEVICE
    OfferToMakeBootableISO $imagesdir
    if [ -e "$imagesdir/all.tar.gz" ] ; then
#	echo -en "Writing extended data disk to beginning of tape ($TAPEDEV)"
#        dd if=$imagesdir/all.tar.gz of=$TAPEDEV 2> /dev/null
#	LogIt -e "$DONE"
        cp -f $imagesdir/all.tar.gz $MONDO_TMP/
    else
	Die "Cannot find all.tar.gz, to be written to tape"
    fi
else
    OfferToMakeBootableISO $imagesdir
fi
if [ "$imagesdir" != "/root/images/mindi" ] ; then
    for i in `find $imagesdir -maxdepth 1 | grep "[i][s|m][g|o]"` ; do
	cp -f $i /root/images/mindi || LogIt "[line 1613] Cannot copy $i to /root/images/mindi"
    done
fi
[ "$TMP_ROOT" != "/tmp" ] && rm -Rf $TMP_ROOT
rm -Rf /tmp/mindi-needlist.txt /tmp/mountlist.txt.$$
LogIt "$FRIENDLY_OUTSTRING"
echo "Mindi is exiting" >> $LOGFILE
exit 0













