[ -z "$exe_file" ] && die "Usage: $0 <MS .exe file>"

ie_ver=`echo $exe_file | perl -ne'/(IE\d)/ && print $1'`
if [ -e $exe_file ] ; then
	exe_file=`echo $exe_file | perl -MFile::Spec -e'print File::Spec->rel2abs(<>)'`
	[ -e $exe_file ] || die "Rel2Abs didn't work"

name="WinXP $ie_ver v2"

function die() {
	echo $@
	exit 1

echo "Woring on $exe_file ($ie_ver)"

# Find the vhd file
vhd_file=`unrar l $exe_file | perl -ne'/(\w[\s\w-]*\.vhd)/ && print $1'`
[ -z "$vhd_file" ] && die "Couldn't find the vhd file ($vhd_file)"
echo "Found vhd file: $vhd_file"

# Create the drive dir
echo "mkdir $vhd_dst"
[ -d $vhd_dst ] || mkdir $vhd_dst || die "Couldn't create $vhd_dst"
echo "vhd: $vhd"

# Unzip the disk image
echo "Changing to $vhd_dst"
cd $vhd_dst || die "Couldn't cd to $vhd_dst"

if [ -e "$vhd_file" ] ; then
	echo "VHD already extracted: $vhd_file"
	echo "Extracting..."
	nice unrar e "$exe_file" "$vhd_file" >> $log 2>&1 \
			|| die "Couldn't extract $vhd_file from $exe_file"
	echo "done"

vdi="`echo $vhd | sed -e 's/\.vhd$/.vdi/'`"
vmdk="`echo $vhd | sed -e 's/\.vhd$/.vmdk/'`"
raw="`echo $vhd | sed -e 's/\.vhd$/.raw/'`"

# Create the vbox vm
echo "--- Create vm"
VBoxManage createvm -name "$name" -register || die "Error creating vm"

# All the IE images have the same UUID so need to fix before registering
# This would be the easiest, but it doesn't work. Knows bug in VBox
# echo "--- Change uuid"
# VBoxManage internalcommands setvdiuuid "$vhd" || die "Error changing UUID"
# VBoxManage internalcommands sethduuid "$vhd" || die "Error changing UUID"

# Tried to clonevdi, but get the same UUID error, so convert->convert->convert
echo "--- Convert to raw"
nice qemu-img convert -O raw -f vpc "$vhd" "$raw" || die "Error converting to raw"
echo "--- Convert to vdi"
nice VBoxManage convertdd "$raw" "$vdi" || die "Error converting to vdi"

echo "--- Registerimage"
## VBoxManage registerimage disk "$vdi" || die "Error registering disk"
# could use "--type writethrough" then it reverts back each time rebooted

echo "--- Update vm"
VBoxManage modifyvm "$name" --ostype "WindowsXP" \
		--memory 192 --vram 8 --hwvirtex on --nic1 nat \
		--hda "$vdi" || die "Error modifying vm"

echo "--- Cleanup"
rm "$vhd" "$raw"

echo "---------"
echo "Remember to boot into safe mode F8 then in dos command:"
echo "  cd \WINDOWS\system32\drivers"
echo "  ren processr.sys processr.old"
echo "Once rebooted install vboxadditions then run"
echo "  D:\VBoxWindowsAdditions-x86.exe /extract /D=C:\Drivers"
echo "To avoid popups:"
echo "    * Start > Administrative Tools > Computer Management"
echo "    * Select Device Manager."
echo "    * Select Batteries, Unknown Device -> Disable"
echo "    * Select Network Adapters, Ethernet Controller -> Update Driver"
echo "    * Select Yes, now and every time, click Next"
echo "    * Select Install from a list or specific location, click Next"
echo "    * Enter location 'C:\Drivers\x86\Network\AMD'"
echo "    * Click Finish"