#!/bin/ash

# Generic ARAM rootfs Loader V1

count_down() {
	c=$1
	message=$2
	while [ $c -gt 0 ]; do
		echo -n "$message [$c] "
		button=`jssleep 1`
		if [ $button -ne 0 ]; then
			echo ""
			return $button
		else
			echo -ne '\r'
		fi
		c=$((c-1))
	done
	echo "$message    "
	return 0
}

try_to_mount_sdcard() {
	sdcard=$1
	size=`cat /sys/block/${sdcard}/${sdcard}1/size 2> /dev/null`
	[ -n "$size" ] && {
		echo -ne "\rTrying SD/MMC $sdcard ...\n  "
		mount -n -o ro -t vfat /dev/${sdcard}1 /sdcard && {
			return 0
		}
		echo "... skipped."
	}
	return 1
}

umount_sdcard() {
	umount /sdcard 2>/dev/null
}

try_to_mount_disc() {
	echo -ne "\rTrying DVD ...\n  "
	mount -n -o ro -t iso9660 /dev/dvd /disc && {
		return 0
	}
	echo "... skipped."
	return 1
}

umount_disc() {
	umount /disc 2>/dev/null
}

uncompress_root_filesystem() {
	fs_z=$1

	echo -n "Uncompressing root filesystem ... "
	bunzip2 -c $fs_z > /dev/aram
	echo "done."
}

switch_to_new_root() {
	migrate_disc=$1
  
	/bin/mount -w -o loop=/dev/loop3  /sdcard/mamefs-fs /new-root && {
		cd /new-root
    mount -o bind /sdcard /new-root/sdcard
		#
		if [ $migrate_disc -eq 1 ]; then
			mkdir ./disc 2> /dev/null
			mount -o bind /disc ./disc
			umount /disc 2> /dev/null
		fi

		#
		mkdir old-root 2> /dev/null
		pivot_root . old-root && \
		exec /bin/chroot . /sbin/init <dev/console >dev/console 2>&1

		# should not get here
		if [ $migrate_disc -eq 1 ]; then
			umount ./disc
		fi
		cd ..
		umount /new-root
	}
	return 1
}


mount -n -t proc proc /proc 2>/dev/null
mount -n -t sysfs sysfs /sys 2>/dev/null
swapoff /dev/aram 2>/dev/null

ARAMFS=mamefs-fs

while [ 0 -eq 0 ]; do
	echo ""
	echo ""
	echo ""

	echo "Generic ARAM rootfs Loader V1"
	echo "www.gc-linux.org"
	echo ""
	echo "rootfs image: $ARAMFS"
	echo ""

	#
	found=0

	# SD/MMC
	umount_sdcard
	sdcards="rvlsda gcnsda gcnsdb"
	for sdcard in $sdcards; do
		 {
      mount -n -o rw -t vfat /dev/${sdcard}1 /sdcard 
			fs=/sdcard/mamefs-fs
			if [ -r $fs ]; then
				found=1				
				switch_to_new_root 0
			else
				umount_sdcard
			fi
		}
	done

	# optical disc
	umount_disc
	try_to_mount_disc && {
		fs=/disc/$ARAMFS
		if [ -r $fs ]; then
			found=1
			uncompress_root_filesystem $fs
			switch_to_new_root 1
		fi
		umount_disc
	}

	echo ""
	if [ $found -eq 0 ]; then
		echo "Sorry, I'm unable to locate $ARAMFS."
	else
		echo "Sorry, I need a working root filesystem image."
	fi
#	count_down 30 "Press any button to try it again"
  echo Retry in 10 seconds
  sleep 10

	clear
done

umount /sys 2>/dev/null
umount /proc 2>/dev/null

