#!/static/sh
#
# BOOYO Linux General Startup Script
#        Myoung Tcheun <tcheun@chollian.net>
#
# Knoppix linuxrc is modified for BOOYO
#
#
# This script needs some of the builtin ash commands (if, test, ...)
# mount/umount, insmod/rmmod are also a builtin in ash-booyo.
#

# hardcoded configurable options
# Default maximum size of dynamic ramdisk in kilobytes
RAMSIZE=1000000
# End of options

# Don't allow interrupt signals
trap "" 1 2 3 15

# "Safe" SCSI modules in the right order for autoprobe
# Warning: The sym53c8xx.o and g_NCR* cause a kernel Oops if no such adapter
# is present.
#
# NB: It looks like that ncr53c8xx.o is more stable than 53c7,8xx.o for
# a ncr53c810 controller (at least on my installation box it's more
# immune to SCSI timeouts)
# Removed 53c7,8xx -> crashes if no device attached.
# Removed AM53C974 -> crashes tmscsim if adapter found
# Added initio.o on request (untested)
# ncr53c8xx.o NCR53c406a.ko mptscsih.o advansys.o aha1740.o 
# dtc.ko eata.ko megaraid.o pas16.ko pci2220i.o pci2000.o 
# psi240i.ko qlogicfc.ko seagate.o t128.ko u14-34f.ko ultrastor.ko 
# wd7000.o
SCSI_MODULES="aic7xxx.ko aic7xxx_old.ko BusLogic.ko \
ncr53c8xx.ko NCR53c406a.ko \
initio.ko mptscsih.ko \
advansys.ko aha1740.ko aha1542.ko aha152x.ko \
atp870u.ko dtc.ko eata.ko fdomain.ko gdth.ko \
megaraid.ko pas16.ko pci2220i.ko pci2000.ko psi240i.ko \
qlogicfas.ko qlogicfc.ko qlogicisp.ko \
seagate.ko t128.ko tmscsim.ko u14-34f.ko ultrastor.ko wd7000.ko \
a100u2w.ko 3w-xxxx.ko"

# Misc functions

INSMOD="/static/insmod"

#RMMOD="/modules/rmmod"

# Builin filesystems
BUILTIN_FS="iso9660 ext2"

mountit(){
# Usage: mountit src dst "options"
# Uses builtin mount of ash.booyo
for fs in $BUILTIN_FS; do
test -b $1 && mount -t $fs $3 $1 $2 >/dev/null 2>&1 && return 0
done
return 1
}

FOUND_SCSI=""
FOUND_BOOYO=""
INTERACTIVE=""

# Clean input/output
exec >/dev/console </dev/console 2>&1

# Reset fb color mode
RESET="]R"
# ANSI COLORS
# Erase to end of line
CRE="
[K"
# Clear and reset Screen
CLEAR="c"
# Normal color
NORMAL="[0;39m"
# RED: Failure or error message
RED="[1;31m"
# GREEN: Success message
GREEN="[1;32m"
# YELLOW: Descriptions
YELLOW="[1;33m"
# BLUE: System mesages
BLUE="[1;34m"
# MAGENTA: Found devices or drivers
MAGENTA="[1;35m"
# CYAN: Questions
CYAN="[1;36m"
# BOLD WHITE: Hint
WHITE="[1;37m"

# Clear screen with colormode reset
# echo "$CLEAR$RESET"
# echo "$CLEAR"
# Just go to the top of the screen
# echo -n "[H[J"
echo ""
# Be verbose
echo "${WHITE}Welcome to the ${CYAN}B${MAGENTA}O${YELLOW}O${WHITE}Y${RED}O${WHITE} live Linux-on-CD!${NORMAL}"
echo ""
echo ""

# We only need the builtin commands and /static at this point
PATH=/static
export PATH

umask 022

# Mount /proc and /dev/pts
mount -t proc /proc /proc

# Disable kernel messages while probing modules in autodetect mode
echo "0" > /proc/sys/kernel/printk

#mount -t devpts /dev/pts /dev/pts
# Kernel 2.6
mount -t sysfs none /sys >/dev/null 2>&1
/static/udevstart

# Read boot command line with builtin cat command (shell read function fails in Kernel 2.4.19-rc1)
CMDLINE="$(cat /proc/cmdline)"

# Check if we are in interactive startup mode
case "$CMDLINE" in *BOOT_IMAGE=expert\ *) INTERACTIVE="yes"; :>/interactive; ;; esac
case "$CMDLINE" in *modules-disk*) INTERACTIVE="yes"; ;; esac
# Does the user want to skip scsi detection?
NOSCSI=""
case "$CMDLINE" in *noscsi*|*nobootscsi*) NOSCSI="yes"; ;; esac
case "$CMDLINE" in *nousb*|*nobootusb*) NOUSB="yes"; ;; esac
case "$CMDLINE" in *nofirewire*|*nobootfirewire*) NOFIREWIRE="yes"; ;; esac
NOCD=""
case "$CMDLINE" in *fromhd*) NOCD="yes"; ;; esac
case "$CMDLINE" in *fromdvd*) FROMDVD="yes"; ;; esac
case "$CMDLINE" in *idecd*|*atapicd*) IDECD="yes"; ;; esac
case "$CMDLINE" in *noideraid*) NOIDERAID="yes"; ;; esac
case "$CMDLINE" in *usb2*) USB2="ehci-hcd.ko"; ;; esac

