#!/usr/bin/env bash

set -Eeuxo pipefail

echo "creating OCI compliant file.."

rootfs=$1
targetBase=$2
targetBaseDir=$(dirname "$targetBase")

# extract kernel image, cmdline and initramfs
cp "$rootfs/boot/"vmlinuz* "$targetBase.vmlinuz"
cp "$rootfs/boot/"initrd* "$targetBase.initrd"
read -r _ cmdline < "$rootfs/etc/kernel/cmdline" 

# get the actual root fs
# if it's the empty default (#) we need to rewrite that
root_source=$(tail -n 1 "$rootfs/etc/fstab" | cut -d " " -f 1)
if [ $root_source = "#" ]; then
  root_source="LABEL=ROOT"
fi

cmdline="root=$root_source $cmdline"

# onmetal
# neccessary binary has been placed into the build container
imageid=$(onmetal-image build --rootfs-file "$targetBaseDir/rootfs.raw" --kernel-file "$targetBase.vmlinuz" --initramfs-file "$targetBase.initrd" --command-line "$cmdline" --store-path "$targetBaseDir/onmetal" | tail -n1 | cut -d" " -f3)
onmetal-image list --store-path "$targetBaseDir/onmetal"

# a little cleanup
tar -C "$targetBaseDir" -cJf "/$targetBaseDir.oci.tar.xz" "onmetal/"
rm -rf "$targetBaseDir/onmetal"

