#!/bin/bash

set -e
set -x

shopt -s nullglob

IMG="$1"
DIR="$(mktemp -d)"
ROOT="${DIR}/squashfs"

if ldconfig -p | grep -q 'libeatmydata.so\s'; then
    export LD_PRELOAD="libeatmydata.so"
fi
export LC_ALL=C

cleanup() {
    for d in dev/pts sys proc dev; do
        mountpoint -q "${ROOT}/$d" && umount "${ROOT}/$d"
    done
    mountpoint -q "${DIR}/mnt" && umount "${DIR}/mnt"
    rm -rf "$DIR"
}
trap cleanup ERR

[ "$(id -u)" = 0 ]

mkdir -p "${DIR}/mnt" "${DIR}/image"

mount $([ -f "$IMG" ] && echo "-o loop") "$IMG" "${DIR}/mnt"
rsync -aP "${DIR}/mnt/" "${DIR}/image/"
umount "${DIR}/mnt"

NAME="$(isoinfo -d -i "$IMG" | sed -ne 's/^Volume id: //p')"

unsquashfs -d "${ROOT}" "${DIR}/image/casper/filesystem.squashfs"

cp /etc/resolv.conf "${ROOT}/etc"
cp /etc/hosts "${ROOT}/etc"

for d in dev proc sys dev/pts; do
    mount --bind "/$d" "${ROOT}/$d"
done

chroot "${ROOT}" dpkg-divert --local --rename --add /sbin/initctl
chroot "${ROOT}" ln -s /bin/true /sbin/initctl

sed -i -e 's/main/main universe/g' "${ROOT}/etc/apt/sources.list" "${ROOT}"/etc/apt/sources.list.d/*.list
chroot "${ROOT}" apt-get update || :
chroot "${ROOT}" apt-get install -y -f bootchart

mv "${ROOT}"/boot/initrd.img-* "${DIR}"/image/casper/initrd.*

chroot "${ROOT}" apt-get clean
rm "${ROOT}/etc/resolv.conf" "${ROOT}/etc/hosts" 
rm "${ROOT}/sbin/initctl"
chroot "${ROOT}" dpkg-divert --rename --remove /sbin/initctl

chroot "${ROOT}" dpkg-query -W --showformat='${Package} ${Version}\n' > "${DIR}/image/casper/filesystem.manifest"
grep -F -v -e 'ubiquity' -e 'casper' "${DIR}/image/casper/filesystem.manifest" > "${DIR}/image/casper/filesystem.manifest-desktop"

for d in dev/pts sys proc dev; do
    umount "${ROOT}/$d"
done

rm "${DIR}/image/casper/filesystem.squashfs"
mksquashfs "${ROOT}" "${DIR}/image/casper/filesystem.squashfs"
printf $(du -sx --block-size=1 "${ROOT}" | cut -f1) > "${DIR}/image/casper/filesystem.size"
(cd "${DIR}/image" && find -type f -print0 | xargs -0 md5sum | grep -F -v 'isolinux/boot.cat' >"${DIR}/md5sum.txt")

mkisofs -D -r -V "bootchart ${NAME:0:22}" -cache-inodes -J -l -b isolinux/isolinux.bin -c isolinux/boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table -o "${IMG%.iso}.bootchart.iso" "${DIR}/image"
