#!/bin/bash


export PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/sbin;/usr/local/bin:";
export PS4="[\D{%T}] +";
BACK_UP="\033[1K\033[0G";
HILITE="\033[1m";
NORMAL="\033[0m";
WARN="\033[1m";
NOTE="\033[01;33m";
ERR="\033[31m";
BAD="\033[1m";
INIT="/sbin/init";
NOROOTCACHE="no";
SLEEP="0";
ROOT_IN_RAM="no";
SPLASH_LAST_PROGRESS="45";
host="`hostname`";
unset OVERLAY0 OVERLAY RUN PKG ROOT ROOTDEV ROOT_BN ROOT_OPT RW RO STORAGE_DEV STORAGE_MP STORAGE_MOUNT;
export STORAGE_DEV STORAGE_MP;
brk_start="0";
brk_end="99";
brk_n="$brk_start";
himem="32768";
author="Petrov V.Y. <petrov.vy@gmail.com>";
version="0.06, 070905";
version="0.07, 080607";
version="0.08, 080711";
version="0.09, 080926";
version="0.10, 081023";
version="0.20, 090716";
version="0.21, 090827";
version="0.22, 100201";
version="0.24, 100208";
version="0.25, 100414";
version="0.26, 100707, remove plymouth, add fbsplash.";
version="0.27, 101203, add overlay with empty \$ROOT.";
version="1.01, 130201, Gentoo 130121.";
version="1.02, 130213, add overlay0.";
version="1.03, 160516, Gentoo 140710, kernel 3.12.21-gentoo-r1.p4.";


initkmsg() {
	[[ -e /dev/kmsg ]] && echo "initrd: ${*}" >> /dev/kmsg;
}

initmsg() {
	initkmsg "${*}";
	echo -e "initrd: ${HILITE}${*}${NORMAL}"
}

emsg() {
	echo -e "${ERR}${*}${NORMAL}";
}

echonmsg() {
	#echo -n -e "${HILITE}${*}${NORMAL}"
	echo -n -e "${*}"
}


brk() {
	brk_n=$(($brk_n+1));
	local msg="$*";
	local b=`eval echo '$b'${brk_n}`;

	initkmsg "${msg} (b${brk_n})";
	if [[ "$b" == "yes" ]]; then
		[[ -n $SPLASH_FUNCS ]] && splash "rc_exit";
		initkmsg "breakpoint $brk_n, run bash."; echo;
		[[ -d /root ]] && H="/root" || H="/";
		env HOME=$H setsid bash;
	fi;
}


brkA() {
	local A="$1"; shift;
	local msg="$*";
	local b=`eval echo '$b_'${A}`;

	initkmsg "${msg} (b_${A})";
	if [[ "$b" == "yes" ]]; then
		[[ -n $SPLASH_FUNCS ]] && splash "rc_exit";
		initkmsg "breakpoint '$A', run bash."; echo;
		[[ -d /root ]] && H="/root" || H="/";
		env HOME=$H setsid bash;
	fi;
}


err() {
	local msg=$1 action=$2 param=$3 timeout="";
	if [[ $action == "sh" ]]; then
		emsg "error: ${msg}. Go to shell.."; echo;
		[[ $param == "warning" ]] && timeout="-t 10";
		sulogin $timeout /dev/console;
	elif [[ $action == "reboot" ]]; then
		emsg "error: ${msg}. System will be rebooted.."; echo;
		[[ -n $param ]] && sulogin -t $param /dev/console;
		sync;
		[[ "$host" == '(none)' ]] && umount -adf >/dev/null 2>&1;
		[[ "$host" == '(none)' ]] && /sbin/reboot -dfh;
	elif [[ $action == "stop" ]]; then
		emsg "error: ${msg}. System stopped."; echo;
		sync;
		[[ "$host" == '(none)' ]] && umount -adf >/dev/null 2>&1;
		sulogin /dev/console;
		exec sleep 4294967295;
	else
		emsg "error: ${msg}."; echo;
	fi
}



mounted() {
	return `grep -q "$1" /proc/mounts`
}