BOOYO_DIR="BOOYO"
BOOYO_NAME="BOOYO"
case "$CMDLINE" in *booyo_dir=*) BOOYO_DIR="$booyo_dir"; ;; esac
case "$CMDLINE" in *booyo_name=*) BOOYO_NAME="$booyo_name"; ;; esac

BOOYO_DEBUG=""
case "$CMDLINE" in *debug*) echo "6" > /proc/sys/kernel/printk;
BOOYO_DEBUG="yes"; ;; esac

# BOOYO Kernel conig for SCSI and SCSI CDROM is set to M instead of Y on Knoppix.
$INSMOD /modules/scsi/scsi_mod.ko >/dev/null 2>&1
$INSMOD /modules/scsi/sd_mod.ko >/dev/null 2>&1
$INSMOD /modules/scsi/libata.ko >/dev/null 2>&1
$INSMOD /modules/scsi/ata_piix.ko >/dev/null 2>&1
$INSMOD /modules/scsi/sr_mod.ko >/dev/null 2>&1

# Check for IDE-SCSI capable CD-Rom(s)
# BOOYO Kernel conig for ide-cd is set to Y instead of M on Knoppix.
test -n "$IDECD" || $INSMOD /modules/scsi/ide-scsi.ko >/dev/null 2>&1

# Mount module disk
mountmodules(){
TYPE="$1"; shift
echo -n "${CRE}${CYAN}Please insert ${TYPE} modules disk and hit Return. ${NORMAL}"
read a
echo -n "${CRE}${BLUE}Mounting ${TYPE} modules disk... ${NORMAL}"
# We always mount over /modules/scsi (because it's there ;-)
if mountit /dev/fd0 /modules/scsi "-o ro"; then
echo "${GREEN}OK.${NORMAL}"
return 0
fi
echo "${RED}NOT FOUND.${NORMAL}"
return 1
}

# Unmount module disk
umountmodules(){
TYPE="$1"; shift
echo -n "${CRE}${BLUE}Unmounting ${TYPE} modules disk... ${NORMAL}"
umount /modules/scsi 2>/dev/null
echo "${GREEN}DONE.${NORMAL}"
}

# Ask user for modules
askmodules(){
TYPE="$1"; shift
echo "${BLUE}${TYPE} modules available:${WHITE}"
c=""; for m in "$@"; do
if test -f "/modules/scsi/$m"; then
test -z "$c"  && { echo -n "	$m"; c="1"; } || { echo "		$m"; c=""; }
fi
done
[ -n "$c" ] && echo ""
echo "${CYAN}Load ${TYPE} Modules?${NORMAL}"
echo "${CYAN}[Enter full filename(s) (space-separated), Return for autoprobe, ${WHITE}n${CYAN} for none] ${NORMAL}"
echo -n "${CYAN}insmod module(s)> ${NORMAL}"
read MODULES
case "$MODULES" in n|N) MODULES=""; ;; y|"")  MODULES="$*"; ;; esac
}

# Try to load the given modules (full path or current directory)
loadmodules(){
TYPE="$1"; shift
if test -z "$BOOYO_DEBUG"; then
test -n "$INTERACTIVE" && echo "6" > /proc/sys/kernel/printk
fi
for i in "$@"; do
echo -n "${CRE}${BLUE}Probing ${TYPE}... ${MAGENTA}$i${NORMAL}"
if test -f /modules/scsi/$i && $INSMOD -f /modules/scsi/$i >/dev/null 2>&1
then
case "$i" in *ataraid*) ;; *) echo "${CRE} ${GREEN}Found ${TYPE} device(s) handled by ${MAGENTA}$i${GREEN}.${NORMAL}" ;; esac
case "$TYPE" in scsi|SCSI) FOUND_SCSI="yes"; ;; esac
fi
done
if test -z "$BOOYO_DEBUG"; then
test -n "$INTERACTIVE" && echo "0" > /proc/sys/kernel/printk
fi
echo -n "${CRE}"
}

