#!/bin/sh

# (c) 2009-2022 SHIMADA Hirofumi
# based :
#  30-bootmenu.sh (c) 2007 Paul Sokolovsky
#  initramfs-framework Copyright (C) 2011 O.S. Systems Software LTDA.
# Licensed on MIT

# pivot-root : 

CFGLOC="/.cfg"
COPYTORAMLOC="/.cfg/copytoram"
FIRMWARELOC="/.cfg/firmware"
ISOLOC="/.iso"
MOUNTLOC="/rootfs"
NEWLOC="/.newroot"
OLDLOC="/.oldroot"
SCANLOC="/.cfg/scan"
UNIONLOC="/.cfg/union"
OVERLAY_UPPERLOC="/.cfg/overlay_upper"
OVERLAY_WORKLOC="/.cfg/overlay_work"
PARAM_FILE="$CFGLOC/.bootparam"
MAIN_READY_FILE="$CFGLOC/.main_image_ready"

pivotroot_enabled() {
	return 0
}

pivotroot_run() {
	if test -e "$PARAM_FILE";
	then
		. $PARAM_FILE
	fi

	# Cehck if mountsqs script was mount main image successfly.
	if test ! -e "$MAIN_READY_FILE";
	then
		echo "pivot-root : Main squashfs image is not ready."

		echo "DEBUG SHELL"
		/bin/sh
		
	fi

	# write parameter
	if test -n "$bootparam_noeject";
	then
		echo "bootparam_noeject=$bootparam_noeject" >> $PARAM_FILE
	fi

	# bind /dev directory on new root
	mount -o bind /dev $NEWLOC/dev

	# copy bootparam and some setting file
	cp $PARAM_FILE $NEWLOC/
	cp $CFGLOC/cocon.cnf.* $NEWLOC/

	# Pivot to Main Distribution
	echo "Pivot root : from $OLDLOC to $NEWLOC"
	
	mkdir -p "$NEWLOC/$OLDLOC"
	pivot_root $NEWLOC $NEWLOC/$OLDLOC

	exec chroot . /sbin/init <dev/console >dev/console 2>&1
}
