#!/bin/sh
set -e

exec >/dev/log
exec 2>/dev/log
exec </dev/null

FSCK=/bin/fsck.mfs
ACPI=/sbin/acpi
if [ -e $ACPI -a -n "`sysenv acpi`" ]
then
	/bin/service -c up $ACPI
fi
/bin/service -c up /sbin/pci
/bin/service -cn up /sbin/floppy -dev /dev/fd0
if [ X`/bin/sysenv bios_wini` = Xyes ]
then
	echo Using bios_wini.
	/bin/service -c up /sbin/bios_wini -dev /dev/c0d0
elif [ X`/bin/sysenv ahci` = Xyes ]
then
	# this is here temporarily, for testing purposes
	/bin/service -c up /sbin/ahci -dev /dev/c0d0 -label ahci_0 -args instance=0
else
	/bin/service -c up /sbin/at_wini -dev /dev/c0d0 -label at_wini_0
	/bin/service -cr up /sbin/at_wini -dev /dev/c1d0 -label at_wini_1 -args instance=1
fi
/bin/service -c edit /sbin/mfs -label fs_imgrd
/bin/service up /sbin/procfs || echo "WARNING: couldn't start procfs"

if /bin/sysenv rootdevname >/dev/null
then
	rootdevname=/dev/`/bin/sysenv rootdevname`
else
	rootdev=`/bin/sysenv rootdev` || echo 'No rootdev?'
	rootdevname=`/bin/dev2name "$rootdev"` ||
		{ echo 'No device name for root device'; exit 1; }
fi

if [ "`sysenv bin_img`" = 1 ]
then
    bin_img="-i "
fi

if sysenv cdproberoot >/dev/null
then
	echo 
	echo 'Looking for boot CD. This may take a minute.'
	echo 'Please ignore any error messages.'
	echo
	cddev=`cdprobe` || { echo 'No CD found'; exit 1; }
	export cddev
	echo "Loading ramdisk from ${cddev}p1"
	loadramdisk "$cddev"p1
elif [ "$rootdevname" = "/dev/ram" ]
then
	if /bin/sysenv rootdevname >/dev/null
	then
		ramimagename=/dev/`/bin/sysenv ramimagename`
	else
		ramimagedev=`/bin/sysenv ramimagedev` ||
			{ echo 'ramimagedev not found'; exit 1; }
		ramimagename=`/bin/dev2name "$ramimagedev"` ||
			{ echo 'No device name for ramimagedev'; exit 1; }
	fi

	echo "Loading ramdisk from $ramimagename"
	loadramdisk "$ramimagename" || echo "WARNING: loadramdisk failed"
fi
echo "Root device name is $rootdevname"
if [ -e $FSCK ]
then	$FSCK -p $rootdevname
fi
/bin/newroot $bin_img"$rootdevname"
/bin/mount -e -n -t procfs none /proc || echo "WARNING: couldn't mount procfs"

exec /bin/sh /etc/rc "$@"