find_on_dev() {
	[[ -z "$*" ]] && return 1;
	local what=$1 devs=$2;
	local d mp my_mkdir my_mount;

	unset STORAGE_DEV STORAGE_MP;
	for d in $devs; do
		[[ ! -e $d ]] && continue;
		mp="/mnt/${d#/dev/}";
		my_mount="no";
		if ! mounted "^$d $mp "; then
			my_mkdir="no";
			if [[ ! -d $mp ]]; then mkdir $mp; my_mkdir="yes"; fi
			if ! mount -o ro $d $mp >/dev/null 2>&1; then
				#initkmsg "failed mount '$d': skipping...";
				[[ $my_mkdir == "yes" ]] && rmdir $mp;
				continue;
			fi
			my_mount="yes";
		fi
		if [[ ! -e $mp/$what ]]; then
			#initkmsg "not found '${what}' on '$d': skipping...";
			[[ $my_mount == "yes" ]] && umount $mp;
			[[ $my_mkdir == "yes" ]] && rmdir $mp;
			continue;
		fi
		initkmsg "found '${what}' on '$d'.";
		STORAGE_DEV="$d";
		STORAGE_MP="$mp";
		return 0;
	done
	initkmsg "not found '${what}'.";
	return 1;
}


exec_newroot() {
	local N="$1";
	brkA prepare_rootfs "prepare new root.";
#	cd /;
#	mount -n -t devtmpfs none $N/dev -o exec,nosuid,mode=0755,size=10M;
#	mount -n -t devpts devpts $N/dev/pts -o gid=5,mode=0620,noexec,nosuid;
#	mount -n -t tmpfs none $N/dev/shm -o rw,mode=0755;
#	mount -n -t sysfs sysfs $N/sys -o nosuid,nodev,noexec;
#	mount -n -t securityfs -o nodev,noexec,nosuid securityfs $N/sys/kernel/security;
#	mount -n -t debugfs -o nodev,noexec,nosuid debugfs $N/sys/kernel/debug;
#	#mount -n -t configfs -o  nodev,noexec,nosuid configfs $N/sys/kernel/config;
#	mount -n -t tmpfs -o nodev,noexec,nosuid,mode=755,size=10m cgroup_root $N/sys/fs/cgroup;
#	mount -n -t proc proc $N/proc;
#	mount -n -t binfmt_misc binfmt_misc $N/proc/sys/fs/binfmt_misc -o nodev,noexec,nosuid;
#	#mount -n -t usbfs usbfs $N/proc/bus/usb -o rw,devmode=0664,devgid=85,noexec,nosuid;
#	mount -n -t tmpfs -o mode=0755,nosuid,nodev tmpfs $N/run;

	echo "ROOT_IN_RAM='$ROOT_IN_RAM'"                    >> $N/dev/.initrd.env;
	echo "INITRD_BOOT='yes'"                             >> $N/dev/.initrd.env;
#	echo "INITRD_DEV_PREPARED='yes'"                     >> $N/dev/.initrd.env;
#	echo "INITRD_SYS_PREPARED='yes'"                     >> $N/dev/.initrd.env;
#	echo "INITRD_PROC_PREPARED='yes'"                    >> $N/dev/.initrd.env;
#	echo "INITRD_RUN_PREPARED='yes'"                     >> $N/dev/.initrd.env;
	echo "STORAGE_MOUNT='$STORAGE_MOUNT'"                >> $N/dev/.initrd.env;
	echo "STORAGE_DEV='$STORAGE_DEV'"                    >> $N/dev/.initrd.env;
	echo "STORAGE_MP='$STORAGE_MP'"                      >> $N/dev/.initrd.env;
	echo "SPLASH_LAST_PROGRESS='$SPLASH_LAST_PROGRESS'"  >> $N/dev/.initrd.env;

	[[ -n $SPLASH_FUNCS ]] && splash_update_progress $SPLASH_LAST_PROGRESS;

	[[ -n $printk_old ]] && echo "$printk_old" > /proc/sys/kernel/printk;
	brkA umount_old "umount old /dev, /proc, /sys.";
	umount -nfl /dev/shm /dev/pts /dev /proc/sys/fs/binfmt_misc /proc /sys 2>/dev/null;

	brkA switch_root "switch to new rootfs '$ROOT'.";
#sulogin /dev/console;
#	cd $N;
#	exec chroot . $INIT </dev/console >/dev/console 2>&1;
	exec switch_root $N "$INIT" 2> /dev/null;
}


