#/bin/sh

need() { which $1 > /dev/null || tazpkg get-install ${2:-$1}; }

[ -s slitaz-4.0.iso ] || wget http://mirror.slitaz.org/iso/4.0/slitaz-4.0.iso
mount -o loop,ro slitaz-4.0.iso /media/cdrom
dd of=hdsubroot bs=1024k seek=200 count=0 2> /dev/null # sparse file
if [ -n "$1" ]; then
	need mkdosfs dosfstools
	mkdosfs hdsubroot
else
	echo y | mke2fs hdsubroot
fi
mount -o loop hdsubroot /media/usbdisk
mkdir -p /media/usbdisk/slitaz/boot
if [ -n "$1" ]; then
	need mount.posixovl posixovl
	mount.posixovl /media/usbdisk/slitaz
fi
for i in $(ls -r /media/cdrom/boot/rootfs*); do
	unlzma -c $i | ( cd /media/usbdisk/slitaz ; cpio -idmu )
done
cp /media/cdrom/boot/rootfs4.gz /media/usbdisk/slitaz/boot/rootfs.gz
cp /media/cdrom/boot/bzImage /media/usbdisk/slitaz/boot/
umount -d /media/cdrom
cat > /media/usbdisk/syslinux.cfg <<EOT
default slitaz
label slitaz
	kernel /slitaz/boot/bzImage
	initrd /slitaz/boot/rootfs.gz
	append rw root=/dev/null lang=fr_FR kmap=fr-latin1 mount=/dev/hda subroot=slitaz posixovl
EOT
if [ -n "$1" ]; then
	umount /media/usbdisk/slitaz
	sync
	syslinux $(losetup | grep hdsubroot | cut -d: -f1)
else
	sed -i 's/ posixovl//' /media/usbdisk/syslinux.cfg
	mv /media/usbdisk/syslinux.cfg /media/usbdisk/slitaz/boot/extlinux.conf
	extlinux --install /media/usbdisk/slitaz/boot
fi
umount -d /media/usbdisk
need qemu
qemu -k fr -hda hdsubroot
