# Local filesystem mounting			-*- shell-script -*-

pre_mountroot()
{
	[ "$quiet" != "y" ] && log_begin_msg "Running /scripts/local-top"
	run_scripts /scripts/local-top
	[ "$quiet" != "y" ] && log_end_msg
	
	# Don't wait for a root device that doesn't have a corresponding
	# device in /dev (ie, mtd0)
	if [ "${ROOT#/dev}" = "${ROOT}" ]; then
		return
	fi

	while [ -z "${FSTYPE}" ]; do
		FSTYPE=$(wait-for-root "${ROOT}" ${ROOTDELAY:-30})

		# Load ubi with the correct MTD partition and return since
		# fstype doesn't work with a char device like ubi.
		if [ -n "$UBIMTD" ]; then
			modprobe ubi mtd=$UBIMTD
			return
		fi

		# Run failure hooks, hoping one of them can fix up the system
		# and we can restart the wait loop.  If they all fail, abort
		# and move on to the panic handler and shell.
		if [ -z "${FSTYPE}" ] && ! try_failure_hooks; then
			break
		fi
	done

	# We've given up, but we'll let the user fix matters if they can
	while [ -z "${FSTYPE}" -a ! -e "${ROOT}" ]; do
		# give hint about renamed root
		case "${ROOT}" in
		/dev/hd*)
			suffix="${ROOT#/dev/hd}"
			major="${suffix%[[:digit:]]}"
			major="${major%[[:digit:]]}"
			if [ -d "/sys/block/sd${major}" ]; then
				echo "WARNING bootdevice may be renamed. Try root=/dev/sd${suffix}"
			fi
			;;
		/dev/sd*)
			suffix="${ROOT#/dev/sd}"
			major="${suffix%[[:digit:]]}"
			major="${major%[[:digit:]]}"
			if [ -d "/sys/block/hd${major}" ]; then
				echo "WARNING bootdevice may be renamed. Try root=/dev/hd${suffix}"
			fi
			;;
		esac
		echo "Gave up waiting for root device.  Common problems:"
		echo " - Boot args (cat /proc/cmdline)"
		echo "   - Check rootdelay= (did the system wait long enough?)"
		echo "   - Check root= (did the system wait for the right device?)"
		echo " - Missing modules (cat /proc/modules; ls /dev)"
		panic "ALERT!  ${ROOT} does not exist.  Dropping to a shell!"
	done
}

process_ubuntu()
{
	mrom_dir=$1

	if [ -e /tmpmnt/system.img ]; then
		# Prepare the root filesystem
		if [ -e /tmpmnt/.developer_mode ]; then
			echo "initrd: mounting system.img (developer mode)" >/dev/kmsg || true
			mount -o loop,rw /tmpmnt/system.img ${rootmnt}
			mountroot_status="$?"
		else
			echo "initrd: mounting system.img (user mode)" >/dev/kmsg || true
			mount -o loop,ro /tmpmnt/system.img ${rootmnt}
			mountroot_status="$?"
		fi
		mount --move /tmpmnt ${rootmnt}/data

		# Create any missing persistent directory
		for dir in system-data system-data/dbus \
			system-data/network-manager/connections \
			system-data/network-manager/lib \
			system-data/log system-data/log/upstart userdata android-data; do
			mkdir -p ${rootmnt}/data/$dir
		done

		# Move some data to persistant storage (first-boot)
		if [ ! -d ${rootmnt}/data/phablet ]; then
			cp -Ra ${rootmnt}/home/phablet ${rootmnt}/data/phablet
		fi

		# Mount all the Android partitions
		mkdir -p ${rootmnt}/android/cache
		mkdir -p ${rootmnt}/android/system
		mount -o bind $mrom_dir/cache ${rootmnt}/android/cache
		mount -o loop,ro ${rootmnt}/var/lib/lxc/android/system.img ${rootmnt}/android/system

		# Apply device-specific udev rules
		device=$(grep ^ro.product.device= ${rootmnt}/android/system/build.prop |sed -e 's/.*=//')
		if [ -n "$device" ]; then
			echo "initrd: identified device as $device" >/dev/kmsg || true
			mount --bind ${rootmnt}/usr/lib/lxc-android-config/70-$device.rules ${rootmnt}/lib/udev/rules.d/70-android.rules
		fi

		# Bind-mount /lib/modules from Android
		[ -e /system/lib/modules ] && mount --bind /system/lib/modules /lib/modules

		# Bind-mount the fstab
		mount --bind ${rootmnt}/usr/lib/lxc-android-config/image-fstab ${rootmnt}/etc/fstab
	elif [ -d /tmpmnt/ubuntu ]; then
		mount --bind /tmpmnt/ubuntu ${rootmnt}
		mountroot_status="$?"
		# Possibly a re-partitioned device
	else
		echo "initrd: Couldn't find a system partition." >/dev/kmsg || true
		panic "Couldn't find a system partition. Spawning adbd ..."
	fi
}

