#!/bin/busybox sh
# License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
#
# /init of the Makronix Mobile initramfs: bring up the USB network, find the
# root file system by UUID, hand over to its /sbin/init.  Run by the static
# busybox of the base (tools/mkinitramfs.sh); POSIX sh, busybox applets only.
#
# Kernel arguments read here:
#   root=UUID=<uuid>   the root file system (tools/mkbootimg.sh, ROOT_UUID)
#   makronix.debug     stop before switch_root and serve a shell
#
# Two layouts are understood on the partition, decided by /system/current
# (docs/NEXT.md, task B; measured on the host 2026-11-09, see
# devices/hotdogb/AGENTS.md):
#
#   new  the partition holds /system/current (the system, tools/mkrootimg.sh)
#        and /data (the state that survives updates).  / is a bind of
#        /system/current; /home, /root and /var/lib are binds of /data/...;
#        /etc is an overlay, so changes persist while the system's defaults
#        stay visible.  /data and /system are bound in as well; the partition
#        itself has no path after switch_root (every path in the new root is
#        inside it), and does not need one: the overlay holds the upper
#        directory, the binds hold the file system.
#   old  the partition IS the root: mounted read-only at / and left to the
#        root's stage 1 to check and remount (images before 2026-11-09).
#
# The kernel has everything built in that this needs (UFS, sd, DWC3, NCM,
# configfs, ext4): no modules are loaded here.  On any failure the init does
# not halt: it serves a root shell with telnetd on USB_IP and waits.

/bin/busybox --install -s /bin
export PATH=/bin

USB_IP=172.16.42.1
HOST_IP=172.16.42.2
CONFIGFS=/sys/kernel/config/usb_gadget

log() {
	echo "makronix-rd: $*" > /dev/kmsg
}

rescue() {
	log "$* -- shell: telnet $USB_IP"
	mkdir -p /dev/pts
	mountpoint -q /dev/pts || mount -t devpts devpts /dev/pts
	telnetd -l /bin/sh -b "$USB_IP"
	while :; do sleep 3600; done
}

mkdir -p /proc /sys /dev /run /sysroot /sysroot.real /etc
mount -t proc proc /proc
mount -t sysfs sysfs /sys
mount -t devtmpfs devtmpfs /dev
mount -t tmpfs -o mode=0755,nosuid,nodev tmpfs /run
mount -t configfs configfs /sys/kernel/config

root= debug=
for a in $(cat /proc/cmdline); do
	case $a in
	root=UUID=*)	root=${a#root=UUID=} ;;
	makronix.debug)	debug=1 ;;
	esac
done
log "start, root UUID=$root"

# USB: one gadget (g1) with the network (NCM, as the pmOS initramfs set it
# up, the same addresses) and a serial port (ACM: /dev/ttyACM0 on the host,
# ttyGS0 here, console=ttyGS0 and a getty in the root).  Both from the start,
# so the root does not have to rebind the gadget to add the serial port
# (its 01-acm-console.sh then has nothing to do), and the host keeps its
# address and the netconsole its link.
usb_up() {
	i=0
	while [ -z "$(ls /sys/class/udc 2>/dev/null)" ]; do
		i=$((i + 1)); [ $i -le 100 ] || { log "no UDC"; return 1; }
		sleep 0.1
	done
	g=$CONFIGFS/g1
	mkdir -p "$g/strings/0x409" "$g/functions/ncm.usb0" "$g/functions/acm.GS0" \
		"$g/configs/c.1/strings/0x409"
	echo 0x18D1 > "$g/idVendor"
	echo 0xD001 > "$g/idProduct"
	echo Makronix > "$g/strings/0x409/manufacturer"
	echo Makronix > "$g/strings/0x409/serialnumber"
	echo "Makronix Mobile" > "$g/strings/0x409/product"
	echo "USB network and serial" > "$g/configs/c.1/strings/0x409/configuration"
	ln -s "$g/functions/ncm.usb0" "$g/configs/c.1/"
	ln -s "$g/functions/acm.GS0" "$g/configs/c.1/"
	ls /sys/class/udc | head -n 1 > "$g/UDC"
	ifname=$(cat "$g/functions/ncm.usb0/ifname")
	ifconfig "$ifname" "$USB_IP" netmask 255.255.255.0 up
	# one lease, ten days: the host keeps its address after the handover,
	# when the root's NetworkManager holds USB_IP statically
	cat > /etc/udhcpd.conf <<EOF
start $HOST_IP
end $HOST_IP
max_leases 1
interface $ifname
lease_file /run/udhcpd.leases
option subnet 255.255.255.0
option lease 864000
EOF
	udhcpd /etc/udhcpd.conf
	log "usb network up: $ifname $USB_IP"
}
usb_up || rescue "usb network failed"

