#!/bin/busybox sh
##################################################
#
# PXE script by Serva - Automated PXE Server
#   Copyright (c) 2010-2017 by Patrick Masotta
#           www.vercot.com/~serva/
#
#   License: GNU Public License, 2017/09/06
##################################################

#
# By Chih-Wei Huang <cwhuang@linux.org.tw>
# and Thorsten Glaser <tg@mirbsd.org>
#
# Last updated 2015/10/23
#
# License: GNU Public License
# We explicitely grant the right to use the scripts
# with Android-x86 project.
#


INITRD="INITRD_N23.1.GZ"
KVER="4.4.24-android-x86_64"


PATH=/sbin:/bin:/system/bin:/system/xbin; export PATH

# configure debugging output
# Lets modify this to generate log with this data regardless od DEBUG=X.
# But with DEBUG=0/"" it shouldn't have set -x
if [ -n "$DEBUG" ]; then
	LOG=/tmp/log
	set -x
else
	LOG=/dev/null
	test -e "$LOG" || busybox mknod $LOG c 1 3
fi
exec 2>> $LOG

# early boot
if test x"$HAS_CTTY" != x"Yes"; then
	# initialise /proc and /sys
	busybox mount -t proc proc /proc
	busybox mount -t sysfs sys /sys
	# let busybox install all applets as symlinks
	busybox --install -s
	# spawn shells on tty 2 and 3 if debug or installer
	if test -n "$DEBUG" || test -n "$INSTALL"; then
		# ensure they can open a controlling tty
		mknod /dev/tty c 5 0
		# create device nodes then spawn on them
		mknod /dev/tty2 c 4 2 && openvt
		mknod /dev/tty3 c 4 3 && openvt
	fi
	if test -z "$DEBUG" || test -n "$INSTALL"; then
		echo 0 0 0 0 > /proc/sys/kernel/printk
	fi
	# initialise /dev (first time)
	mkdir -p /dev/block
	echo /sbin/mdev > /proc/sys/kernel/hotplug
	mdev -s
	# re-run this script with a controlling tty
	exec env HAS_CTTY=Yes setsid cttyhack /bin/sh "$0" "$@"
fi

# now running under a controlling tty; debug output from stderr into log file
# boot up Android

echo "┌────────────────────────────────────────────────┐"
echo "│          Serva - Automated PXE Server          │"
echo "│   Copyright (c) 2010-2017 by Patrick Masotta   │"
echo "│             www.vercot.com/~serva/             │"
echo "└────────────────────────────────────────────────┘"
sleep 2

error()
{
	echo $*
	return 1
}

try_mount()
{
	RW=$1; shift
	if [ "${ROOT#*:/}" != "$ROOT" ]; then
		# for NFS roots, use nolock to avoid dependency to portmapper
		RW="nolock,$RW"
	fi
	# FIXME: any way to mount ntfs gracefully?
	mount -o $RW,noatime,nodiratime $@ || mount.ntfs-3g -o rw,force $@
}

# region @jide
mount_system_dev_img_if_necessary()
{
	if [ -n "$REMOUNT_RW" ]; then
		[ 0$REMOUNT_RW -eq 0 ] && return
	else
		[ 0$removable -eq 1 ] && return
	fi

	if [ 0$REMOUNT_RW -gt 0 ] || grep -qE "ro.build.type=(userdebug|eng)" /android/system/build.prop; then
		remount_rw
		mount | grep /mnt | grep -q rw || return
		if [ ! -e /mnt/$SRC/system_dev.img ]; then
			echo "extract system.sfs to /mnt/$SRC/system_dev.img for developer to easily adb sync"
			(( pv /sfs/system.img > /mnt/$SRC/system_dev.img )) 2>&1
			[ $? -ne 0 ] && return
		else
			echo "using the existing /mnt/$SRC/system_dev.img for developer to easily adb sync"
		fi
		umount /android/system
		mount -o loop,rw /mnt/$SRC/system_dev.img /android/system
	fi
}
# endregion