do_overlay()
{
	local OVR="$1" N="$2" a overlay f b;

	if [[ -z $OVR || -z $STORAGE_DEV || -z $STORAGE_MP ]]; then
		initkmsg "overlays: empty vars.";
		return;
	fi
	
	overlay="$(realpath $STORAGE_MP/$OVR)";
	if [[ ! -e $overlay ]]; then
		initkmsg "overlays: not exist overlay '$overlay'.";
		return;
	fi

	for f in $(find $overlay -type f -print | sort); do
		a=$(basename $f);
		initkmsg "overlays: use '$a'.";
		if [[ ($f =~ ^.*.tar.gz$) || ($f =~ ^.*.tar$) ]]; then
			if tar xf $f -C /root install 2>/dev/null; then
				x="/root/install";
				[[ -x $x ]] && $x install "$N" "$f" "$STORAGE_DEV" "$STORAGE_MP" 2>&1 | tee /dev/kmsg;
				rm -f $x;
			else
				[[ ! -d "$N" ]] && continue;
				tar xf $f --exclude Makefile --exclude version --exclude desc.txt -C "$N";
			fi
		elif [[ $f =~ ^.*.sq$ ]]; then
			[[ ! -d "$N" ]] && continue;
			cp -afP $f $N/mnt/;
			b=${a%.sq};
			mkdir $N/mnt/$b && mount -o ro,loop $N/mnt/$a $N/mnt/$b; rc=$?;
			if [[ $rc != 0 ]]; then err "f='$f', rc=$rc"; continue; fi
			x="$N/mnt/$b/install";
			[[ -f $x && -x $x ]] && $x install "$N" "$f" "$N/mnt/$b" 2>&1 | tee /dev/kmsg;
		elif [[ $f =~ ^.*\.sh$ ]]; then
			cp $f /tmp/$a >/dev/null 2>&1 && b="/tmp/$a";
			chmod u=rwX,go= $b;
			$b "$f" "$STORAGE_DEV" "$STORAGE_MP" | tee /dev/kmsg;
		else
			initkmsg "overlays: unsupported container '$a'.";
		fi
	done
}



# *****************************************************************************
#[[ "$q" == "quiet" && "$RHGB" == "yes" ]] || initmsg "start ${0}";

mount -oremount,rw /;
mount -n -t proc -o noexec,nosuid,nodev proc /proc
cmdline="`cat /proc/cmdline` "; # " $" is needed.
#echo "3 4 0 3" > /proc/sys/kernel/printk;

brkA start "start";

for x in $cmdline; do
	[[ $x == setx ]]           && set -x;
	[[ $x =~ ^b[0-9]+$ ]]      && eval ${x}="yes";
	[[ $x =~ ^b_[_0-9a-zA-Z]+$ ]] && eval ${x}="yes";
	[[ $x =~ ^root= ]]         && ROOT="${x#root=}";
	[[ $x =~ ^rootdev= ]]      && ROOTDEV="${x#rootdev=}";
	[[ $x =~ ^init= ]]         && INIT="${x#init=}";
	[[ $x =~ ^sleep= ]]        && SLEEP="${x#sleep=}";
	[[ $x =~ ^overlay0= ]]     && OVERLAY0="${x#overlay0=}";
	[[ $x =~ ^overlay= ]]      && OVERLAY="${x#overlay=}";
	[[ $x =~ ^norootchache ]]  && NOROOTCHACHE="yes";
	[[ $x =~ ^splash= ]]       && SPLASH="${x#splash=}";
	[[ $x == ro ]]             && RO="$x";
	[[ $x == rw ]]             && RW="$x";
	[[ $x == storage_mount ]]  && STORAGE_MOUNT="yes";
	[[ $x == version ]]        && SHOWVERSION="yes";
	[[ $x == quiet ]]          && QUIETX="yes";
done

#[[ $OVERLAY == "OVERLAY" && -z $ROOT ]] && OVERLAY="overlay";
#[[ $OVERLAY == "OVERLAY" && -n $ROOT ]] && OVERLAY="$ROOT.overlay";
[[ -n $OVERLAY ]] && OVERLAY_SHOW="$OVERLAY" || OVERLAY_SHOW="none";
[[ -n $ROOT ]] && ROOT_BN="${ROOT##*/}";

