#!/bin/bash

SCRIPT=$(realpath ${BASH_SOURCE})
IMAGES=$(realpath $(dirname ${SCRIPT})/../build/images/)

image_file() {
    local fname=$(readlink -f ${IMAGES}/${1})
    if [[ ! -f ${fname} ]]; then
        >&2 printf "File ${fname} does not exist\n"
        exit 1
    fi
    printf $fname
}


EFIBOOT=$(image_file systemd-bootx64.efi)
KERNEL=$(image_file bzImage)
ROOTFS=$(image_file citadel-image-intel-corei7-64.ext2)
APPIMG_ROOTFS=$(image_file ../appimg/appimg-rootfs.tar.xz)
HOWTO=$(image_file ../../docs/howto.md)
INSTALL_SH=$(image_file ../../scripts/install.sh)

KERNEL_CMDLINE="add_efi_memmap intel_iommu=off cryptomgr.notests rcupdate.rcu_expedited=1 rcu_nocbs=0-64 tsc=reliable no_timer_check noreplace-smp i915.fastboot=1 quiet splash"

INSTALLPACK=/tmp/installpack
BOOTPATH=${INSTALLPACK}/boot

make_loader_conf() {
    echo "default bootA"
    echo "timeout 5"
}

make_boot_conf() {
    echo "title Subgraph OS (Citadel) [Root Partition ${1}]"
    echo "linux /bzImage"
    echo "options LABEL=Boot root=/dev/mapper/citadel-rootfs${1} ${KERNEL_CMDLINE}"
}

setup_boot() {
    mkdir -p ${BOOTPATH}/EFI/BOOT
    mkdir -p ${BOOTPATH}/loader/entries
    cp ${EFIBOOT} ${BOOTPATH}/EFI/BOOT/bootx64.efi
    cp ${KERNEL} ${BOOTPATH}/bzImage
    make_loader_conf > ${BOOTPATH}/loader/loader.conf
    make_boot_conf 'A' > ${BOOTPATH}/loader/entries/bootA.conf
    make_boot_conf 'B' > ${BOOTPATH}/loader/entries/bootB.conf
}


rm -rf /tmp/installpack
mkdir -p /tmp/installpack/components
setup_boot
cp ${ROOTFS} /tmp/installpack/components/citadel-image-rootfs.ext2
cp ${APPIMG_ROOTFS} /tmp/installpack/components/
cp ${HOWTO} /tmp/installpack/components/
cp ${INSTALL_SH} /tmp/installpack
chmod +x /tmp/installpack/install.sh

tar -C /tmp -cvf installpack.tar installpack