# Check for SCSI, use modules on bootfloppy first
if test -n "$INTERACTIVE"; then
# Let the user select interactively
askmodules SCSI $(cd /modules/scsi; echo *.ko)
else
# these are the autoprobe-safe modules
MODULES="$SCSI_MODULES"
fi
test -z "$NOSCSI" && test -n "$MODULES" && loadmodules SCSI $MODULES
# End of SCSI check

# Check for IDE-Raid devices
# kernel 2.6 does not support ide-raid
#if test -z "$NOIDERAID"; then
#( cd /modules/scsi; { $INSMOD ataraid.ko >/dev/null 2>&1 && $INSMOD silraid.ko >/dev/null 2>&1 ; } || $INSMOD medley.ko >/dev/null 2>&1 || $INSMOD pdcraid.ko >/dev/null 2>&1 )
#fi
# End of IDE-Raid check

# Check for USB, use modules on bootfloppy first
if test -z "$NOUSB"; then
echo -n "${CRE}${BLUE}Checking for for USB...${NORMAL}"
# BOOYO kernel config set usbcore Y
#if test -f /modules/scsi/usbcore.ko; then
#$INSMOD /modules/scsi/usbcore.ko >/dev/null 2>&1
FOUNDUSB=""

# The names of usb host modules are different (2.4 and 2.6?)
#for i in $USB2 usb-uhci.ko usb-ohci.ko; do
for i in ohci-hcd.ko uhci-hcd.ko ehci-hcd.ko; do
test -f /modules/scsi/$i && $INSMOD /modules/scsi/$i >/dev/null 2>&1 && FOUNDUSB="yes"
done
if test -n "$FOUNDUSB"; then
test -f /modules/scsi/usb-storage.ko && $INSMOD /modules/scsi/usb-storage.ko >/dev/null 2>&1
# BOOYO kernel config doesn't support Low Performance USB Block driver
#test -f /modules/scsi/ub.ko && $INSMOD /modules/scsi/ub.ko >/dev/null 2>&1
else
# For an unknown reason, unloading usbcore hangs sometimes
# rmmod usbcore >/dev/null 2>&1
true
fi
echo -n "${CRE}"
fi
# End of USB check

# Check for Firewire, use modules on bootfloppy first
if test -z "$NOFIREWIRE"; then
echo -n "${CRE}${BLUE}Checking for Firewire...${NORMAL}"
if test -f /modules/scsi/ieee1394.ko; then
echo -n "${CRE}${BLUE}Loading ieee1394...${NORMAL}"
$INSMOD /modules/scsi/ieee1394.ko >/dev/null 2>&1
FOUNDFIREWIRE=""
for i in ohci1394.ko; do
echo -n "${CRE}${BLUE}Loading $i...${NORMAL}"
test -f /modules/scsi/$i && $INSMOD /modules/scsi/$i >/dev/null 2>&1 && FOUNDFIREWIRE="yes"
done
if test -n "$FOUNDFIREWIRE"; then
echo -n "${CRE}${BLUE}Loading sbp2.ko...${NORMAL}"
test -f /modules/scsi/sbp2.ko && $INSMOD /modules/scsi/sbp2.ko sbp2_serialize_io=1 >/dev/null 2>&1
else
# For an unknown reason, unloading ieee1394 hangs smetimes
# echo -n "${CRE}${BLUE}Unloading ieee1394...${NORMAL}"
# rmmod ieee1394 >/dev/null 2>&1
true
fi
fi
echo -n "${CRE}"
fi
# End of FIREWIRE check

# Unfortunately, hotpluggable devices tend to need some time in order to register
if test -n "$FOUNDUSB" -o -n "$FOUNDFIREWIRE"; then
echo -n "${CRE}${BLUE}Scanning for USB/Firewire devices... ${NORMAL}"
if test -n "$FOUNDFIREWIRE"; then
# Wait for driver to register
sleep 2
# Kernel 2.6 does this automatically
#case "$(cat /proc/version 2>/dev/null)" in *version\ 2.6.*) ;; *) for host in 0 1 2 3 4 5 6 7; do for channel in 0 1; do for id in 0 1 2 3 4 5 6 7; do echo "scsi add-single-device $host $channel $id 0" >/proc/scsi/scsi 2>/dev/null; done; done; done ;; esac
fi
#sleep 6
echo "${BLUE}Done.${NORMAL}"
fi

# Check for misc modules in expert mode
if test -n "$INTERACTIVE"; then
another=""; answer=""
while test "$answer" != "n" -a "$answer" != "N"; do
echo -n "${CYAN}Do you want to load additional modules from$another floppy disk? [${WHITE}Y${CYAN}/n] ${NORMAL}"
another=" another"
read answer
case "$answer" in n*|N*) break; ;; esac
if mountmodules new; then
askmodules new $(cd /modules/scsi; echo *.ko)
test -n "$MODULES" && loadmodules new $MODULES
umountmodules current
fi
done
fi
# All interactively requested modules should be loaded now.