unset printk_old;
if [[ "$QUIETX" == "yes" ]]; then
	printk_old=$(cat /proc/sys/kernel/printk);
	#echo "0 0 0 0" > /proc/sys/kernel/printk;
	#echo "3 4 0 3" > /proc/sys/kernel/printk;
	echo "1 4 0 3" > /proc/sys/kernel/printk;
	#cat /proc/sys/kernel/printk;
fi
if [[ "$SHOWVERSION" == "yes" ]]; then
	initmsg "     Author: ${author}.";
	initmsg "     Version: ${version}.";
fi

[[ -n $RO ]] && ROOT_OPT="-o ro";
[[ -n $RW ]] && ROOT_OPT="-o rw";


brkA prepare_dev "prepare /dev.";
mount -n -t devtmpfs none /dev -o exec,nosuid,mode=0755,size=10M;
[[ -e /dev.tar.gz ]]  && tar xzf /dev.tar.gz -C / >/dev/null 2>&1;
[[ -c /dev/console ]] || mknod -m 600 /dev/console c 5 1
[[ -c /dev/tty1 ]]    || mknod -m 620 /dev/tty1 c 4 1;
[[ -c /dev/tty  ]]    || mknod -m 666 /dev/tty c 5 0;
[[ -c /dev/null ]]    || mknod -m 666 /dev/null c 1 3;
[[ -c /dev/kmsg ]]    || mknod -m 660 /dev/kmsg c 1 11; 
[[ -d /dev/pts ]]     || mkdir -m 0755 -p /dev/pts;
[[ -d /dev/shm ]]     || mkdir -m 1777 -p /dev/shm;

#[[ -e /dev/stdin ]]   || ln -snf fd/0 /dev/stdin;
#[[ -e /dev/stdout ]]  || ln -snf fd/1 /dev/stdout;
#[[ -e /dev/stderr ]]  || ln -snf fd/2 /dev/stderr;
#[[ -e /proc/kcore ]]  || ln -snf /proc/kcore /dev/core;

mount -n -t devpts devpts /dev/pts -o noexec,nosuid,gid=5,mode=0620;
mount -n -t tmpfs  shm    /dev/shm -o noexec,nosuid,nodev;

[[ -d /sys ]] || mkdir -m 0755 /sys;
mount -n -t sysfs sysfs /sys -o nosuid,nodev,noexec;

mount -t binfmt_misc binfmt_misc /proc/sys/fs/binfmt_misc -o nodev,noexec,nosuid;

brkA start_udevd "start udevd.";
[[ -e /proc/sys/kernel/hotplug ]] && echo "" > /proc/sys/kernel/hotplug;
pkill -9 udevd >/dev/null 2>&1;
/lib/systemd/systemd-udevd --daemon; rc=$?;
#echo CONSOLE=/dev/console > /dev/.udev_populate;
udevadm trigger --type=subsystems --action=add;
udevadm trigger --type=devices --action=add;
udevadm settle --timeout=60;


eval `dircolors -b /etc/DIR_COLORS`;
[[ -n $SPLASH && -x /sbin/splashctl ]] && . /sbin/splashctl start;


brkA sleep "sleep $SLEEP second.";
if [[ "$SLEEP" -gt 0 ]]; then
	sleep "$SLEEP";
fi

#brkA stop_udevd "stop udevd.";
#pkill -9 udevd >/dev/null 2>&1;
#rm -f /dev/.udev_populate;
[[ -n $SPLASH_FUNCS ]] && splash_update_progress 5;


#modules="loop cryptoloop aes squashfs
#	ehci-hcd ohci-hcd uhci-hcd mbcache jbd ext2 ext3 fat vfat
#	scsi_mod sd_mod usb-storage libata ata_piix pata_via pata_jmicron sata_via ahci";
modules="exportfs aufs";
brkA load_modules "load modules: $modules.";
for m in $modules; do
	echo $m | grep -q "^#" || modprobe $m 1>/dev/null 2>&1;
done
[[ -n $SPLASH_FUNCS ]] && splash_update_progress 10;


