#!/bin/sh

###############################################################################
# capture boot process for troubleshooting

exec 2>/run/initfs.trc
set -x


###############################################################################
# program variables

ROOTMNT='/mnt/rootfs'
INITBIN='/sbin/init'
ROOTDEV='LABEL=root'
MNTFLAG='ro'

GETARGS='get_arg_core'


###############################################################################
# set environment visible to /init

for f in /etc/env.d/*.sh
do
	if [ -r $f ]
	then
		. $f
	fi
done


###############################################################################
# global kernel command line functions

import_handler() {
	local func="$1"

	GETARGS="${GETARGS} $func"

}

import_cmdline() {
	local arg func

	for arg in $(cat /proc/cmdline)
	do
		for func in $GETARGS
		do
			$func $arg
		done
	done

	if [ -n "$ROOTFLG" ]
	then
		MNTOPTS="${MNTFLAG},${ROOTFLG}"
	else
		MNTOPTS=$MNTFLAG
	fi

}


###############################################################################
# core kernel argument handler

get_arg_core() {
	local arg="$1"

	case $arg in

		ro)
			MNTFLAG=ro
			;;
		rw)
			MNTFLAG=rw
			;;

		root=*)
			ROOTDEV=${arg#root=}
			;;

		rootflags=*)
			ROOTFLG=${arg#rootflags=}
			;;

		init=*)
			INITBIN=${arg#init=}
			;;

	esac
}


###############################################################################
# ensure the root device is accessible

# try it
mount_rootfs() {
	local fstype

	fstype=$(blkid $NEXTDEV | sed 's/.*TYPE=//;s/^"//;s/"$//')

	if [ -z "$fstype" ]
	then
		return 1
	fi

	mount -t $fstype -o $MNTOPTS $NEXTDEV $ROOTMNT

	return $?
}

# probe it
load_rootdev() {
	local f

	for f in /lib/initfs/load.d/*.sh
	do
		if [ -r $f ]
		then
			. $f
		fi
		is_rootfs_mounted && break
	done

}

# test for it
is_rootfs_mounted() {
	grep -q $ROOTMNT /etc/mtab
}

# highlevel: the whole sequence
mount_rootfs_effort() {

	if [ -z $NEXTDEV ]
	then
		NEXTDEV=$ROOTDEV
	fi

	mount_rootfs

	if ! is_rootfs_mounted
	then
		local f
		for f in /lib/initfs/load.d/*.sh
		do
			if [ -r $f ]
			then
				. $f
			fi
			is_rootfs_mounted && break
		done
	fi

	if ! is_rootfs_mounted
	then
		mount_rootfs
		return $?
	fi

	return 0
}


###############################################################################
# MAIN BLOCK

for f in /lib/initfs/init.d/*.sh
do
	if [ -r $f ]
	then
		. $f
	fi
done
unset f

import_cmdline

mount_rootfs_effort

for f in /lib/initfs/done.d/*.sh
do
	if [ -r $f ]
	then
		. $f
	fi
done
unset f

exec chroot $ROOTMNT $INITBIN

echo BUG: got to end of rootfs:/init
exit # panic - should never get here