#!/bin/bash

function deploy() {
	find /etc/init.d -type f | while read f; do
		SZ=`stat "$f" | grep Size | awk -F " " '{print $2}'`
		DIR=`dirname "$f"`
		sudo mkdir -p /mnt/$DIR > /dev/null 2>&1
		sudo dd if=/dev/zero of=/mnt/$f bs=$SZ count=1 > /dev/null 2> /dev/null
	done
}

# Check arguments
if [ -z "$1" ]; then
	echo "Specify the type of mutation to perform."
	exit 1
fi

# Clean things out
rm -rf ext2.0.img ext2.1.img

# Create ext2 filesystem
dd if=/dev/zero of=ext2.0.img bs=1024k count=32
mkfs.ext2 -F ext2.0.img

# Load up filesystem
cp ext2.0.img ext2.1.img
sudo mount ext2.1.img /mnt -o loop
deploy
sudo umount /mnt

# Compute differences
./bddiff 512 ext2.0.img ext2.1.img > ext2.1.diff
LOOP=1

# Now start mutating
echo -en "Mutation loop=$LOOP "
while true; do
	rm -rf ext2.$((LOOP + 1)).img
	cp ext2.$LOOP.img ext2.$((LOOP + 1)).img
	./bdmutate 512 ext2.$((LOOP + 1)).img 0.2 $* < ext2.$LOOP.diff
	# do we really want to fsck?
	#fsck.ext2 -f -y ext2.$((LOOP + 1)).img
	RES=0  #$?
	# modify fs
	if [ $RES -eq 0 ]; then
		sudo mount ext2.$((LOOP + 1)).img /mnt -o loop
		RES=$?
		if [ $RES -eq 0 ]; then
			deploy
			sudo umount /mnt
		else
			fsck.ext2 -f -y ext2.$((LOOP + 1)).img
			RES=$?
			if [ $RES -eq 4 ]; then
				fsck.ext2 -f -y ext2.$((LOOP + 1)).img -b 8193
				RES=$?
				if [ $RES -eq 4 ]; then
					echo 'Dead fs, exiting....'
					read f
				fi
			fi
		fi
	fi
	./bddiff 512 ext2.$LOOP.img ext2.$((LOOP + 1)).img > ext2.$((LOOP + 1)).diff

	LOOP=$((LOOP + 1))
	echo -en "Mutation loop=$LOOP "
done	

exit 0