if [[ -n "${OVERLAY0}" ]]; then
	brk "search overlay0 '${OVERLAY0}'.";
	SEARCH_DEVS=`echo $ROOTDEV /dev/sd* /dev/sr*`;
	find_on_dev "$OVERLAY0" "$SEARCH_DEVS"; rc=$?;
	[[ $rc != 0 ]] && err "not found overlay0 '${OVERLAY0}'" "sh" "critical";
	brkA overlays0 "overlays0: '$OVERLAY_SHOW' ($STORAGE_DEV:$STORAGE_MP).";
	do_overlay "${OVERLAY0}" "/";
	[[ -n $SPLASH_FUNCS ]] && splash_update_progress 15;
fi


if [[ -n "$ROOT" && (-b "$ROOT" || "$ROOT" =~ "LABEL=" || "$ROOT" =~ "UUID=") ]]; then
	# $ROOT is a block special file, or LABEL or UUID, then just mount and boot from it
	brkA mount_root "mount new real rootfs.";
	mkdir /N;
	chmod u=rwx,go=rx /N;
	mount $ROOT_OPT "$ROOT" /N >/dev/null 2>&1;
	[[ $? != "0" ]] && err "fail mount '${ROOT}'" "sh" "critical";
	exec_newroot;
fi


# expected rootfs in squishfs: search, mount and load
brkA search_rootfs "search rootfs '${ROOT}'.";
ROOT="${ROOT:-root.sq}";
SEARCH_DEVS=`echo $ROOTDEV /dev/sd* /dev/sr*`;
find_on_dev "$ROOT" "$SEARCH_DEVS"; rc=$?;
[[ $rc != 0 ]] && err "not found rootfs '${ROOT}'" "sh" "critical";
ROOT_IN_RAM="yes";
[[ -n $SPLASH_FUNCS ]] && splash_update_progress 20;


brkA cache_rootfs "no cache rootfs '${ROOT}' to RAM: $NOROOTCACHE.";
if [[ "$NOROOTCACHE" = "no" ]]; then
	mem=`free | grep "Mem:" | awk '{print($2)}'`;
	if [[ "$mem" -lt ${himem} ]]; then
		initkmsg "unsufficient memory (${mem}): no cache rootfs '${ROOT}'.";
		NOROOTCACHE="yes";
	else
		cp $STORAGE_MP/${ROOT} /; rc=$?;
		if [[ $rc != 0 ]]; then
			initkmsg "caching failed (likely due to lack of space).";
			rm -f /${ROOT};
		fi
	fi
fi
[[ -n $SPLASH_FUNCS ]] && splash_update_progress 30;


[[ -e /${ROOT_BN} ]] && from="RAM" || from="storage";
[[ -e /${ROOT_BN} ]] && AROOT="/${ROOT_BN}" || AROOT="$STORAGE_MP/${ROOT}";
brkA mount_rootfs "mount new rootfs '$AROOT' from $from.";
mkdir /N /N/aufs /N/er2_aufs_{rw,ro};
mount -o ro,loop "$AROOT" /N/er2_aufs_ro; rc=$?;
[[ $rc != 0 ]] && err "failed mount rootfs '$AROOT'" "sh" "critical";
mount -t tmpfs tmpfs /N/er2_aufs_rw >/dev/null 2>&1; rc=$?;
[[ $rc != 0 ]] && err "failed mount tmpfs" "sh" "critical";
mount -t aufs -o br=/N/er2_aufs_rw=rw:/N/er2_aufs_ro=ro none /N/aufs; rc=$?;
[[ $rc != 0 ]] && err "failed mount aufs" "sh" "critical";
[[ -n $SPLASH_FUNCS ]] && splash_update_progress 35;

mkdir /N/aufs/mnt/er2_aufs_{rw,ro};
mount --move /N/er2_aufs_rw /N/aufs/mnt/er2_aufs_rw;
mount --move /N/er2_aufs_ro /N/aufs/mnt/er2_aufs_ro;


brkA overlays "overlays: '$OVERLAY_SHOW' ($STORAGE_DEV:$STORAGE_MP).";
do_overlay "${OVERLAY}" "/N/aufs";
[[ -n $SPLASH_FUNCS ]] && splash_update_progress 40;


[[ "$STORAGE_MOUNT" != "yes" ]] && umount $STORAGE_MP && unset STORAGE_MP;


exec_newroot /N/aufs;
