#! /bin/bash

set -e
export LC_ALL=C

# http://cdimage.debian.org/cdimage/weekly-builds/amd64/jigdo-dvd/debian-testing-amd64-DVD-1.jigdo
# http://cdimage.debian.org/cdimage/weekly-builds/amd64/jigdo-dvd/debian-testing-amd64-DVD-1.template
# http://cdimage.debian.org/cdimage/unofficial/non-free/firmware/jessie/current/firmware.tar.gz

for p in isohybrid genisoimage curl
do
    command -v "$p" > /dev/null || {
	echo "$0: command $p not found" >&2
	exit 2
    }
done

iso="${1?iso file}"


if [[ -d target ]]; then
    echo "skipping: unpack iso"
else
    mkdir -p target
    bsdtar xf "$iso" -C target/
    chmod -R u+w target
fi

if [[ $(find target/firmware -type f | wc -l) -gt 1 ]]; then
    echo "skipping: firmware unpack"
else
    tar xf firmware.tar.gz -C target/firmware
fi

if grep -q 'ius.cfg' target/isolinux/menu.cfg; then
    echo "skipping: isolinux"
else
    cp -v ~heiko/d/preseed/isolinux/ius.cfg target/isolinux/
    perl -i.bak -pe 's/^include stdmenu.cfg\Z/${&}\ninclude ius.cfg/' \
		 target/isolinux/menu.cfg 
fi


if [[ -f target.iso ]]; then
	echo "skipping: geniso"
else
    volid=$(isoinfo -d -i ${iso} | grep '^Volume id:' | cut -f3- -d' ')
    genisoimage -o target.iso -V "$volid" \
	-r -J \
	-no-emul-boot -boot-load-size 4 -boot-info-table \
	-b isolinux/isolinux.bin \
	-c isolinux/isolinux.cat \
	./target
    isohybrid target.iso
fi
