#!/bin/sh
# Author: Fox_exe
# Skype: Fox_experience

export PATH=/bin:/sbin:/usr/bin:/usr/sbin

echo "# Loading, please wait..."

# ========= VARS =========
SWAP_DEV=/dev/sda1
DATA_DEV=/dev/sda2
ROOT_DEV=/dev/sda3
CONF_DEV=/dev/sda5

# Temp vars
ROOTFS=/mnt/root
PARTSCRIPT="mklabel gpt \
mkpart primary 0% 1G \
mkpart primary 4G 100% \
mkpart primary 1G 4G"

# ========= FUNC =========
run_shell () {
	echo "# Runing a shell..."

	# Start network and run telnet server
	ifup -a
	sleep 1
	telnetd -l /bin/ash

	# Run UART shell
	exec 0</dev/console
	exec 1>/dev/console
	exec 2>/dev/console
	exec setsid cttyhack ash
}

ask_for_stop () {
	key='boot'
	read -r -p "### Press any key to stop and run shell... (2)" -n1 -t2 key
	if [ "$key" != 'boot' ] || [ $BUTTON_STATUS == 1 ]; then
		run_shell
	fi
}

# ========= CODE =========
echo "# Mounting filesystems..."
# hide error messages, if kernel already mount /dev
mount -t devtmpfs -o size=10M,mode=0755 udev /dev > /dev/null 2>&1
mkdir -p /dev/pts
mount -t devpts -o noexec,nosuid,gid=5,mode=0620 devpts /dev/pts > /dev/null 2>&1
mount -t tmpfs -o "nosuid,size=20%,mode=0755" tmpfs /run
mount -t sysfs -o nodev,noexec,nosuid sysfs /sys
mount -t proc -o nodev,noexec,nosuid proc /proc

echo "# Booting OS..."
ask_for_stop
if [ -b $SWAP_DEV ] && [ -b $ROOT_DEV ] && [ -b $DATA_DEV ] && [ ! -b $CONF_DEV ]; then
	mount $ROOT_DEV $ROOTFS || run_shell
	if [ -h $ROOTFS/linuxrc ]; then
		umount /sys 2> /dev/null
		umount /proc 2> /dev/null
		umount /dev/pts 2> /dev/null
		umount /dev 2> /dev/null
		exec switch_root -c /dev/console $ROOTFS /linuxrc || run_shell
	fi
fi

run_shell
