#!/bin/sh
PATH=/sbin:/usr/sbin:/bin:/usr/bin
export PATH HOME=/root TERM=linux

# Make every busybox applet available as /bin/<applet>.
/bin/busybox --install -s

# Pseudo / virtual filesystems.
mount -t proc     -o nosuid,noexec,nodev proc  /proc 2>/dev/null
mount -t sysfs    -o nosuid,noexec,nodev sysfs /sys  2>/dev/null
mount -t devtmpfs -o nosuid,mode=0755     dev   /dev  2>/dev/null
# tmpfs for /tmp and /run.
mount -t tmpfs -o nosuid,nodev,mode=1777 tmpfs /tmp
mount -t tmpfs -o nosuid,nodev,mode=0755 tmpfs /run
mkdir -p /dev/pts /dev/shm
mount -t devpts -o nosuid,noexec,gid=5,mode=0620 devpts /dev/pts 2>/dev/null
mount -t tmpfs  -o nosuid,nodev,mode=1777 tmpfs  /dev/shm 2>/dev/null

hostname busybox 2>/dev/null

# Networking: bring up loopback + every eth* via busybox udhcpc (ip backend).
ip link set lo up 2>/dev/null
for ifpath in /sys/class/net/eth*; do
    [ -e "$ifpath" ] || continue
    iface=${ifpath##*/}
    ip link set "$iface" up
    udhcpc -i "$iface" -s /usr/share/udhcpc/default.script -t 5 -T 2 -A 2 -b -q \
        >/dev/null 2>&1 || true
done

# Dropbear ssh in the background. Create everything it needs *first* so it
# never fails to start, then detach it.
mkdir -p /etc/dropbear /var/run /var/log /var/empty /run/dropbear /root/.ssh
chmod 0700 /var/empty /root/.ssh
dropbear -R -E -p 22 -p 2222 >/var/log/dropbear.log 2>&1 &

cat <<'BANNER'

  ==> busybox initramfs ready
      console login is root; ssh users: root/123@@@  busybox/busybox  bb/bb
      ssh ports: 22, 2222 (password auth) | doas/sudo: passwordless to root

BANNER

spawn_shell() {
    dev=$1
    name=$2
    [ -e "$dev" ] || return 0

    while true; do
        setsid -c /bin/sh -l <"$dev" >"$dev" 2>&1 || true
        echo "($name shell exited - respawning)" >"$dev" 2>/dev/null || true
        sleep 1
    done
}

# Keep both common QEMU modes interactive:
# - graphical: /dev/console points at tty0 because console=tty0 is last
# - nographic: serial stdio is /dev/ttyS0
spawn_shell /dev/ttyS0 serial &
spawn_shell /dev/console console
