#!/bin/bash -v
# SETUP
mount -nt proc  proc /proc
mount -nt sysfs sysfs /sys
(while read d m r; do [ "$d" = devtmpfs -a "$m" = /dev ] && exit 0
 done < /proc/mounts) || {
	mount -t tmpfs devfs /tmp &&
	cp -a /dev/* /tmp &&
	mount --move /tmp /dev
}
test -d /dev/pts || mkdir /dev/pts
mount -nt devpts devpts /dev/pts &
(
	ifconfig lo up
	test -f /etc/hostname && hostname --file /etc/hostname
)&

(
	cg=; while read g r; do
		[ "${g:0:1}" = '#' ] || cg="$cg,$g"
	done < /proc/cgroups
	mkdir /dev/cgroups &&
	mount -nt cgroup -o "${cg:1}" cgroup /dev/cgroups
)&

(
	mount -nt tmpfs run /run &&
	mkdir /run/lock /run/network
) &
mount -nt tmpfs tmp /tmp &
(
	mkdir /dev/shm &&
	mount -nt tmpfs shm /dev/shm -o nodev,nosuid,relatime
)&
mount -nt debugfs debugfs /sys/kernel/debug &

wait
read t < /proc/uptime && echo $t

HOME=/tmp # do not export HOME for udev
HOME=$HOME openvt -c 2 -w -- /bin/bash &
/sbin/udevd --daemon
/sbin/udevadm trigger
/sbin/udevadm settle
set +v # END OF MAIN SETUP
read t < /proc/uptime && echo -e "\e[1mUptime till now: $t\e[0m"

export HOME

test -e /proc/swaps && {
	echo Activating swap...
	swapon -a &
}

test -x /sbin/readahead-list && {
	echo Preloading programs...
	(
	for f in /usr/bin/vim /usr/bin/top ; do
		ldd -v "$f" |grep "^[	]/.*:$"|cut -c2-|cut -d: -f1
	done 2>/dev/null | grep -v "^/lib/" > /tmp/readahead
	test -e /tmp/readahead && {
		/sbin/readahead-list /tmp/readahead
		rm -f /tmp/readahead
	}
	) &
}

echo 9 >/proc/sysrq-trigger
echo -e '\e[32;1m'$(uname -a)'\e[0m'

export HOME
(shopt -s nullglob
grep -q notests /proc/cmdline ||
for LINUXRC_TEST in /boot/tests/*; do
	if test -x "$LINUXRC_TEST"
	then
		export LINUXRC_TEST
		echo TESTING "$LINUXRC_TEST"
		(. "$LINUXRC_TEST")
	fi
done) &

# reboot through three presses of power btn
(for e in /sys/class/input/event*/device/name
do
	if [ "$(< $e)" = 'Power Button' ]; then
		dev=${e%/device/name}
		exec /usr/local/bin/input-event -d /dev${dev:10} \
			-b power -t5 -r3 -- /sbin/reboot -f
	fi
done) &

# user shell
while :; do /sbin/getty 38400 tty3; done &
while :; do /sbin/getty 38400 tty4; done &
# X environment
grep -q nostartx /proc/cmdline ||
( mount -r /var
  test -d /var/lib/sudo && mount -t tmpfs -o size=$((1*1024*1024)) sudo /var/lib/sudo
  test -x /var/my-startx &&
  mount -r /home &&
  mount -t tmpfs -o size=$((1*1024*1024)) xkb /var/lib/xkb &&
  mount -t tmpfs -o size=$((15*1024*1024)) varlog /var/log &&
  /var/my-startx )&

NICE=
type -p nice >/dev/null && NICE="nice -n -3"
exec $NICE /bin/bash
