#!/bin/sh

# Default PATH differs between shells, and is not automatically exported
# by klibc dash.  Make it consistent.
export PATH=/sbin:/usr/sbin:/bin:/usr/bin

panic () {
    echo $@
    exit 1
}

[ -d /dev ] || mkdir -m 0755 /dev
[ -d /root ] || mkdir -m 0700 /root
[ -d /sys ] || mkdir /sys
[ -d /proc ] || mkdir /proc
[ -d /tmp ] || mkdir /tmp
[ -d /run ] || mkdir /run
mkdir -p /var/lock
mount -t sysfs -o nodev,noexec,nosuid sysfs /sys
mount -t proc -o nodev,noexec,nosuid proc /proc
mount -t tmpfs -o "nodev,noexec,nosuid,size=${RUNSIZE:-10%},mode=0755" tmpfs /run
mount -t devtmpfs -o $dev_exec,nosuid,mode=0755 udev /dev
mkdir -p /dev/pts
mount -t devpts -o noexec,nosuid,gid=5,mode=0620 devpts /dev/pts || true

# Start udev
SYSTEMD_LOG_LEVEL=info /lib/systemd/systemd-udevd --daemon --resolve-names=never
udevadm trigger --type=subsystems --action=add
udevadm trigger --type=devices --action=add
udevadm settle || true

# Lookup and mount boot device
mkdir /boot

BOOTPART=$(grep /boot /etc/fstab | grep -v '^#' | awk '{ print $1 }')

if [ -b "$BOOTPART" ]; then
    BOOTDEV=${BOOTPART}
else
    BOOTDEV="$(blkid -l -t "$BOOTPART" -o device)" || panic "UNABLE TO FIND BOOT DEVICE $BOOTPART"
fi
modprobe ext4
mount ${BOOTDEV} /boot

# Extract real initramfs
REALINITRAMFS="/boot/initrd.img-$(uname -r)"
[ -f "$REALINITRAMFS" ] || panic "UNABLE TO FIND INITRAMFS $REALINITRAMFS"

mkdir realinit
cd realinit
if command -v zstd > /dev/null && zstd --test "$REALINITRAMFS"; then
    zstd -d -c "$REALINITRAMFS" | cpio -i
elif gzip -t "$REALINITRAMFS"; then
    gzip -d -c "$REALINITRAMFS" | cpio -i
elif xz -t "$REALINITRAMFS"; then
    xz -d -c "$REALINITRAMFS" | cpio -i
elif unlzma -t "$REALINITRAMFS"; then
    unlzma -c "$REALINITRAMFS" | cpio -i
else
    panic "unable to decompress initramfs"
fi
cd /

# Make sure we use binaries and files from the real initramfs
for dir in bin sbin lib; do
    ln -sf /realinit/$dir /
done

mkdir /oldinit
mv /etc /usr /var /oldinit

for dir in conf etc scripts usr var cryptroot; do
    ln -sf /realinit/$dir /
done

# Cleanup before starting the "real" initramfs
udevadm control --exit

umount /boot
umount /dev/pts
umount /dev
umount /sys
[ -d /dev/pts ] && rmdir /dev/pts

# Start real initramfs (sourcing the script as it must be PID 1)
. /realinit/init
