#!/bin/sh
# PID 1, from the initramfs. With sosie.lower=DEV it builds / from two layers and
# moves into it; without, Linux runs from the initramfs itself.
#   sosie.lower=DEV  the read-only system disk (tools/mkrootfs.py, SquashFS)
#   sosie.upper=DEV  the ext4 disk that keeps every change; without it, changes
#                    go to memory and are lost: also the safe mode
/bin/busybox --install -s
mount -t proc proc /proc
mount -t sysfs sysfs /sys
mount -t devtmpfs devtmpfs /dev 2>/dev/null
# the names most programs expect for their open files
ln -sf /proc/self/fd /dev/fd
ln -sf /proc/self/fd/0 /dev/stdin
ln -sf /proc/self/fd/1 /dev/stdout
ln -sf /proc/self/fd/2 /dev/stderr
# pseudo-terminals, for a remote shell
mkdir -p /dev/pts && mount -t devpts devpts /dev/pts
export PATH=/bin:/sbin:/usr/bin:/usr/sbin HOME=/root

arg() { sed -n "s/.*sosie\.$1=\([^ ]*\).*/\1/p" /proc/cmdline; }
lower=$(arg lower)
upper=$(arg upper)

# an address on the network the host plugged in: 10.0.0.N from sosie.host=N.
# Done here, not on the system disk, so that saved disks with an older system
# have it too.
host=$(arg host | sed 's/^0*//')
if [ -n "$host" ] && [ -e /sys/class/net/eth0 ]; then
	if ip link set lo up && ip addr add "10.0.0.$host/24" dev eth0 && ip link set eth0 up; then
		echo "Network: this machine is 10.0.0.$host."
		hostname "sosie$host"
	else
		echo "WARNING: the network did not come up."
	fi
fi

# a shell in the initramfs, for when / cannot be built
rescue() {
	echo "sosie: $1. This is a rescue shell: nothing here is saved."
	cd /root
	setsid cttyhack sh
	poweroff -f
}

if [ -n "$lower" ]; then
	mkdir -p /lower /rw /newroot
	mount -t squashfs -o ro "$lower" /lower || rescue "the system disk did not mount"
	kept=
	if [ -n "$upper" ]; then
		if mount -t ext4 -o commit=1 "$upper" /rw; then kept=1
		else echo "WARNING: the saved disk did not mount. It was not changed."; fi
	fi
	[ -n "$kept" ] || mount -t tmpfs tmpfs /rw || rescue "no room for changes"
	# the two directories overlayfs needs, side by side on the writable disk
	mkdir -p /rw/upper /rw/work || rescue "the writable layer is unusable"
	mount -t overlay overlay -o lowerdir=/lower,upperdir=/rw/upper,workdir=/rw/work /newroot || rescue "the two layers did not combine"
	if [ -n "$kept" ]; then state=saved; else state=memory; fi
	mount --move /proc /newroot/proc && mount --move /sys /newroot/sys && mount --move /dev /newroot/dev || rescue "could not move into /"
	export SOSIE_ROOT=$state
	exec switch_root /newroot /sbin/sosie-init
fi

echo
echo "Welcome to Linux on sosie."
cd /root
# a controlling terminal, so job control and Ctrl-C work
setsid cttyhack sh
poweroff -f
