#!/bin/sh
#
# Copyright (C) 2007-2009 Canonical, Ltd.
# Author: Jamie Strandboge <jamie@canonical.com>
# License: GPLv3
#
set -e

uqtconf="$HOME/.uqt-vm-tools.conf"
if [ -s "$uqtconf" ]; then
    . "$uqtconf"
else
    echo "Could not find '$uqtconf'"
    exit 1
fi

. $UQT_VM_TOOLS/libvm.sh
abort_if_root

network="network:default"	# network:default give libvirt integration
prefix="test-iso-"
start="1"
num="1"
iso=""
sparse_args="sparse=true"
if [ "$vm_iso_fully_allocate" = "yes" ]; then
    sparse_args="sparse=false"
fi

usage() {
    echo "vm-iso.sh <iso> -n name [<number>]"
    echo "vm-iso.sh <iso> [<number> [<start number>]]"
    exit 1
}

if [ -z "$1" ]; then
    usage
    exit 1
fi

iso="$1"
shift
if [ ! -s "$iso" ]; then
    echo "'$iso' doesn't exist"
    exit 1
fi

iters="1"
if [ "$1" = "-n" ]; then
    if [ -z "$2" ]; then
       usage
       exit 1
    fi
    prefix="$2"
    shift 2
    if [ -n "$1" ]; then
        num="$1"
        shift
        end=$((${start}+${num}-1))
        iters=`seq 1 $end`
    fi
elif [ ! -z "$1" ]; then
    num="$1"
    shift
    if [ ! -z "$1" ]; then
        start="$1"
        shift || true
    fi
    end=$((${start}+${num}-1))
    iters=`seq $start $end`
fi

num_disks=1
if [ ! -z "$vm_iso_ndisks" ]; then
    num_disks=$(($vm_iso_ndisks))
fi

echo "Create VM(s) with:"
echo "Memory: ${vm_memory} (Required: desktop >= 384, server/alternate >= 256)"
echo "VCPUs: ${vm_iso_vcpus}"
echo "Disks: ${num_disks}"
echo "Disk size (per disk): ${vm_root_size}"
echo -n "Fully allocate disk: "
if [ "$vm_iso_fully_allocate" = "yes" ]; then
    echo "yes"
else
    echo "no"
fi
echo "OS type: ${vm_iso_ostype}/${vm_iso_osvariant}"
echo -n "Continue (y/N)? "
read ans
if [ "$ans" != "y" ] && [ "$ans" != "Y" ]; then
    echo "Aborting"
    exit 0
fi

for i in ${iters} ; do
    name="${prefix}${i}"
    vmdir="${vm_path}/$name"
    mkdir $vmdir || {
        echo "Skipping '$name'. '$vmdir' exists"
        continue
    }

    disk_size=`echo "scale=2 ; ${vm_root_size} / 1024" | bc`
    disk_args=""
    if [ $num_disks -ge 1 ]; then
        for i in `seq 1 $num_disks` ; do
            disk_args="$disk_args --disk path=${vmdir}/disk${i}.img,size=$disk_size,$sparse_args"
        done
    fi

    virt-install --connect=${vm_connect} --name=$name --ram=${vm_memory} --vcpus=${vm_iso_vcpus} $disk_args --accelerate --hvm --cdrom=$iso --os-type=${vm_iso_ostype} --os-variant=${vm_iso_osvariant} --vnc --network=$network &
    if [ "$vm_iso_fully_allocate" = "yes" ]; then
	# wait until the VM comes up before proceeding since there is heavy
	# disk IO creating these disks and if we fire off 5 iso tests at once,
        # we feel great pain
        count=0
        while [ "$count" -lt 30 ]; do
            if vm_exists "$name" && vm_running "$name" ; then
                break
            fi
            count=$(( $count + 1 ))
            sleep 5
        done
    fi
    sleep 5
done