[ -n "$root" ] || rescue "no root=UUID= on the command line"
i=0
while :; do
	dev=$(findfs "UUID=$root" 2>/dev/null) && break
	i=$((i + 1)); [ $i -le 300 ] || rescue "root UUID=$root not found"
	sleep 0.1
done
log "root is $dev"

# New layout (see the top): /system/current is the system, /data the state
# that survives updates.  The first boot creates /data and takes the system's
# /var/lib and /root over once, so the machine id, the bluetooth pairings and
# root's keys are not new on every update.
mount_new_layout() {
	mount -o remount,rw /sysroot.real || rescue "cannot remount $dev read-write"
	if [ ! -d /sysroot.real/data ]; then
		log "first boot: creating /data"
		mkdir -p /sysroot.real/data/home /sysroot.real/data/root \
			/sysroot.real/data/var/lib /sysroot.real/data/etc/upper \
			/sysroot.real/data/etc/work || rescue "cannot create /data"
		cp -a /sysroot.real/system/current/var/lib/. \
			/sysroot.real/data/var/lib/ || rescue "cannot copy /var/lib to /data"
		cp -a /sysroot.real/system/current/root/. \
			/sysroot.real/data/root/ || rescue "cannot copy /root to /data"
	fi
	mkdir -p /sysroot.real/data/home /sysroot.real/data/root \
		/sysroot.real/data/var/lib /sysroot.real/data/etc/upper \
		/sysroot.real/data/etc/work || rescue "cannot create /data"

	mount --bind /sysroot.real/system/current /sysroot ||
		rescue "cannot bind /system/current"
	mkdir -p /sysroot/home /sysroot/root /sysroot/var/lib /sysroot/data \
		/sysroot/system
	mount --bind /sysroot.real/data/home /sysroot/home ||
		rescue "cannot bind /data/home"
	mount --bind /sysroot.real/data/root /sysroot/root ||
		rescue "cannot bind /data/root"
	mount --bind /sysroot.real/data/var/lib /sysroot/var/lib ||
		rescue "cannot bind /data/var/lib"
	mount --bind /sysroot.real/data /sysroot/data || rescue "cannot bind /data"
	mount --bind /sysroot.real/system /sysroot/system ||
		rescue "cannot bind /system"
	# /etc as an overlay: a changed file stays changed, everything else comes
	# fresh from the system at every update (docs/NEXT.md, why not a bind)
	mount -t overlay overlay \
		-o lowerdir=/sysroot/etc,upperdir=/sysroot.real/data/etc/upper,workdir=/sysroot.real/data/etc/work \
		/sysroot/etc || rescue "cannot overlay /etc"
	# The partition itself stays mounted at /sysroot.real.  It cannot be moved
	# into the new root (every path there is inside it: the bind of
	# /system/current makes that so, measured 2026-11-09), and unmounting it
	# would be a detach whose propagation is not ours to rely on.  The overlay
	# and the binds hold it; it has no path after switch_root, and /data and
	# /system are what the system uses.
	log "layout: /system/current, /data, /etc as an overlay"
}

# read-only first: an old image is run exactly as before, and the root's init
# checks the file system and remounts it; a new one is made read-write above
# (its /data must be writable)
mount -o ro "$dev" /sysroot.real || rescue "cannot mount $dev"
if [ -d /sysroot.real/system/current ]; then
	mount_new_layout
else
	log "layout: whole partition (image without /system/current)"
	mount --move /sysroot.real /sysroot || rescue "cannot move $dev to /sysroot"
fi
# -L too: Debian's /sbin/init is an absolute link, resolved only after switch_root
[ -x /sysroot/sbin/init ] || [ -L /sysroot/sbin/init ] || rescue "no /sbin/init on $dev"
[ -z "$debug" ] || rescue "makronix.debug: stopped before switch_root"

log "switch_root to /sbin/init"
killall udhcpd 2>/dev/null
for m in /dev /proc /sys /run; do
	mount --move "$m" "/sysroot$m" || rescue "cannot move $m"
done
exec switch_root /sysroot /sbin/init
