# !/bin/sh
#
# Copyright Matthias Hentges (c) 2005
#
# License: GPL (see http://www.gnu.org/licenses/gpl.txt for a copy of the GPL)


# This file will teach you how to implement your own scripts while using existing altboot
# code.

# /sbin/init.altboot searches /etc/altboot-menu for scripts. It will only list scripts which
# return a title when run with the "title" parameter. 
# Script which do not return a title will never be shown in the boot menu!
# 
M_TITLE="Boot from images on HDD3"

# The "title" parameter is implemented at the end of this script so it will never be reached
# and the script will simply be ignored by altboot.


# The die() function aborts the boot if something goes wrong and sets STDIN / STDERR / STDOUT
# correctly.
die() {
	echo "ERROR: $1" >/dev/tty0
	exec $SH_SHELL </dev/tty0 >/dev/tty0 2>&1
}

# This function is activated by init.altboot by calling this script with the "run" option
run_module() {

	# altboot.func contains re-useable code. If you intend to use check_target (see below)
	# you must keep this line. If not, delete it.
	test -e /etc/altboot.func && . /etc/altboot.func || die "ERROR: /etc/altboot.func not found. Check your installation!"	


	# The only thing you'll have to do is get your medium mounted.
	# The following lines mount a SD card on 2.4-series kernels on a Zaurus
	
	##########################################
	
	
	echo -n "Mounting rootfs rw..." >/dev/tty0
	mount -o remount,rw / >/dev/tty0 2>&1 && echo ok  >/dev/tty0|| die "mount -o remount,rw / failed"

	#echo -n "Generating device files..." >/dev/tty0
	#/etc/init.d/devices start && echo ok  >/dev/tty0|| die "FAILED"

	cardmgr -o < /dev/tty0 > /dev/tty0 2>&1 || echo "cardmgr -o failed!"

	check_fs $HDD3_DEVICE $HDD3_TYPE

	echo -n "Mounting $HDD3_MOUNTPOINT..."  >/dev/tty0
	if [ "$HDD3_TYPE" = "" ]; then
		HDD3_TYPE="auto"
	fi
	/bin/mount -t $HDD3_TYPE -o defaults,noatime $HDD3_DEVICE $HDD3_MOUNTPOINT >/dev/null 2>&1 && echo ok  >/dev/tty0|| die "/bin/mount -t auto -o defaults,noatime $HDD3_DEVICE $HDD3_MOUNTPOINT failed"
		
	echo ""

	# Give the SD and CF mounting some time. This is a must for SD			
	sleep 2
	##########################################	
	
	# Once the medium (be it a CF or SD card, or even a NFS drive) is mounted somewhere,
	# just call check_target with the mountpoint as parameter.
	# check_target searches the medium for a real filesystem and loop-images and
	# asks the user what to boot if there are several choices.
	
	# Check for a real fs and loop-images.
	check_target "$HDD3_MOUNTPOINT" >/dev/tty0
	
	# Done :)
		
}


case "$1" in
title)	echo "$M_TITLE";;
run)	run_module "$2";;
esac
