#!/bin/bash -x
#
# $Id: linuxrc,v 1.13 2002/11/07 09:03:03 root Exp $
#
# Find the CD-ROM and copy the root to ramdisk
#

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/
export PATH

ldconfig

umask 022
mkdir -p /ram /proc

mount -t proc none /proc

use_nfs=false

for arg in `cat /proc/cmdline`; do
    case "$arg" in
	initsh)
	    bash -i
	    ;;
	NFSDIR=*)
	    use_nfs=true
	    nfsdir=`echo "$arg" | cut -d= -f2-`
	    ;;
	*)
	    ;;
    esac
done

if ! $use_nfs; then
    # Try to detect a CD-ROM.  Since USB devices are detected
    # asynchronously, try a few times before giving up...
    found=false
    for z in 1 2 4 8 ; do
	if find-cd; then
	    found=true
	    break
	fi
	sleep $z
    done
    if ! $found; then
	if ! find-cd; then
	    echo "Unable to find CD-ROM and NFSDIR not specified" 1>&2
	    bash -i
        fi
    fi
fi

# 64M should be plenty big... we shouldn't be using
# even close to that much.  Make sure we get enough
# inodes, however...
mount -t tmpfs -o size=64M,nr_inodes=64K none /ram

cd /ram
mkdir -p usr proc initrd dev
if $use_nfs; then
    mount -r -t nfs -o nolock "$nfsdir" usr
else
    cp -pR /dev/cdrom dev
    mount -r -t iso9660 dev/cdrom usr
fi
tar xfpz usr/root.tar.gz 2>/dev/null

cd /
cat > /ram/etc/mtab <<EOF
none / tmpfs rw 0 0
/dev/ram0 /initrd ext2 rw 0 0
EOF
if $use_nfs; then
    echo "$nfsdir /usr nfs ro,nolock 0 0" >> /ram/etc/mtab    
else
    echo `readlink /dev/cdrom` /usr iso9660 ro 0 0 >> /ram/etc/mtab    
fi

umount /proc

# Switch roots and run init
cd /ram
pivot_root . initrd
exec sbin/init "$@" <>dev/console 2>&1
