#!/bin/busybox sh
# shellcheck disable=SC1091

[ -e /hooks/10-verbose-initfs.sh ] && set -x

. ./init_functions.sh
. /usr/share/misc/source_deviceinfo

export PATH=/usr/bin:/bin:/usr/sbin:/sbin
/bin/busybox --install -s
/bin/busybox-extras --install -s

# Mount everything, set up logging, modules, mdev
mount_proc_sys_dev
create_device_nodes
setup_log
setup_firmware_path
# shellcheck disable=SC2154
load_modules /lib/modules/initramfs.load "$deviceinfo_modules_initfs usb_f_rndis"

setup_mdev
setup_dynamic_partitions "${deviceinfo_super_partitions:=}"
setup_framebuffer
show_splash "Loading..."
mount_subpartitions
run_hooks /hooks

# Always run dhcp daemon/usb networking for now (later this should only
# be enabled, when having the debug-shell hook installed for debugging,
# or get activated after the initramfs is done with an OpenRC service).
setup_usb_network
start_unudhcpd

mount_boot_partition /boot
extract_initramfs_extra /boot/initramfs-extra
setup_udev
run_hooks /hooks-extra

wait_root_partition
delete_old_install_partition
resize_root_partition
unlock_root_partition
resize_root_filesystem
mount_root_partition

# Mount boot partition into sysroot, so OpenRC doesn't need to do it (#664)
umount /boot
mount_boot_partition /sysroot/boot "rw"

init="/sbin/init"
setup_bootchart2

# ProLinux Init
# /squishroot - squashfs rootfs
# /persistroot - overlayed persisant storage
# /tmproot - overlayed tmpfs
# /workdir - overlayfs workdir
# /oroot - target root

splash_error() {
    show_splash "ERROR: $1"
    sleep 5
    pkill pbsplash
    /bin/busybox sh
}

echo "Running ProLinux Init script..."
#  show_splash "Loading system configuration..."
pkill pbsplash

echo "-- Welcome to Sineware ProLinux 2 --"
modprobe squashfs || splash_error "Could not load squashfs module!"
modprobe overlay || splash_error "Could not load overlayfs module!"
echo "Mounting prolinux squashfs 'squishroot'"
mount -o remount,rw /sysroot

echo "----"
echo "Loading System Configuration..."
# read /sysroot/data/prolinux.toml for which squashfs to use
selected_root=$(awk -F "=" '/pl2.selected_root/ {print $2}' /sysroot/data/prolinux.toml | tr -d ' ' | tr -d "'")
locked_root=$(awk -F "=" '/pl2.locked_root/ {print $2}' /sysroot/data/prolinux.toml | tr -d ' ' | tr -d "'")
echo "Selected Root: $selected_root"
echo "Locked Root: $locked_root"
echo "----"

mount -o loop /sysroot/prolinux_${selected_root}.squish /sysroot/squishroot 

if grep -q pl2.stage2 /proc/cmdline; then
    echo "Loaded stage 2 kernel!"
    # we are booted into the stage 2 kernel.
    # if we are locked, we need to mount the locked rootfs
    if [ "$locked_root" = "true" ]; then
        echo "Locked rootfs detected, mounting..."
        mkdir -pv /tmproot
        mount -t tmpfs tmpfs /tmproot
        mkdir -pv /tmproot/overlay
        mkdir -pv /tmproot/workdir
        mount -t overlay overlay -o lowerdir=/sysroot/squishroot:/sysroot/persistroot,upperdir=/tmproot/overlay,workdir=/tmproot/workdir /sysroot/oroot || splash_error "Could not mount overlayfs!"
    else
        mount -t overlay overlay -o lowerdir=/sysroot/squishroot,upperdir=/sysroot/persistroot,workdir=/sysroot/workdir /sysroot/oroot || splash_error "Could not mount overlayfs!"
    fi
    mount --bind /sysroot /sysroot/oroot/sineware
    mount --bind /sysroot/data/home /sysroot/oroot/home

    mkdir -pv /sysroot/oroot/lib/modules
    mount --bind /sysroot/squishroot/opt/device-support/$deviceinfo_codename/modules /sysroot/oroot/lib/modules || splash_error "Could not mount kernel modules!"

    ls -l /sysroot
    echo "----"
    #/bin/busybox sh

    ls -l /sysroot/oroot
    echo "Starting up..."
    
    show_splash "Starting up..."
else 
    echo "Loading stage 2 kernel (kexec) from /sysroot/squishroot/device-support/$deviceinfo_codename/..."
    cmdline=$(cat /proc/cmdline)

    # remove module_blacklist=* from cmdline
    cmdline=$(echo $cmdline | sed 's/module_blacklist=[^ ]*//g')
    
    cmdline="$cmdline pl2.stage2"
    kexec -l /sysroot/squishroot/opt/device-support/$deviceinfo_codename/vmlinuz* --initrd=/sysroot/squishroot/opt/device-support/$deviceinfo_codename/initramfs --append="$cmdline"
    umount /sysroot/squishroot
    kexec -e

    # kexec failed
    splash_error "Could not kexec stage 2 kernel!"
fi

# Switch root
killall telnetd mdev udevd msm-fb-refresher 2>/dev/null
umount /proc
umount /sys
umount /dev/pts
umount /dev

# shellcheck disable=SC2093
exec switch_root /sysroot/oroot "$init"

echo "ERROR: switch_root failed!"
echo "Looping forever. Install and use the debug-shell hook to debug this."
echo "For more information, see <https://postmarketos.org/debug-shell>"
loop_forever
