#!/bin/bash

if [ ! $# == 1 ]; then
	echo "ERR: $0 amd64|i386"
	exit 1
fi

if [ $USER != 'root' ]; then
	echo "ERR: $0 must be launched as root"
	exit 1
fi

ARCH=$1
ISO=debian-7.7.0-$ARCH-netinst.iso
INITRD=install.amd/initrd.gz

if [ ! -r $ISO ]; then
	echo "ERR: missing iso $ISO"
	exit 1
fi

# force clean...
umount loop-$ARCH 2> /dev/null || true
rmdir loop-$ARCH 2> /dev/null || true
rm -rf cd-$ARCH 2> /dev/null || true
rm -rf initrd-$ARCH 2> /dev/null || true

echo "extract iso $ISO to cd-$ARCH"
mkdir loop-$ARCH
mount -o ro,loop $ISO loop-$ARCH
mkdir cd-$ARCH
rsync -a -H --exclude=TRANS.TBL loop-$ARCH/ cd-$ARCH
umount loop-$ARCH
rmdir loop-$ARCH

echo "extract cd-$ARCH/$INITRD to initrd-$ARCH"
mkdir initrd-$ARCH || true
cd initrd-$ARCH
gzip -dc ../cd-$ARCH/$INITRD | cpio -id
echo "override initrd-$ARCH with initrd-override-$ARCH"
rsync -a ../initrd-override-$ARCH/* .
echo "create new cd-$ARCH/$INITRD from initrd-$ARCH"
find . | cpio -H newc --create | gzip -9 > ../cd-$ARCH/$INITRD
cd ..

echo "override cd-$ARCH with cd-$ARCH-override"
rsync -a cd-override-$ARCH/* cd-$ARCH/

echo "generate new cd-$ARCH/md5sum.txt"
cd cd-$ARCH/
md5sum `find -follow -type f 2> /dev/null` > md5sum.txt
cd ..

NEWISO=`basename $ISO .iso`-`date +%Y%m%dT%H%M%S`.iso
echo "create iso $NEWISO from cd-$ARCH"
genisoimage -quiet -o $NEWISO \
	-r -J -no-emul-boot -boot-load-size 4 -boot-info-table \
	-b isolinux/isolinux.bin -c isolinux/boot.cat ./cd-$ARCH

SUPANNISO=`basename $ISO .iso`-supann.iso
ln -sf $NEWISO $SUPANNISO
echo "linked to $SUPANNISO"
