#!/bin/sh
#
# 02/18/02
# - use a ramdisk for /tmp (after copying old /tmp stuff into it)
#
# 02/13/02
# - fixed segfaults ('open') by replacing 'sh' call with '/bin/sh' call
#
# 02/11/02
# - changed LaunchTerminals() to try to work with newly-compiled 'open'
# - don't write 'start-nfs error' if start-nfs doesn't exist; just go on
#
# 01/25/02
# - added tmpfs and some space-checking
#
# 01/10/02
# - cleaned up script
#
# 01/09/02
# - added stuff to start NFS services if necessary
# - reordered some of the main() stuff, for elegance's sake
#
# 01/06/02
# - added Petris and 'tail -f /tmp/mondo-restore.log' to LaunchTerminals()
#
# 01/03/02
# - changed /usr/share/ to /usr/local/
#
# 12/24/01
# - fix some typos
#
# 12/22/01
# - added lots of cool stuff to make Mindi _nearly_ boot from tape
#
# 12/10/01
# - restructured the welcome msg echoed to screen
#
# 12/09/01
# - broke up spaghetti code; made lots of subroutines
#
#------------------------------------------------------------


ConfigureLoggingDaemons() {
    echo -en "Running klogd..."
    klogd -c 1 > /dev/null 2> /dev/null
    echo -en "Done.\nRunning syslogd..."
    syslogd > /dev/null 2> /dev/null
    echo "Done."
    LogIt "klogd and syslogd have been started."
}



Die() {
    LogIt "Fatal error! $1" 1
    exec sh
}




LaunchTerminals() {
#    for i in 2 3 4 5 6 ; do
#        startsess tty$i /bin/sh
#    done
#    startsess tty7 /bin/sh /sbin/wait-for-petris
#    startsess tty8 /usr/bin/tail -f /tmp/mondo-restore.log

    open -c 2 /bin/sh
    open -c 3 /bin/sh
    open -c 4 /bin/sh
    open -c 5 /bin/sh
    open -c 6 /bin/sh
    open -c 7 -- /bin/sh /sbin/wait-for-petris
    open -c 8 -- /usr/bin/tail -f /tmp/mondo-restore.log
}


LoadKeymap() {
    local fname
    fname=`cat /tmp/KEYMAP-LIVES-HERE 2> /dev/null`
    [ "$fname" = "" ] && return
    if which loadkeys > /dev/null 2> /dev/null ; then
        loadkeys $fname
# loadkmap != loadkeys
#    elif which loadkmap > /dev/null 2> /dev/null ; then
#        loadkmap < $fname
    else
        LogIt "Using default keyboard map." 1
    fi
}


HandleTape() {
    local res
    tapedev=`cat /tmp/mondo-restore.cfg | grep tapedev | tr -s ' ' ' ' | cut -d' ' -f2`
    cd /mnt/groovy-stuff
    tar -zxf $tapedev
    if [ "$?" -ne "0" ] ; then
	cd /
	LogIt "Failed to use tape as extended datadisk. Reverting to floppies." 1
	HandleCDROMorFloppies
	res=$?
    else
	clear
	LogIt "Using tape as extended datadisk. Good." 3
	echo "Using tape as extd ddisk." > /tmp/TAPEDEV-HAS-DATA-DISKS
	res=0
        CD_MOUNTED_OK=yes
    fi
    return $res
}



HandleCDROMorFloppies() {
    find-and-mount-cdrom
    res=$?
    if [ "$res" -eq "0" ] ; then
        clear
	LogIt "OK, I am running on a CD-ROM. Good." 3
        CD_MOUNTED_OK=yes
    elif [ "$res" -eq "1" ] ; then
        clear
	LogIt "OK, I am running on floppies. Good." 3
	CD_MOUNTED_OK=""
    else
	LogIt "OK, I am falling back to floppy mode." 3
	CD_MOUNTED_OK=""
    fi
    return 0
}