mountroot()
{
	pre_mountroot

	# Make sure the device has been created by udev before we try to mount
	udevadm settle

	# Get the root filesystem type if not set
	if [ -z "${ROOTFSTYPE}" ]; then
		[ -n "${FSTYPE}" ] || FSTYPE=$(blkid -s TYPE -o value "${ROOT}")
		ROOTFSTYPE="${FSTYPE}"
	else
		FSTYPE=${ROOTFSTYPE}
	fi
	
	[ "$quiet" != "y" ] && log_begin_msg "Running /scripts/local-premount"
	run_scripts /scripts/local-premount
	[ "$quiet" != "y" ] && log_end_msg

	if [ "${readonly}" = "y" ] && \
	   [ -z "$LOOP" ]; then
		roflag=-r
	else
		roflag=-w
	fi

	# FIXME This has no error checking
	[ -n "${FSTYPE}" ] && modprobe ${FSTYPE}

	# FIXME This has no error checking
	# Mount root
	mount ${roflag} ${FSTYPE:+-t ${FSTYPE} }${ROOTFLAGS} ${ROOT} ${rootmnt}
	mountroot_status="$?"
	if [ "$LOOP" ]; then
		if [ "$mountroot_status" != 0 ]; then
			if [ ${FSTYPE} = ntfs ] || [ ${FSTYPE} = vfat ]; then
				panic "
Could not mount the partition ${ROOT}.
This could also happen if the file system is not clean because of an operating
system crash, an interrupted boot process, an improper shutdown, or unplugging
of a removable device without first unmounting or ejecting it.  To fix this,
simply reboot into Windows, let it fully start, log in, run 'chkdsk /r', then
gracefully shut down and reboot back into Windows. After this you should be
able to reboot again and resume the installation.
(filesystem = ${FSTYPE}, error code = $mountroot_status)
"
			fi
		fi
	
		mkdir -p /host
		mount -o move ${rootmnt} /host

		if [ ! -d "/host/${LOOP}" ]; then
		    panic "LOOP folder does not exit on the device, ${LOOP}"
		fi

		# Get the loop filesystem type if not set
		if [ -z "${LOOPFSTYPE}" ]; then
			panic "LOOPFSTYPE was not set!"
		else
			FSTYPE="${LOOPFSTYPE}"
		fi

		if [ "$FSTYPE" = "unknown" ]; then
			panic "LOOPFSTYPE was set to unknown!"
		fi

		if [ ${readonly} = y ]; then
			roflag=-r
		else
			roflag=-w
		fi

		# FIXME This has no error checking
		modprobe loop
		modprobe ${FSTYPE}

		mkdir -p /tmpmnt
		mount ${roflag} -o loop -t ${FSTYPE} ${LOOPFLAGS} "/host/${LOOP}/data.img" /tmpmnt

		echo "initrd: mounted all loops" >/dev/kmsg || true

		process_ubuntu "/mrom_dir/"
		
		echo "process_ubuntu complete" >/dev/kmsg || true

		mkdir -p ${rootmnt}/host
		mount -o move /host ${rootmnt}/host

		mkdir -p ${rootmnt}/mrom_dir/data
		mkdir -p ${rootmnt}/mrom_dir/system
		mkdir -p ${rootmnt}/mrom_dir/cache
		mkdir -p ${rootmnt}/data
		mkdir -p ${rootmnt}/system
		
		mount ${roflag} -o loop -t ${FSTYPE} ${LOOPFLAGS} "${rootmnt}/host/${LOOP}/system.img" ${rootmnt}/mrom_dir/system
		mount ${roflag} -o loop -t ${FSTYPE} ${LOOPFLAGS} "${rootmnt}/host/${LOOP}/cache.img" ${rootmnt}/mrom_dir/cache
		mount ${roflag} -o loop -t ${FSTYPE} ${LOOPFLAGS} "${rootmnt}/host/${LOOP}/data.img" ${rootmnt}/mrom_dir/data
		mount -o bind ${rootmnt}/mrom_dir/system ${rootmnt}/system
		mount -o bind ${rootmnt}/mrom_dir/data ${rootmnt}/data
	elif [ "$ROOTSUBDIR" ]; then
		if [ "$mountroot_status" != 0 ]; then
			panic "
Could not mount the partition ${ROOT}.
This could also happen if the file system is not clean because of an operating
system crash, an interrupted boot process, an improper shutdown, or unplugging
of a removable device without first unmounting or ejecting it.
(filesystem = ${FSTYPE}, error code = $mountroot_status)
"
		fi

		mkdir -p /host
		mount -o move ${rootmnt} /host
		
		if [ ! -d "/host/$ROOTSUBDIR" ]; then
		    panic "Failed to bind folder ${ROOTSUBDIR} as root: folder does not exist."
		fi

		if [ ! -d "/host/$ROOTSUBDIR/data" ]; then
		    panic "Failed to bind folder ${ROOTSUBDIR}/data: folder does not exist."
		fi

		mkdir -p /tmpmnt
		mount -o bind "/host/$ROOTSUBDIR/data" /tmpmnt

		process_ubuntu "/host/$ROOTSUBDIR/"

		mkdir -p ${rootmnt}/host
		mount -o move /host ${rootmnt}/host

		mrom_dir="${rootmnt}/host/$ROOTSUBDIR"

		mkdir -p ${rootmnt}/system
		mkdir -p ${rootmnt}/data
		mkdir -p ${rootmnt}/mrom_dir
		mount -o bind ${mrom_dir}/system ${rootmnt}/system
		mount -o bind ${mrom_dir}/data ${rootmnt}/data
		mount -o bind ${mrom_dir} ${rootmnt}/mrom_dir
	fi

	[ "$quiet" != "y" ] && log_begin_msg "Running /scripts/local-bottom"
	run_scripts /scripts/local-bottom
	[ "$quiet" != "y" ] && log_end_msg
}
