#!/bin/bash
set -e

# This script assumes you have a static BusyBox binary and a built Linux kernel (bzImage)
# located in the 'kernel/' directory.

echo "--- Creating Minimal Initramfs (cpio.gz) ---"

mkdir -p initramfs/bin initramfs/proc initramfs/sys initramfs/tmp

# Create the init script (as per instructions.txt)
echo "#!/bin/sh" > initramfs/init
echo "mount -t proc proc /proc" >> initramfs/init
echo "mount -t sysfs sys /sys" >> initramfs/init
echo "mount -t tmpfs tmpfs /tmp" >> initramfs/init
echo "echo \"Welcome to HDGL Lattice Minimal Shell!\"" >> initramfs/init
echo "exec /bin/busybox sh" >> initramfs/init

chmod +x initramfs/init

# Placeholder for BusyBox - REPLACE with your compiled static binary
if [ ! -f initramfs/bin/busybox ]; then
    echo "PLACEHOLDER: BusyBox is missing. Please place your static busybox binary at 'initramfs/bin/busybox'"
    touch initramfs/bin/busybox
fi

# Create the cpio archive
(cd initramfs && find . | cpio -H newc -o > ../initramfs.cpio)

# Compress the archive
gzip initramfs.cpio
mv initramfs.cpio.gz .

echo "Initramfs created: initramfs.cpio.gz"
echo "Please ensure 'kernel/bzImage' is a valid Linux kernel image."