#!/bin/sh
set -e

name="bitpixie"
scriptpath="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
images="$scriptpath/images"

# Images are stored in the images/ folder, named like $name.2024123101.* where
# the last two digits are an increasing counter.

latest_image() {
    ls -1 "$images" | sort | tail -n 1 | rev | cut -d '.' -f 2- | rev
}

next_image() {
    current_date=$(date +%Y%m%d)
    counter=1
    while [ -e "$images/$name.${current_date}$(printf %02d $counter).initramfs" ]; do
        counter=$((counter + 1))
    done
    echo "$name.${current_date}$(printf %02d $counter)"
}

fixup_image() {
    current_date=$(date +%Y%m%d)
    counter=1
    while [ -e "$images/$name.${current_date}$(printf %02d $((counter + 1))).initramfs" ]; do
        counter=$((counter + 1))
    done
    echo "$name.${current_date}$(printf %02d $counter)"
}


mkdir -p "$images"

case "$1" in
    build)
        if [ "$2" = "--fixup" ]; then
            image=$(fixup_image)
        else
            image=$(next_image)
        fi
        echo "Building image $image"
        docker run --privileged --platform linux/amd64 --rm -v "${scriptpath}":/mnt -w /root \
            alpine:3.20.3 "/mnt/$name-build.sh" "/mnt/images/$image"
        ;;
    qemu)
        image=$(latest_image)
        echo "Running image $image in QEMU (terminate with Ctrl-A X," \
            "shutdown with Ctrl-A C system_powerdown)"
        # TODO do whole secure boot setup?
        qemu-system-x86_64 -m 4G -nographic \
             -kernel "$images/$image.kernel" \
             -initrd "$images/$image.initramfs" \
             -append "console=ttyS0"
        ;;
    deploy)
        image=$(latest_image)
        echo "Deploying image $image to $scriptpath/../../pxe/tftp"
        cp "$images/$image.kernel" "$scriptpath/../../pxe/tftp/linux"
        cp "$images/$image.initramfs" "$scriptpath/../../pxe/tftp/alpine-initrd.xz"
        ;;
    "")
        echo "Usage: $0 <subcommand>"
        echo
        echo "Subcommands:"
        echo "  build [ --fixup ] - Build the image"
        echo "  qemu              - Run the image in QEMU"
        echo "  deploy            - Deploy the image to the PXE directory"
        echo
        echo "Latest image: $(latest_image)"
        ;;
    *)
        echo "Error: Unknown subcommand '$1'"
        exit 1
        ;;
esac
