#!/bin/sh
# DF-5667: build /vkroot.img — minimal vkernel root (adapted from the
# DF-5655 rig). Differences vs DF-5655:
#   - no TLS-trigger binaries (not needed here)
#   - vkinit mounts devfs so /dev/kmem + /dev/console exist inside the vkernel
set -e
cd /tmp

dd if=/dev/zero of=/vkroot.img bs=1m count=1200
vnconfig -c /dev/vn0 /vkroot.img
newfs /dev/vn0
mount /dev/vn0 /mnt
mkdir -p /mnt/bin /mnt/sbin /mnt/lib /mnt/libexec /mnt/root /mnt/etc /mnt/dev /mnt/tmp /mnt/var /mnt/usr/bin
for f in sh cat ls echo cp mv rm mkdir chmod dd kill ps test sleep stty uname hostname hexdump; do
  cp /bin/$f /mnt/bin/ 2>/dev/null || true
done
cp "/bin/[" /mnt/bin/ 2>/dev/null || true
for f in mount umount sysctl reboot devfs; do cp /sbin/$f /mnt/sbin/ 2>/dev/null || true; done
# DF keeps these in /usr/bin, not /bin
mkdir -p /mnt/usr/bin
for f in grep head tail hexdump od; do cp /usr/bin/$f /mnt/usr/bin/ 2>/dev/null || true; done
cp -p /lib/*.so* /mnt/lib/
cp -p /libexec/ld-elf.so.2 /mnt/libexec/
chmod 1777 /mnt/tmp

cat > /tmp/vkinit.c <<'CEOF'
#include <fcntl.h>
#include <unistd.h>
#include <sys/mount.h>
int main(void) {
	int fd = open("/dev/console", O_RDWR);
	if (fd >= 0) { dup2(fd,0); dup2(fd,1); dup2(fd,2); if (fd>2) close(fd); }
	if (mount("devfs", "/dev", 0, NULL) != 0) {
		static const char m[] = "vkinit: devfs mount failed\n";
		if (write(2, m, sizeof(m)-1)) {}
	}
	execl("/bin/sh", "sh", (char *)NULL);
	return 1;
}
CEOF
cc -static -O -o /mnt/bin/vkinit /tmp/vkinit.c

umount /mnt
vnconfig -u vn0
echo "IMAGE DONE"
