#!/bin/bash
# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
# Adapted for the Ubuntu 26.04 + ROS 2 Lyrical image of unkernel-ros2 from
# unkernel's guest/distro/debian/rootfs/usr/local/sbin/kw-init (release
# v0.3.0-261202-b033dc7), modified 2026-12-03. Changes: no sysv-rc runlevels (the Docker-derived
# root has no services), no box64 binfmt, and a fallback mount of /dev/shm
# (Fast DDS's shared-memory transport needs it). The base (b033dc7) already
# mounts /dev/shm, so the fallback has not run in testing.
#
# PID 1 of the image. The base execs /usr/local/sbin/kw-init first. The kw
# layer's runtime (/usr/lib/kw/, from the base) does the rest: rc (mounts,
# hostname), welcome, net (DHCP, in the background), and at the end, after
# this has stopped every process, shutdown (leave /data clean). In between
# it respawns the console's login shell on hvc0 (kwtty login) and kwtty
# serve, until poweroff, halt or reboot (/usr/local/sbin) signal it
# (SIGUSR1, SIGUSR2); then reboot(2) through the base's busybox.

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
# POSIX shared memory (shm_open) for DDS, if the base did not mount it.
if ! mountpoint -q /dev/shm 2>/dev/null; then
	mkdir -p /dev/shm
	mount -t tmpfs -o mode=1777,nosuid,nodev shm /dev/shm
fi
/usr/lib/kw/welcome
/usr/lib/kw/net background

action=
trap 'action=poweroff' USR1
trap 'action=reboot' USR2
: > /run/kw-init
export HOME=/root
cd /root
declare -A role started
console() { setsid -c /usr/bin/kwbox tty login <>/dev/hvc0 >&0 2>&0 & role[$!]=console; started[$!]=$SECONDS; }
kwtty() { { /usr/lib/kw/net wait 2>/dev/null; exec /usr/bin/kwbox tty serve; } </dev/null & role[$!]=kwtty; started[$!]=$SECONDS; }
console
kwtty
if [ ! -s /etc/machine-id ]; then
	{ sleep 1; read -r id < /proc/sys/kernel/random/uuid && echo "${id//-/}" > /etc/machine-id; } </dev/null &
fi
while [ -z "$action" ]; do
	pid=
	wait -n -p pid || true
	[ -n "$pid" ] && [ -n "${role[$pid]-}" ] || continue
	r=${role[$pid]}
	[ $((SECONDS - started[$pid])) -ge 1 ] || sleep 1
	unset "role[$pid]" "started[$pid]"
	[ -n "$action" ] || $r
done

trap '' USR1 USR2
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