HowMuchFreeSpaceOnRamdisk() {
   df -m | grep /dev/ram | head -n1 | tr -s '\t' ' ' | cut -d' ' -f4
}



InsertEssentialModules() {
    for j in 1 2 3 4 ; do
        for i in `ls /*.o* 2> /dev/null` ; do
            [ -f "$i" ] && insmod $i > /dev/null 2> /dev/null
        done
    done
}



PauseForRaids() {
    if [ "`dmesg | grep -i "RAID Controller"`" != "" ] || [ "`dmesg | grep -i "Vendor: 3ware"`" != "" ] ; then
        LogIt "RAID controller(s) detected. Pausing 10 seconds to let them warm up." 1
        echo -en "Pausing..."
        for i in 1 2 3 4 5 6 7 8 9 10 ; do
            sleep 1
            echo -en "$(($i*10))%..."
        done
        echo "Done."
    fi
}


RunDevfsd() {
    loc=`which devfsd 2> /dev/null`
    if [ "$loc" != "" ] ; then
        LogIt "Starting devfsd"
        devfsd /dev &
        sleep 5
    fi
}



SpaceTests() {
    [ -e "/tmp/filelist.full" ] && cp /tmp/filelist.full /tmp/FLF
    if [ "`HowMuchFreeSpaceOnRamdisk`" -le "3" ] ; then
        LogIt "Ramdisk is a bit smaller than I would like." 1
        LogIt "Please re-run Mondo/Mindi but edit /usr/local/mindi first" 1
        LogIt "and set EXTRA_SPACE to something high, e.g. 8000" 1
        Die "Aborting. Please reboot."
    fi
    rm -f /tmp/FLF
}



StartLvms() {
    if [ -e "/tmp/i-want-my-lvm" ] ; then
        LogIt "Scanning LVM's..." 1
        vgscan
        cat /tmp/i-want-my-lvm | grep "# vgchange" | sed s/#// > /tmp/start-lvm
        chmod +x /tmp/start-lvm
        echo -en "Starting LVM's..."
        /tmp/start-lvm &
        for i in 1 2 3 4 5 ; do
	    echo -en "."
	    sleep 1
        done
        echo "Done."
    fi
# If necessary, cannibalize 'analyze-my-lvm'; copy some of its code here,
# pipe vgscan's output, strip it, run 'vgchange' on its output, etc.etc.
    LogIt "LVM's have been started."
}



StartNfs() {
    if which portmap > /dev/null 2> /dev/null ; then
        LogIt "Running portmap"
	portmap
        [ "$?" -eq "0" ] && LogIt "Portmap started OK" || LogIt "Portmap error"
        which start-nfs > /dev/null 2> /dev/null && start-nfs
    fi
}


StartRaids() {
    local raid_devices i
    raid_devices=`cat /tmp/mountlist.txt | grep /dev/md | cut -d' ' -f1`
    for i in $raid_devices ; do
        if cat /proc/mdstat | grep `basename $i` > /dev/null 2> /dev/null ; then
            LogIt "$i is started already; no need to run 'raidstart $i'" 1
        else
	    LogIt "Running 'raidstart $i'" 1
	    raidstart $i
        fi
#        sleep 1
    done
#    [ "$raid_devices" != "" ] && PauseForRaid
}


SwapTheMountExecs() {
    if [ -e "/bin/mount.libc5" ] ; then
        LogIt "Swapping busybox's mount with libc5 mount"
        mv /bin/mount /bin/mount.bb
        mv /bin/mount.libc5 /bin/mount
        sync
    fi
}


TryAgainToFindCD() {
    local res
    [ "`cat /tmp/mondo-restore.cfg | grep "using-cdstream yes"`" ] && return
    LogIt "Trying to mount CD-ROM a 2nd time..."
    find-and-mount-cdrom --second-try
    res=$?
    if [ "$res" -eq "0" ] ; then
        CD_MOUNTED_OK=yes
        LogIt "CD-ROM drive mounted successfully." 1
    else
        LogIt "I still cannot find or mount the CD-ROM drive, by the way."
    fi
}