check_root()
{
	local r
	if [ "`dirname $1`" = "/dev" ]; then
		[ -e $1 ] || return 1
		blk=`basename $1`
		[ ! -e /dev/block/$blk ] && ln $1 /dev/block
		dev=/dev/block/$blk
		r=$(ls /sys/block/$blk/removable /sys/block/*/$blk/../removable 2>/dev/null)
		[ -n "$r" ] && r=$(cat $r) || r=0
	else
		dev=$1
	fi
	try_mount ro $dev /mnt || return 1
	if [ -n "$iso" -a -e /mnt/$iso ]; then
		mount --move /mnt /iso
		mkdir /mnt/iso
		mount -o loop /iso/$iso /mnt/iso
		SRC=iso
	elif [ ! -e /mnt/$SRC/ramdisk.img ]; then
		return 1
	fi
	removable=$r
	zcat /mnt/$SRC/ramdisk.img | cpio -id > /dev/null
	[ -n "$SYSTEM" ] && blk=`basename $SYSTEM` || blk=
	if [ -b "/dev/$blk" ]; then
		[ ! -e /dev/block/$blk ] && ln /dev/$blk /dev/block
		mount -o ro /dev/block/$blk system
	elif [ -e /mnt/$SRC/system.sfs ]; then
		mount -o loop /mnt/$SRC/system.sfs /sfs
		mount -o loop,ro /sfs/system.img system
		mount_system_dev_img_if_necessary
	elif [ -e /mnt/$SRC/system.img ]; then
		mount -o loop,ro /mnt/$SRC/system.img system
	elif [ -d /mnt/$SRC/system ]; then
		mount --bind /mnt/$SRC/system system
	else
		rm -rf *
		return 1
	fi
	mkdir mnt
	if [ -n "$DEBUG" ]; then
		echo " found at $1"
	fi
	rm /sbin/mke2fs
	hash -r
}

remount_rw()
{
	# "foo" as mount source is given to workaround a Busybox bug with NFS
	# - as it's ignored anyways it shouldn't harm for other filesystems.
	mount -o remount,rw foo /mnt
}

debug_shell()
{
	if [ -x system/bin/sh ]; then
		echo Running MirBSD Korn Shell...
		USER="($1)" system/bin/sh -l 2>&1
	else
		echo Running busybox ash...
		sh 2>&1
	fi
}



kver=$(uname -r)
if [ $KVER != $kver ]; then
 echo "** ERROR: $INITRD does not support Kernel=$kver"
 setsid cttyhack /bin/sh                       
fi

if [ $netpath ]; then
echo "Starting Network Services... "

depmod
sleep 2


#kver=`uname -r`
#insmod /lib/modules/$kver/kernel/drivers/scsi/vmw_pvscsi.ko            2>&1
#insmod /lib/modules/$kver/kernel/drivers/hv/hv_vmbus.ko                2>&1
#insmod /lib/modules/$kver/kernel/drivers/scsi/hv_storvsc.ko            2>&1
#insmod /lib/modules/$kver/kernel/drivers/net/hyperv/hv_netvsc.ko       2>&1
#insmod /lib/modules/$kver/kernel/drivers/hv/hv_utils.ko                2>&1
#insmod /lib/modules/$kver/kernel/drivers/hv/hv_balloon.ko              2>&1
#insmod /lib/modules/$kver/kernel/drivers/hid/hid-hyperv.ko             2>&1
#sleep 70


# load scripts
for s in `ls /scripts/* /src/scripts/*`; do
        test -e "$s" && source $s
#        test -e "$s"  &&  [ "${s:(-9)}" != "1-install" ] && source $s
done

auto_detect


#check netpath
urlprot=${netpath:0:7}
if [[ "$urlprot" != "http://" ]]; then
 echo "ERROR: No HTTP netpath."
 setsid cttyhack /bin/sh                        
fi


#let's see if BOOTIF(IPPAPEND 2) is present
if [ -z $BOOTIF ]; then
 echo "ERROR: IPAPPEND 2 not present."
 setsid cttyhack /bin/sh                        
fi

echo "Probe Ethernet..."
sleep 3
ifconfig lo up

# get mac address out of BOOTIF
bootif_mac=$(echo ${BOOTIF#*-} | sed -e 'y,-,:,')

# look for devices with matching mac address, and set DEVICE to
# appropriate value if match is found.
for device in /sys/class/net/* ; do
 if [ -f "$device/address" ]; then
#echo "device=$device"
   current_mac=$(cat "$device/address")
#echo "current_mac=$current_mac"
   if [ "$bootif_mac" = "$current_mac" ]; then
    DEVICE=${device##*/}
#echo "DEVICE=$DEVICE"
    break
   fi
 fi
done


if [ -z $DEVICE ]; then
 echo "Error locating booting ETH device."
 setsid cttyhack /bin/sh                        
fi

ifconfig $DEVICE up
ip_clnt=$(udhcpc -i $DEVICE | grep Lease | cut -f 3 -d ' ')
ifconfig $DEVICE $ip_clnt up

ifconfig "$DEVICE"


echo "wget ${netpath}system.sfs..."
wget "${netpath}system.sfs"  2>&1
#echo "wget ${netpath}system.img..."
#wget "${netpath}system.img"  2>&1

if [ $? -ne 0 ]; then
 check_status 1
 echo "Wget failed."
 setsid cttyhack /bin/sh                        
fi
mv /system.sfs /mnt/$SRC        2>&1
#mv /system.img /mnt/$SRC        2>&1

echo "wget ${netpath}ramdisk.img..."
wget "${netpath}ramdisk.img"  2>&1
if [ $? -ne 0 ]; then
 check_status 1
 echo "Wget failed."
 setsid cttyhack /bin/sh                        
fi
mv /ramdisk.img /mnt/$SRC       2>&1

if [ -n "$INSTALL" ]; then
 echo "wget ${netpath}install.img..."
 wget "${netpath}install.img"  2>&1
 if [ $? -ne 0 ]; then
  check_status 1
  echo "Wget failed."
  setsid cttyhack /bin/sh                        
 fi
mv /install.img /mnt/$SRC       2>&1
fi

if [ -n "$INSTALL" ]; then
 echo "wget ${netpath}kernel..."
 wget "${netpath}kernel"  2>&1
 if [ $? -ne 0 ]; then
  check_status 1
  echo "Wget failed."
  setsid cttyhack /bin/sh                        
 fi
mv /kernel /mnt/$SRC    2>&1
fi

if [ -n "$INSTALL" ]; then
 echo "wget ${netpath}initrd.img..."
 wget "${netpath}initrd.img"  2>&1
 if [ $? -ne 0 ]; then
  check_status 1
  echo "Wget failed."
  setsid cttyhack /bin/sh                        
 fi
mv /initrd.img /mnt/$SRC        2>&1
fi

sync

rm -rf /lib/modules 2>&1 #

mount -t tmpfs tmpfs /android           2>&1  # initrd has a /android  (ramdisk)
cd /android                             2>&1



##
zcat /mnt/$SRC/ramdisk.img | cpio -id > /dev/null

mount -o loop /mnt/$SRC/system.sfs /sfs # initrd.img  has a /sfs
mount -o loop /sfs/system.img system    # ramdisk.img has a /system
#mount -o loop /mnt/$SRC/system.img system    # ramdisk.img has a /system




mkdir cache mnt mnt/sdcard              2>&1
mount -t tmpfs tmpfs cache              2>&1    # (ramdisk)
##

ln -s mnt/$SRC  /src                    2>&1
ln -s android/system /                  2>&1
ln -s ../system/lib/modules /lib        2>&1    #ln /lib/modules: File exists
ln -s ../system/lib/firmware /lib       2>&1


if [ -n "$INSTALL" ]; then
    cd /
    #zcat /mnt/$SRC/install.img | cpio -iud > /dev/null
    zcat /src/install.img | cpio -iud > /dev/null

    source /scripts/1-install

fi


# ensure keyboard driver is loaded
[ -n "$INSTALL" -o -n "$DEBUG" ] && modprobe atkbd


if [ 0$DEBUG -gt 0 ]; then
    echo -e "\nType 'exit' to continue booting...\n"
    debug_shell debug-found
fi


# A target should provide its detect_hardware function.
# On success, return 0 with the following values set.
# return 1 if it wants to use auto_detect
[ "$AUTO" != "1" ] && detect_hardware && FOUND=1


[ "$INSTALL" -eq 1 ] && do_install
[ "$INSTALL" = "2" -o "$INSTALL" = "PREINSTALL_MBR" -o "$INSTALL" = "PREINSTALL_EFI" ] && do_preinstall


load_modules
mount_data
mount_sdcard
setup_tslib
setup_dpi
post_detect
find_network_dev_name


if [ 0$DEBUG -gt 1 ]; then
    echo -e "\nUse Alt-F1/F2/F3 to switch between virtual consoles"
    echo -e "Type 'exit' to enter Android...\n"

    debug_shell debug-late
fi



[ -n "$DEBUG" ] && SWITCH=${SWITCH:-chroot}

# We must disable mdev before switching to Android
# since it conflicts with Android's init
echo > /proc/sys/kernel/hotplug

export ANDROID_ROOT=/system

# Dump logs right before attempting to load Android.
dump_logs "END-OF-INIT"


exec ${SWITCH:-switch_root} /android /init


# avoid kernel panic
while :; do
    echo
    echo '      Android-x86 console shell. Use only in emergencies.'
    echo
    debug_shell fatal-err
done


fi # if [ $netpath ]; then -------------------------------------------------------------------/




if [ -n "$DEBUG" ]; then
	echo -n Detecting Android-x86...
fi

[ -z "$SRC" -a -n "$BOOT_IMAGE" ] && SRC=`dirname $BOOT_IMAGE`

for c in `cat /proc/cmdline`; do
	case $c in
		iso-scan/filename=*)
			eval `echo $c | cut -b1-3,18-`
			;;
		*)
			;;
	esac
