#!/bin/bash
# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
# PID 1 of the Debian image (/sbin/init -> /usr/local/sbin/kw-init; Debian's
# /sbin is a link to /usr/sbin). The kw layer's runtime (/usr/lib/kw/, from
# the base) does the rest: rc (mounts, hostname, binfmt), welcome, net
# (DHCP, in the background), and at the end, after this has stopped every
# process, shutdown (leave /data clean). Services are Debian's init scripts
# as sysv-rc runs them: runlevel 2 once DHCP is done (/etc/rc2.d, in
# insserv's order), 0 or 6 at the end; runlevel S (rcS.d, initscripts' early
# boot) is the kw layer's rc and never runs. /usr/sbin/runlevel reports the
# level from /run/kw-runlevel, so that a package's invoke-rc.d starts what
# it installs. In between it respawns the console's login shell on hvc0
# (kwtty login: the user "user", or kw.user= on the kernel command line) and
# kwtty serve (started once DHCP is done, so that programs the host starts
# find the network), until poweroff, halt or reboot (/usr/local/sbin) signal
# it (SIGUSR1, SIGUSR2); then reboot(2) through the base's busybox.

# unkernel: PID 1 of the Debian image.
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
if [ $$ != 1 ]; then
	echo "kw-init: not PID 1" >&2
	exit 1
fi
/usr/lib/kw/rc
# x86 binaries: x86_64 and i386 (i486-i686 too) ELF executables go to
# /usr/local/libexec/kw-binfmt (box64), by binfmt_misc, which the
# rc has mounted. The magic/mask pairs are the ones from qemu's
# scripts/qemu-binfmt-conf.sh: 20 bytes, up to e_machine, matching ET_EXEC
# and ET_DYN.
d=/proc/sys/fs/binfmt_misc
if [ -e $d/register ]; then
	reg() { [ -e $d/$1 ] || printf '%s\n' ":$1:M::$2:$3:/usr/local/libexec/kw-binfmt:" > $d/register; }
	reg x86_64 '\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x3e\x00' \
		'\xff\xff\xff\xff\xff\xfe\xfe\x00\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff'
	reg i386 '\x7fELF\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x03\x00' \
		'\xff\xff\xff\xff\xff\xfe\xfe\x00\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff'
fi
/usr/lib/kw/welcome
/usr/lib/kw/net background

# Runs sysv-rc's rc for a runlevel change from $1 to $2, only when that
# level's directory has a script to run (a boot without services starts no
# shell for it): at boot a start link (a disabled service has K links in
# rc2.d), after DHCP is done (net wait, which says when it failed), at the
# end any.
rc() {
	echo "$1 $2" > /run/kw-runlevel
	local links="/etc/rc$2.d/[SK][0-9][0-9]*"
	[ "$1" != N ] || links="/etc/rc$2.d/S[0-9][0-9]*"
	compgen -G "$links" >/dev/null || return 0
	# No sysv-rc (a disk from before /etc/apt/preferences.d/kw-init, where a
	# package had apt replace it with systemd): no services, the boot goes on.
	[ -x /etc/init.d/rc ] || return 0
	[ "$1" != N ] || /usr/lib/kw/net wait
	RUNLEVEL=$2 PREVLEVEL=$1 /etc/init.d/rc "$2"
}
rc N 2

action=
trap 'action=poweroff' USR1
trap 'action=reboot' USR2
: > /run/kw-init
export HOME=/root
cd /root
declare -A role started
# The console's login shell (kwtty login: the user's, with its groups and
# environment, in its home) in a session of its own with hvc0 as its
# controlling terminal (job control, ^C), respawned like busybox init's
# "respawn".
console() { setsid -c /usr/bin/kwbox tty login <>/dev/hvc0 >&0 2>&0 & role[$!]=console; started[$!]=$SECONDS; }
# kwtty sleeps in pause() when there is no vsock device, so it is not
# respawned in a loop.
kwtty() { { /usr/lib/kw/net wait 2>/dev/null; exec /usr/bin/kwbox tty serve; } </dev/null & role[$!]=kwtty; started[$!]=$SECONDS; }
console
kwtty
# D-Bus's machine id, once per machine (the image has none, else every
# machine would share it): dbus-daemon's postinst makes it on a Debian
# system. A second later: made here at once, it delays the prompt by 15 ms
# (2026-11-25).
if [ -d /var/lib/dbus ] && [ ! -s /var/lib/dbus/machine-id ] && [ ! -s /etc/machine-id ]; then
	{ sleep 1; read -r id < /proc/sys/kernel/random/uuid && echo "${id//-/}" > /var/lib/dbus/machine-id; } </dev/null &
fi
while [ -z "$action" ]; do
	pid=
	# Returns for one of our children, or when a trapped signal arrives.
	# Orphans that end up here are reaped by bash itself.
	wait -n -p pid || true
	[ -n "$pid" ] && [ -n "${role[$pid]-}" ] || continue
	r=${role[$pid]}
	# Throttle a program that dies at once.
	[ $((SECONDS - started[$pid])) -ge 1 ] || sleep 1
	unset "role[$pid]" "started[$pid]"
	[ -n "$action" ] || $r
done

trap '' USR1 USR2
if [ "$action" = reboot ]; then rc 2 6; else rc 2 0; fi
exec 3>&2 2>/dev/null   # no "Killed" notices for the children
kill -TERM -1
sleep 0.2
kill -KILL -1
wait
/usr/lib/kw/shutdown 2>&3
exec /run/kw-lower/bin/busybox "$action" -f 2>&3
