#!/bin/bash

# Build the iso.
# Some parts of this (particularly the xorriso command lines) come from
# the ubuntu-cdimage project:
#   http://bazaar.launchpad.net/~ubuntu-cdimage/debian-cd/ubuntu/

# make sure this was run as root
if [ $UID -ne 0 ] ; then
    echo "Need to be root; trying sudo"
    exec sudo env BUILD_CONFIG=$BUILD_CONFIG $0 "$@"
fi
. config || exit 0

set -x
set -e

INITRD=${FS}/initrd.img
VMLINUZ=$(readlink -f ${FS}/vmlinuz)
VMLINUZ_EFI=${VMLINUZ}.efi.signed

if ! [ "$1" == "justiso" ] ; then


    if ! [ -r ${INITRD} -a -r ${VMLINUZ} -a -r ${VMLINUZ_EFI} ] ; then
        set +x
        echo "== Missing kernel and/or initrd.  Either upgrade or reinstall"
        echo "== the kernel inside the image to get the right files."
        exit 1
    fi

    # Recompress initrd if changed
    if [ ${INITRD} -nt ${ISO}/casper/initrd.lz ] ; then
        sh -c "zcat ${INITRD} | lzma > ${ISO}/casper/initrd.lz"
    fi
    # Get kernel and signed EFI kernel
    cp ${VMLINUZ} ${ISO}/casper/vmlinuz
    cp ${VMLINUZ_EFI} ${ISO}/casper/vmlinuz.efi

    # manifests
    chmod +w ${ISO}/casper/filesystem.manifest
    chroot ${FS} dpkg-query -W --showformat='${Package} ${Version}\n' \
        | tee ${ISO}/casper/filesystem.manifest >/dev/null

    # squashfs
    rm -f ${ISO}/casper/filesystem.squashfs
    mksquashfs ${FS} ${ISO}/casper/filesystem.squashfs
    printf $(du -sx --block-size=1 ${FS} | cut -f1) \
        | tee ${ISO}/casper/filesystem.size

fi

# md5sums
rm -f md5sum.txt
find ${ISO} -type f -print0 \
    | xargs -0 md5sum \
    | sed -e "s, ${ISO}, .," \
    | grep -v isolinux/boot.cat \
    | grep -v isolinux/isolinux.bin \
    | grep -v md5sum.txt \
    | tee ${ISO}/md5sum.txt >/dev/null

chown -R ${NONPRIV_UID} ${ISO}

# build CD
xorriso -as mkisofs \
    -joliet -full-iso9660-filenames \
    -rational-rock \
    -V "NILMbuntu ${VERSION}" \
    -input-charset utf-8 -output ${OUTPUT} \
    -b isolinux/isolinux.bin -c isolinux/boot.cat -no-emul-boot \
    -boot-load-size 4 -boot-info-table \
    -eltorito-alt-boot -e boot/grub/efi.img -no-emul-boot \
    -isohybrid-mbr /usr/lib/ISOLINUX/isohdpfx.bin \
    -isohybrid-gpt-basdat -isohybrid-apm-hfsplus \
    ${ISO}

set +x
echo "Burn it with:"
echo "  growisofs -dvd-compat -Z /dev/dvd=${OUTPUT}"
echo "or write directly to a USB key"