# Check for ide-scsi supported CD-Roms et al.
test -f /proc/scsi/scsi && FOUND_SCSI="yes"

# Disable kernel messages again
if test -z "$BOOYO_DEBUG"; then
echo "0" > /proc/sys/kernel/printk
fi

# We now enable DMA right here, for faster reading/writing from/to IDE devices
# in FROMHD or TORAM mode
case "$CMDLINE" in *\ nodma*) ;; *)
for d in $(cd /proc/ide 2>/dev/null && echo hd[a-z]); do
if test -d /proc/ide/$d; then
MODEL="$(cat /proc/ide/$d/model 2>/dev/null)"
test -z "$MODEL" && MODEL="[GENERIC IDE DEVICE]"
echo "${BLUE}Enabling DMA acceleration for: ${MAGENTA}$d 	${YELLOW}[${MODEL}]${NORMAL}"
echo "using_dma:1" >/proc/ide/$d/settings
fi
done
;;
esac

# Now that the right SCSI driver is (hopefully) loaded, try to find CDROM
DEVICES="/dev/hd?"
test -n "$FOUND_SCSI" -a -z "$NOCD" && DEVICES="/dev/scd? /dev/scd?? $DEVICES"
# New: Also try parallel port CD-Roms [for Mike].
DEVICES="$DEVICES /dev/pcd?"
# New: also check HD partitions for a BOOYO/BOOYO image
test -n "$FOUND_SCSI" -a -z "$NOSCSI" && DEVICES="$DEVICES /dev/sd?[1-9] /dev/sd?[1-9][0-9]"
# BOOYO kernel config doesn't support Low Performance USB Block driver
#DEVICES="$DEVICES /dev/ub?[1-9] /dev/ub?[1-9][0-9] /dev/hd?[1-9] /dev/hd?[1-9][0-9]"
DEVICES="$DEVICES /dev/hd?[1-9] /dev/hd?[1-9][0-9]"
case "$CMDLINE" in *fromhd=/dev/*) DEVICES="$fromhd"; ;; esac
for i in $DEVICES
do
if test -z "$BOOYO_DEBUG"; then
echo -n "${CRE}${BLUE}Looking for CDROM in: ${MAGENTA}$i${NORMAL}   "
else
echo "${CRE}${BLUE}Looking for CDROM in: ${MAGENTA}$i${NORMAL}   "
fi
if mountit $i /cdrom "-o ro" >/dev/null 2>&1
then
if test -f /cdrom/$BOOYO_DIR/$BOOYO_NAME
then
if test -z "$BOOYO_DEBUG"; then
echo -n "${CRE} ${GREEN}Accessing BOOYO CDROM at ${MAGENTA}$i${GREEN}...${NORMAL}"
else
echo "${CRE} ${GREEN}Accessing BOOYO CDROM at ${MAGENTA}$i${GREEN}...${NORMAL}"
fi
FOUND_BOOYO="$i"
break
fi
umount /cdrom
fi
done

# Harddisk-installed script part version has been removed
# (BOOYO can be booted directly from HD now).

mount_booyo()
{
  if test -n "$FOUND_BOOYO" -a -f $1/$BOOYO_DIR/$BOOYO_NAME; then
    # DEBUG
    # echo "6" > /proc/sys/kernel/printk
    $INSMOD -f /modules/cloop.ko file=$1/$BOOYO_DIR/$BOOYO_NAME
    mountit /dev/cloop0 /BOOYO "-o ro" || FOUND_BOOYO=""
  fi
}

remount_booyo()
{
  if test -f $TARGET/$BOOYO_DIR/$BOOYO_NAME; then
    umount /BOOYO # unmount it
    echo "rmmod cloop" | /static/ash # release CD - ash crashes with parts of libc in memory -- FF
    umount $SOURCE  # unmount CD
    [ -n "$SOURCE2" ] && umount $SOURCE2  # umount possible loop-device
    mount_booyo $TARGET
  else
    echo "${CRE} ${RED}Warning: Changing to $TARGET failed.${NORMAL}"
    return 1
  fi
  
  return 0
}

boot_from()
{
  # preparations
  /bin/mkdir $TARGET

  SOURCE_DEV=$(echo $CMDLINE | /usr/bin/tr ' ' '\n' | /bin/sed -n '/bootfrom=/s/.*=//p' | /usr/bin/tail -1)
  
  LOOP_DEV=$(echo $SOURCE_DEV | /usr/bin/gawk -F/ '{ print $1 "/" $2 "/" $3 }')
  ISO_PATH=$(echo $SOURCE_DEV | /bin/sed "s|$LOOP_DEV||g" )
  case "$ISO_PATH" in /*.[iI][sS][oO]) ;; *) ISO_PATH="" ;; esac
  LOOP_SOURCE=""
  
  # load filesystems
  /BOOYO/sbin/modprobe ext3
  /BOOYO/sbin/modprobe vfat
  /BOOYO/sbin/modprobe reiserfs
  /BOOYO/sbin/modprobe ntfs    # BE CAREFUL! - Only mount it read only! - FF
 
  if [ -n "$ISO_PATH" ]
  then
     LOOP_SOURCE="$TARGET.loop"
     LOOP_SOURCE2="$LOOP_SOURCE"
     TARGET_DEV="$LOOP_SOURCE$ISO_PATH"
     /bin/mkdir $LOOP_SOURCE
     /BOOYO/sbin/modprobe loop

     /bin/mount -o ro $LOOP_DEV $LOOP_SOURCE || LOOP_SOURCE=""
     /bin/mount -n -o loop $LOOP_SOURCE2$ISO_PATH $TARGET
  else
     TARGET_DEV="$SOURCE_DEV"
    /bin/mount -n -o ro $SOURCE_DEV $TARGET
  fi
  if [ $? -ne 0 ]
  then
     [ -n "$LOOP_SOURCE" ] && /bin/umount $LOOP_SOURCE
     echo -n "${CRE} ${RED}Accessing BOOYO CDROM failed. ${MAGENTA}$TARGET_DEV${RED} is not mountable.${NORMAL}"
     sleep 2
     return 1
  fi
  
  if [ -f $TARGET/$BOOYO_DIR/$BOOYO_NAME ]
  then
    echo -n "${CRE} ${GREEN}Accessing BOOYO CDROM at ${MAGENTA}$TARGET_DEV${GREEN}...${NORMAL}"
  else
    echo -n "${CRE} ${RED}Accessing BOOYO CDROM failed. Could not find $BOOYO_DIR/$BOOYO_NAME on ${MAGENTA}$TARGET_DEV${RED}.${NORMAL}"
    [ -n "$LOOP_SOURCE" ] && /bin/umount $LOOP_SOURCE
    umount $TARGET
    sleep 2
    return 1
  fi
  # remount the CD 
  remount_booyo
}

copy_to()
{
  # preparations
  /bin/mkdir $TARGET
  COPY="$SOURCE/$BOOYO_DIR"

  # look if we copy to hd or to ram
  SIZE="$(/usr/bin/du -s $COPY | /usr/bin/gawk '{print int($1*1.1)}')"
  test -n "$SIZE" || SIZE="800000"
  
  case "$1" in 
    ram)
      TARGET_DEV="/dev/shm"
      TARGET_DEV_DESC="ramdisk"
      FOUNDSPACE="$(/usr/bin/gawk '/MemTotal/{print $2}' /proc/meminfo)"
      /bin/mount -n -t tmpfs -o size=${SIZE}k $TARGET_DEV $TARGET
    ;;
    hd)
      TARGET_DEV=$(echo $CMDLINE | /usr/bin/tr ' ' '\n' | /bin/sed -n '/tohd=/s/.*=//p' | /usr/bin/tail -1)
      TARGET_DEV_DESC="$TARGET_DEV"
      # load filesystems
      /BOOYO/sbin/modprobe vfat
      /BOOYO/sbin/modprobe reiserfs
      /BOOYO/sbin/modprobe jbd
      /BOOYO/sbin/modprobe ext3
      BUILTIN_FS="iso9660 ext3 ext2 reiserfs vfat"
      # we need to use mountit to prevent NTFS to be mounted!
      if mountit $TARGET_DEV $TARGET "-o rw"
      then
        :
      else
        echo -n "${CRE} ${RED}Copying BOOYO CDROM failed. ${MAGENTA}$TARGET_DEV_DESC${RED} is not mountable.${NORMAL}"
	sleep 2
        return 1
      fi
      # check for enough free space
      USED_SPACE=0
      [ -f $TARGET/$BOOYO_DIR/$BOOYO_NAME ] && USED_SPACE=$(/usr/bin/du -s $TARGET/$BOOYO_DIR/$BOOYO_NAME | /usr/bin/gawk '{ print $1 }')
      FOUNDSPACE="$(/bin/df -k $TARGET | /usr/bin/tail -1 | /usr/bin/gawk '{ print $4+int('$USED_SPACE') }')"
   ;;
   *)
     return 1
   ;;
  esac
 
  # sanity check

  if [ $FOUNDSPACE -lt $SIZE ]
  then
    echo -n "${CRE} ${RED}Copying BOOYO CDROM failed. Not enough free space on ${MAGENTA}${TARGET_DEV_DESC}${RED}. Found: ${MAGENTA}${FOUNDSPACE}k${RED} Need: ${MAGENTA}${SIZE}k${RED} ${NORMAL}"
    sleep 2
    umount $TARGET
    return 1
  fi
 
  # do the real copy
  
  echo "${CRE} ${GREEN}Copying BOOYO CDROM to ${MAGENTA}$TARGET_DEV_DESC${GREEN}... Please be patient. ${NORMAL}"
  if [ -z "$use_cp" -a -x /usr/bin/rsync ]
  then 
    # first cp the small files
    /usr/bin/rsync -a --exclude="$BOOYO_DIR/$BOOYO_NAME" $COPY $TARGET # Copy Booyo to $TARGET
    # then the big file with nice progress meter
    [ -f $TARGET/$BOOYO_DIR/$BOOYO_NAME ] && /bin/rm -f $TARGET/$BOOYO_DIR/$BOOYO_NAME
    /usr/bin/rsync -a --progress --include="$BOOYO_DIR/$BOOYO_NAME" --include="$BOOYO_DIR/" --exclude="*" $COPY $TARGET # Copy Booyo to $TARGET
    #/usr/bin/rsync -avP $COPY $TARGET # Copy Booyo to $TARGET
  else
    /bin/cp -a -f $COPY $TARGET # Copy Booyo to $TARGET
  fi
  if [ $? -ne 0 ]
  then
    echo -n "${CRE} ${RED}Copying BOOYO CDROM failed. ${MAGENTA}$TARGET_DEV_DESC${RED} possibly has not enough space left.${NORMAL}"
    sleep 2
    return 1
  fi
  # remount r/o
  /bin/mount -n -o remount,ro $TARGET_DEV $TARGET
  remount_booyo
}

mount_booyo /cdrom

cat > /etc/fstab << EOM
/dev/root       /               ext2    defaults                        0 0
${FOUND_BOOYO}  /cdrom        iso9660 ro                              0 0
/dev/cloop0     /BOOYO       iso9660    ro                              0 0
none            /sys            sysfs   defaults                        0 0
none            /proc           proc    defaults                        0 0
none            /dev/pts        devpts  defaults                        0 0
EOM


COPYTO=""
BOOTFROM=""
DO_REMOUNT=""
REAL_TARGET=""

case "$CMDLINE" in *toram*) DO_REMOUNT="yes"; COPYTO="ram"; ;; esac
case "$CMDLINE" in *tohd=*) DO_REMOUNT="yes"; COPYTO="hd"; ;; esac
case "$CMDLINE" in *bootfrom=*) DO_REMOUNT="yes"; BOOTFROM="yes" ;; esac
 
# Remount later after copying/isoloading/driverloading?
# pre-test if everything succeeded
if  test -n "$DO_REMOUNT" -a -n "$FOUND_BOOYO"
then
  # copy library cache 
  cat /BOOYO/etc/ld.so.cache > /etc/ld.so.cache 
  echo "" 

  SOURCE="/cdrom"
  TARGET="/cdrom2"
 
  # first test for possible hdboot/fromiso (which can be combined with toram / tohd)
  if [ -n "$BOOTFROM" ]
  then
    boot_from
    if [ $? -eq 0 ]
    then
      # set new source / target paths
      REAL_TARGET="$TARGET"
      SOURCE2="$LOOP_SOURCE"
      SOURCE="/cdrom2"
      TARGET="/cdrom3"
    fi
  fi
  if [ -n "$COPYTO" ]
  then
    copy_to $COPYTO && REAL_TARGET="$TARGET"
  fi
fi
 
# Final test if everything succeeded.
if test -n "$FOUND_BOOYO"
then
# copy library cache
cat /BOOYO/etc/ld.so.cache > /etc/ld.so.cache
echo ""

# Enable kernel messages
echo "6" > /proc/sys/kernel/printk

# Set paths
echo -n "${CRE}${BLUE}Setting paths...${NORMAL}"
PATH="/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:."
export PATH

# Debian weirdness
#/BOOYO/bin/cp -a /BOOYO/etc/alternatives /etc/ 2>/dev/null

# Replace /sbin
/BOOYO/bin/rm -f /sbin
/BOOYO/bin/ln -sf /BOOYO/sbin /sbin

# From here, we should have all essential commands available.
hash -r

# Did we remount the source media ? 
if  test -n "$REAL_TARGET"; 
then
   /bin/mount -n --move $REAL_TARGET /cdrom # move it back and go on to normal boot 
fi

# Clean up /etc/mtab (and - just in case - make a nice entry for looped ISO)
egrep " /BOOYO | /cdrom " /proc/mounts | sed 's|/dev/loop0 /cdrom \(.*\) 0 0|'$LOOP_SOURCE$ISO_PATH' /cdrom/ \1,loop=/dev/loop0 0 0|g' >> /etc/mtab

# Clean up /
rm -rf /modules /static

# New in Kernel 2.4.x: tmpfs with variable ramdisk size.
# We check for available memory anyways and limit the ramdisks
# to a reasonable size.
FOUNDMEM="$(awk '/MemTotal/{print $2}' /proc/meminfo)"
TOTALMEM="$(awk 'BEGIN{m=0};/MemFree|Cached/{m+=$2};END{print m}' /proc/meminfo)"
 
# Be verbose
echo "${CRE}${BLUE}Total memory found: ${YELLOW}${FOUNDMEM}${BLUE} kB${NORMAL}"

# Now we need to use a little intuition for finding a ramdisk size
# that keeps us from running out of space, but still doesn't crash the
# machine due to lack of Ram

# Minimum size of additional ram partitions
MINSIZE=2000
# At least this much memory minus 30% should remain when home and var are full.
MINLEFT=16000
# Maximum ramdisk size
MAXSIZE="$(expr $TOTALMEM - $MINLEFT)"
# Default ramdisk size for ramdisk
RAMSIZE="$(expr $TOTALMEM / 5)"

# Check for sufficient memory to mount extra ramdisk for /home + /var
if test -n "$TOTALMEM" -a "$TOTALMEM" -gt "$MINLEFT"; then
test -z "$RAMSIZE" && RAMSIZE=1000000
mkdir -p /ramdisk
# tmpfs/varsize version, can use swap
RAMSIZE=$(expr $RAMSIZE \* 4)
echo -n "${CRE}${BLUE}Creating ${YELLOW}/ramdisk${BLUE} (dynamic size=${RAMSIZE}k) on ${MAGENTA}shared memory${BLUE}...${NORMAL}"
# We need /bin/mount here for the -o size= option
/bin/mount -t tmpfs -o "size=${RAMSIZE}k" /ramdisk /ramdisk && mkdir -p /ramdisk/home /ramdisk/var
mv /etc /ramdisk
ln -s /ramdisk/home /ramdisk/var /ramdisk/var/tmp /ramdisk/etc /
mkdir -p /home/root
rm -Rf /root
ln -sf /ramdisk/home/root /root
echo "${BLUE}Done.${NORMAL}"
else
mkdir -p /home /var
fi

echo -n "${CRE}${BLUE}Creating directories and symlinks on ramdisk...${NORMAL}"
# Create common WRITABLE (empty) dirs
# /var/backups /var/cache/apache /var/lock/news /var/state/misc 
# /var/lib/samba /var/lib/nessus /mnt/cdrom /etc/dhcpc
# does not exist in BOOYO
mkdir -p /var/run /var/lock \
         /var/nis /var/preserve /var/tmp /var/lib \
         /var/spool/cups/tmp \
         /mnt /media \
         /etc/sysconfig /etc/X11 /etc/cups
cp -a /BOOYO/root/* /root/
rm -Rf /root/.[A-z]*
cp -a /BOOYO/etc/skel/.[a-z]* /root/
cp -a /BOOYO/home/booyo /home/booyo
chown -R booyo.booyo /home/booyo
# Create empty utmp and wtmp
:> /var/run/utmp
:> /var/run/wtmp
# mDNSResponder needs network
cp -a /BOOYO/etc/sysconfig/network /etc/sysconfig/ 2>/dev/null
# CUPS wants writable files. :-/
cp -a /BOOYO/etc/cups/*.conf /etc/cups/ 2>/dev/null
cp -a /BOOYO/etc/alternatives /etc/ 2>/dev/null
cp -a /BOOYO/etc/alternatives/print /etc/alternatives/ 2>/dev/null
# resolv.conf must be writable as well
cp -a /BOOYO/etc/resolv.conf /etc/ 2>/dev/null
# sendmail needs /etc/mail/local-host-names, trusted-users
cp -aus /BOOYO/etc/mail/* /etc/ 2>/dev/null
cp -a /BOOYO/etc/mail/local-host-names /etc/mail/ 2>/dev/null
cp -a /BOOYO/etc/mail/trusted-users /etc/mail/ 2>/dev/null
# All files in here should be size zero after Booyo.clean was run
# /var/games does not exist
cp -a /BOOYO/var/local /BOOYO/var/log \
      /BOOYO/var/spool /var/ 2>/dev/null
# /var/lib/wine /var/lib/isdn /var/lib/kdm removed, /var/lib/random-seed added
cp -a /BOOYO/var/lib/games \
      /BOOYO/var/lib/nfs /BOOYO/var/lib/xkb \
      /BOOYO/var/lib/pcmcia \
      /BOOYO/var/lib/dhcp* \
      /BOOYO/var/lib/random-seed \
      /BOOYO/var/lib/dhcp* \
      /var/lib/ 2>/dev/null
# Link device files (real device file copies should NOT require more space, but in fact, they do)
# BOOYO use udev
#cp -aus /dev/capi /dev/ 2>/dev/null
#ln -s /BOOYO/dev/* /dev/ 2>/dev/null
# Problematic directories in /var/lib (lots and lots of inodes)
# /var/lib/dpkg /var/lib/apt /var/lib/doc-base /var/lib/gnome 
# /var/lib/kde /var/lib/texmf removed
echo -n "/sbin/hotplug" > /proc/sys/kernel/hotplug
/sbin/udevstart

ln -s /BOOYO/var/lib/scrollkeeper \
      /var/lib/ 2>/dev/null
# Debian-apt
#ln -s /BOOYO/var/cache/apt /var/cache/ 2>/dev/null
#rm -f /etc/resolv.conf 2>/dev/null
#ln -s /BOOYO/etc/skel /BOOYO/etc/nessus /etc/dhcpc/resolv.conf \
ln -s /BOOYO/etc/skel /etc/ 2>/dev/null
# Index files can be HUGE, so better replace cache/man tree by links later
# cp -a /BOOYO/var/cache/man /var/cache/ 2>/dev/null
# Nessus >1000 plugins
#ln -s /BOOYO/var/lib/nessus/plugins /var/lib/nessus/
# Create links from CDROM for UNWRITABLE (remaining) files
cp -aus /BOOYO/var/* /var/ 2>/dev/null
cp -aus /BOOYO/etc/* /etc/ 2>/dev/null
# Make SURE that these are files, not links!
# /etc/ftpusers /etc/isdn /etc/ioctl.save /etc/inittab /etc/network 
# /etc/sudoers /etc/init /etc/localtime /etc/dhcpc 
# /etc/pnm2ppa.conf removed /etc/gshadow added
#rm -rf /etc/X11/xorg.conf /etc/sysconfig/*
rm -rf /var/run/sudo
cp -a /BOOYO/var/run/sudo /var/run/
rm -rf /etc/passwd /etc/shadow /etc/group /etc/gshadow \
       /etc/passwd- /etc/shadow- /etc/group- /etc/gshadow- \
       /etc/hosts /etc/wvdial.conf \
       /etc/pnm2ppa.conf \
       /etc/ppp /etc/ssh 2>/dev/null
rm -rf /etc/X11/xorg.conf /etc/sysconfig/*
rm -rf /etc/init
rm -rf /etc/rc?.d
ln -s /etc/rc.d/rc?.d /etc/
cp -a /BOOYO/etc/passwd /BOOYO/etc/shadow /BOOYO/etc/group \
      /BOOYO/etc/gshadow /BOOYO/etc/ppp /BOOYO/etc/ssh \
      /BOOYO/etc/hosts /BOOYO/etc/wvdial.conf \
      /BOOYO/etc/sysconfig/ /BOOYO/sbin/init /etc/ 2>/dev/null
echo "${BLUE}Done.${NORMAL}"
# Extremely important, init crashes on shutdown if this is only a link
:> /etc/ioctl.save
:> /etc/pnm2ppa.conf
# Must exist for samba to work
#[ -d /var/lib/samba ] && :> /var/lib/samba/unexpected.tdb
# Kernel 2.6.9 bug?
chmod 1777 /var/tmp
# Diet libc bug workaround
#/bin/cp -f /BOOYO/etc/localtime /etc/localtime
# < modify symbolic link >
rm -rf /etc/sysconfig/network-scripts/ifup /etc/sysconfig/network-scripts/ifdown
cp -aus /sbin/ifup /sbin/ifdown /etc/sysconfig/network-scripts

# Now tell kernel where the real modprobe lives
echo "/sbin/modprobe" > /proc/sys/kernel/modprobe

# Change root device from /dev/fd0 to /dev/ram0
echo "0x100" > /proc/sys/kernel/real-root-dev
umount /proc
# Give control to the init process.
echo "${CRE}${BLUE}Starting init process.${NORMAL}"
rm -f /linuxrc
exec /etc/init "$@" < /dev/console > /dev/console 2>&1
exit 0

else
echo "${CRE}${RED}Can't find BOOYO filesystem, sorry.${NORMAL}"
echo "${RED}Dropping you to a (very limited) shell.${NORMAL}"
echo "${RED}Press reset button to quit.${NORMAL}"
echo ""
echo "Additional builtin commands avaliable:"
echo "	cat        mount     umount"
echo "	insmod     rmmod     lsmod"
echo ""
PS1="booyo# "
export PS1
echo "6" > /proc/sys/kernel/printk
# Allow signals
trap 1 2 3 15
exec /static/ash
fi
