#!/bin/sh
set -e
# this depends on vboot-kernel-utils and u-boot-utils
if [ ! -z "$1" ]; then cd $1; fi
VMLINUZ=arch/arm/boot/zImage
if [ ! -f $VMLINUZ ]; then
    echo $PWD/$VMLINUZ not found
    exit 1
fi
DTB=arch/arm/boot/dts/tegra124-nyan-big.dtb
if [ ! -f $DTB ]; then
    echo $PWD/$DTB not found
    exit 1
fi
HDD=/dev/mmcblk0
KERNEL_PARTITIONS="2 4"
TEST_PARTITION=
# search for kernel partition with lowest priority, this
# is where we put our new kernel
for PARTITION in $KERNEL_PARTITIONS; do
    CURRENT=$(sudo cgpt show -i $PARTITION -P $HDD)
    if [ -z $CURRENT ]; then
        # cgpt will have errored
        exit 1
    fi
    if [ $CURRENT -eq 0 ]; then
	TEST_PARTITION=$PARTITION
    fi
done
TEST_PARTITION_FILE=${HDD}p$TEST_PARTITION
if [ -z "$TEST_PARTITION" ] || [ ! -b $TEST_PARTITION_FILE ]; then
    echo No partition for testing kernel found
    echo Mark one as test by saying cgpt add -i NUMBER -P0 -T0
    exit 1
fi
echo using $TEST_PARTITION_FILE
KERNEL=$(mktemp)
FIT=$(mktemp)
cat > $FIT <<HEREDOC
/dts-v1/;
/ {
    description = "Chrome OS";
    images {
        kernel@1 {
            description = "kernel";
	    data = /incbin/("$PWD/$VMLINUZ");
            type = "kernel_noload";
            arch = "arm";
            os = "linux";
            compression = "none";
            load = <0>;
            entry = <0>;
        };
        fdt@1 {
            description = "nyan_big";
	    data = /incbin/("$PWD/$DTB");
            type = "flat_dt";
            arch = "arm";
            compression = "none";
            hash@1 {
                algo = "sha1";
	    };
        };
    };
    configurations {
        default = "conf@1";
        conf@1 {
            kernel = "kernel@1";
            fdt = "fdt@1";
        };
    };
};
HEREDOC
mkimage -f $FIT $KERNEL
CONFIG=$(mktemp)
cat /proc/cmdline > $CONFIG
BOOTLOADER=$(mktemp)
echo > $BOOTLOADER
sudo vbutil_kernel --pack $TEST_PARTITION_FILE --keyblock=/usr/share/vboot/devkeys/kernel.keyblock --signprivate=/usr/share/vboot/devkeys/kernel_data_key.vbprivk --version=1 --vmlinuz=$KERNEL --bootloader=$BOOTLOADER --config=$CONFIG --arch=arm
sudo cgpt add -i $TEST_PARTITION -P10 -T1 -S0 $HDD