done

mount -t tmpfs tmpfs /android
cd /android
while :; do
	for device in ${ROOT:-/dev/[hmnsv][dmrv][0-9a-z]*}; do
		check_root $device && break 2
		mountpoint -q /mnt && umount /mnt
	done
	sleep 1
	if [ -n "$DEBUG" ]; then
		echo -n .
	fi
done

ln -s mnt/$SRC /src
ln -s android/system /
ln -s ../system/lib/firmware ../system/lib/modules /lib

if [ -n "$INSTALL" ]; then
	zcat /src/install.img | ( cd /; cpio -iud > /dev/null )
fi

if [ -x system/bin/ln -a \( -n "$DEBUG" -o -n "$BUSYBOX" \) ]; then
	mv /bin /lib .
	sed -i 's|\( PATH.*\)|\1:/bin|' init.environ.rc
	rm /sbin/modprobe
	busybox mv /sbin/* sbin
	rmdir /sbin
	ln -s android/bin android/lib android/sbin /
	hash -r
fi

# ensure keyboard driver is loaded
[ -n "$INSTALL" -o -n "$DEBUG" ] && busybox modprobe -a atkbd hid-apple


# Save some important, useful boot info for the Android log dumping script and more
echo '#!/system/bin/sh' > boot_info
echo 'DEBUG="'$DEBUG'"' >> boot_info
echo 'SAVE_LOGS="'$SAVE_LOGS'"' >> boot_info
echo 'DATA_IN_MEM="'$DATA_IN_MEM'"' >> boot_info
echo 'native_partition_path="'$dev'"' >> boot_info
echo 'native_partition_uuid="'`/system/bin/blkid -s UUID -o value $dev`'"' >> boot_info
echo 'native_partition_remix_dir="'$SRC'"' >> boot_info
# If booted from removable storage device
# If any REMIX_OS labeled partition on native boot device found, then set as winfriendly partition path.
removable_boot_win_partition_path=$(/system/bin/blkid -t LABEL="REMIX_OS" -o device ${dev%?}*)
if [[ -n "$removable_boot_win_partition_path" ]]; then
	echo 'removable_boot_win_partition_path="'$removable_boot_win_partition_path'"' >> boot_info
	echo 'removable_boot_win_partition_uuid="'`/system/bin/blkid -s UUID -o value $removable_boot_win_partition_path`'"' >> boot_info
fi

# Log dumper
# Need to decide log dumping points - when should it dump?
dump_logs()
{
	if [[ -n "$DEBUG" || -n "$SAVE_LOGS" ]]; then
		boot_step=$1
		# Log naming
		brand=$(dmidecode -s system-manufacturer) && brand=${brand// /-}
		model=$(dmidecode -s system-product-name) && model=${model// /-}
		version=$(cat /system/build.prop | grep remixos.version | cut -d= -f2-) && version=${version// /-}
		system_arch=$(uname -a | grep -o 'x86\|x86_64' | head -1) && system_arch=${system_arch// /-}

		dmesg="dmesg_${boot_step}_${brand}_${model}_${version}_${system_arch}_$(date +%F_%H-%M).txt"
		lspci="lspci_${boot_step}_${brand}_${model}_${version}_${system_arch}_$(date +%F_%H-%M).txt"
		lsusb="lsusb_${boot_step}_${brand}_${model}_${version}_${system_arch}_$(date +%F_%H-%M).txt"
		cpuinfo="cpuinfo_${boot_step}_${brand}_${model}_${version}_${system_arch}_$(date +%F_%H-%M).txt"
		dmidecode="dmidecode_${boot_step}_${brand}_${model}_${version}_${system_arch}_$(date +%F_%H-%M).txt"
		debuglog="debuglog_${boot_step}_${brand}_${model}_${version}_${system_arch}_$(date +%F_%H-%M).txt"

		# Make sure storage writable and set logs path
		mount -o remount,rw /mnt
		for d in /mnt/$SRC /tmp; do
			logs_src="$d/RemixOS_Logs/Automatic"
			logs_path="$logs_src/${brand}_${model}/$boot_step"
			mkdir -p $logs_path && break
		done
		# Delete all automatically generated logs older than 14 days, no matter the device or boot_step
		find $logs_src -type f -mtime +14 -delete
		# Remove all logs in folder except for 12 most recent (2 of each log type)
		ls -dt $logs_path/* | tail -n +13 | xargs rm -rf > /dev/null

		# Actual dumping
		dmesg > $logs_path/$dmesg
		lspci > $logs_path/$lspci
		lsusb > $logs_path/$lsusb
		dmidecode > $logs_path/$dmidecode
		cat /proc/cpuinfo > $logs_path/$cpuinfo
		cat $LOG > $logs_path/$debuglog

		# COPY LOGS TO WIN FRIENDLY PARTITION IF BOOTED FROM REMOVABLE MEDIA
		if [[ -n "$removable_boot_win_partition_path" ]]; then
			mkdir -p /removable_boot_win_partition && mount $removable_boot_win_partition_path /removable_boot_win_partition
			removable_logs_src="/removable_boot_win_partition/RemixOS_Logs/Automatic"
			removable_logs_path="$removable_logs_src/${brand}_${model}/$boot_step" && mkdir -p $removable_logs_path
			find $removable_logs_src -type f -mtime +14 -delete
			ls -dt $removable_logs_path/* | tail -n +13 | xargs rm -rf > /dev/null
			cp $logs_path/$dmesg $removable_logs_path $logs_path/$lspci $removable_logs_path $logs_path/$lsusb $removable_logs_path $logs_path/$cpuinfo $removable_logs_path $logs_path/$dmidecode $removable_logs_path $logs_path/$debuglog $removable_logs_path
			# Unmount, because otherwise user won't be able to write to that partition once system loads.
			umount /removable_boot_win_partition
		fi
		if [ 0$DEBUG -gt 0 ]; then
			echo -e "\n\nAll logs and hardware info for booting up to this point were saved to:\n\n1. Native partition (where you installed OS) in dir:\n$SRC/RemixOS_Logs/Automatic\nFull path for DEBUG environment:\n$logs_path"
			[ -n "$removable_boot_win_partition_path" ] && echo -e '\n2. "REMIX_OS" Windows friendly partition in dir:\nRemixOS_Logs/Automatic'
			echo -e "\nMore logs for further boot steps will be saved after you exit this environment.\nThis logs session is retained along with 2 other recent sessions until manual or automatic removal.\nWhen logs older then 14 days are found - they are deleted."
		fi
	fi
}

if [ 0$DEBUG -gt 0 ]; then
	# Dump logs right before DEBUG terminal is accessible by user.
	dump_logs "AT-DEBUG-CLI"
	echo -e "\nTo scroll, use Shift + PgUp/PgDn\n\nEnter 'exit' to continue booting...\n"
	debug_shell debug-found
fi

# load scripts
for s in `ls /scripts/* /src/scripts/*`; do
	test -e "$s" && source $s
done

# A target should provide its detect_hardware function.
# On success, return 0 with the following values set.
# return 1 if it wants to use auto_detect
[ "$AUTO" != "1" ] && detect_hardware && FOUND=1

[ "$INSTALL" -eq 1 ] && do_install
[ "$INSTALL" = "2" -o "$INSTALL" = "PREINSTALL_MBR" -o "$INSTALL" = "PREINSTALL_EFI" ] && do_preinstall

mount_data
load_modules
mount_sdcard
init_remixos
setup_tslib
setup_dpi
post_detect

if [ 0$DEBUG -gt 1 ]; then
	echo -e "\nUse Alt-F1/F2/F3 to switch between virtual consoles"
	echo -e "Type 'exit' to enter Android...\n"

	debug_shell debug-late
fi

[ -n "$DEBUG" ] && SWITCH=${SWITCH:-chroot}

# We must disable mdev before switching to Android
# since it conflicts with Android's init
echo > /proc/sys/kernel/hotplug

export ANDROID_ROOT=/system

# Dump logs right before attempting to load Android.
dump_logs "END-OF-INIT"

exec ${SWITCH:-switch_root} /android /init

# avoid kernel panic
while :; do
	echo
	echo '	Android-x86 console shell. Use only in emergencies.'
	echo
	debug_shell fatal-err
done