UseTmpfs()
{
    local mount_cmd
    echo -en "Mounting /tmp/tmpfs..."
    mkdir -p /tmp/tmpfs
# For technical reasons, some sets are as large as 16MB.
# I am allowing 32MB because selective restore occupies a lot of space.
    mount_cmd="mount /dev/shm -t tmpfs -o size=34m"
    $mount_cmd /tmp/tmpfs 2>> /tmp/mondo-restore.log
    if [ "$?" -ne "0" ] ; then
        Die "Failed. UPGRADE YOUR RAM! Please! Dude, your computer is dying of thirst over here..."
        umount /tmp/tmpfs > /dev/null 2> /dev/null
	rmdir /tmp/tmpfs
        ln -sf /mnt/RESTORING/tmp /tmp/tmpfs; # used by mondo-restore
	LogIt "Failed to mount /tmp/tmpfs; using ugly softlink instead"
    else
        echo -en "Pivoting /tmp..."
        umount /tmp/tmpfs
        mkdir -p /tmp.old
        mv -f /tmp/* /tmp.old/
        $mount_cmd /tmp
        mv /tmp.old/* /tmp/
        rmdir /tmp.old
        mkdir -p /tmp/tmpfs
        mkdir -p /mnt/groovy-stuff
	echo "Done."
	LogIt "Successfully mounted dynamic /tmp ramdisk"
    fi
}


WelcomeMessage()
{
#    clear
    echo "********************************************************************"
    echo "MINDI mini-distro by Hugo Rabson --- http://www.microwerks.net/~hugo"
    echo "Boot disk based on AlfaLinux & Trinux. Sbminst by Suzhe & Lonius."
    echo "BusyBox by Erik Andersen. LZO and LZOP by Marcus Oberhumer."
which petris > /dev/null 2> /dev/null && echo "Petris was written by Peter Seidler <p.seidler@mail1.stofanet.dk>."
    echo "Executables and source code are covered by the GNU GPL. No warranty."
    echo "********************************************************************"
}



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


PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/mondo:/usr/local/mondo:/usr/local/mindi:.
export PATH

/bin/update
mount /proc/ /proc -v -t proc 
rm -f /foozero
LaunchTerminals
InsertEssentialModules
UseTmpfs
if [ ! -e "/tmp/mondo-restore.cfg" ] ; then
    LogIt "Warning - /tmp/mondo-restore.cfg not found"
fi
if [ "`cat /tmp/mondo-restore.cfg | grep tapedev`" ] ; then
    HandleTape
else
    HandleCDROMorFloppies
fi
res=$?
insert-all-my-modules > /dev/null &
sleep 2
install-additional-tools
SwapTheMountExecs
ConfigureLoggingDaemons
insert-all-my-modules &
sleep 2
RunDevfsd
PauseForRaids
StartLvms
StartRaids
StartNfs
LoadKeymap
mkdir -p /tmp/tmpfs
WelcomeMessage
# SpaceTests; # Mandrake Linux 8.1 doesn't like this

[ "$res" -ne "0" ] && Die "Unable to process CD-ROM or floppies. Terminating."
[ -e "/tmp/mountlist.txt" ] && cp -f /tmp/mountlist.txt /tmp/mountlist.original
res="`cat /mnt/cdrom/archives/THIS-CD-NUMBER 2> /dev/null`"
[ "$res" != "1" ] && [ "$res" != "" ] && Die "This is CD #$res in the series. Please insert CD #1."
[ "$CD_MOUNTED_OK" != "yes" ] && TryAgainToFindCD
LogIt "Calling post-init $mountlist"
post-init                                     ; # a separate script
echo -en "To reboot, press CTRL-ALT-DEL together.\r"
umount /mnt/cdrom 2> /dev/null
exec sh
