#!/bin/bash

usage() {
cat << EOF
usage: $0 options 

OPTIONS:
  --name VM name
  --targetDir directory where the VM disk(s) will be created
  --memoryMB  memory size of the VM in MBytes
  --ncpu    number of VCPUs of the VM
  --net customization option for network interface: Iface / mode / ip / netmask / gateway
  --hostname customization option : new hostname of the guest OS
EOF
}

name=
targetDir=
memoryMB=
ncpu=
customOptions=

while [[ $1 = -* ]]; do
	case "$1" in
     		--name)
      		name="$2"
      		shift 2
		;;

     		--targetDir)
      		targetDir="$2"
      		shift 2
		;;

     		--memoryMB)
      		memoryMB="$2"
      		shift 2
		;;

     		--ncpu)
      		ncpu="$2"
      		shift 2
		;;

     		--diskSizeMB)
      		diskSizeMB="$2"
      		shift 2
		;;


		--net)
		customOptions="${customOptions} $1 $2"
		shift 2
		;;

		--hostname)
		customOptions="${customOptions} $1 $2"
		shift 2
		;;

  esac
done

if [[ -z $name ]] || [[ -z $targetDir ]] ||  [[ -z $memoryMB ]] || [[ -z $ncpu ]] 
then
     usage
     exit 1
fi


templateDir=`dirname $(cd "${0%/*}" 2>/dev/null; echo "$PWD"/"${0##*/}")`


# copy template disk

targetDiskFileName=${targetDir}/vm-${name}.img
echo Copying ${templateDir}/disk.img to ${targetDiskFileName}
cp ${templateDir}/disk.img ${targetDiskFileName}

# customize image

if [[ -n ${customOptions} ]]
then
	${templateDir}/customize --disk ${targetDiskFileName} ${customOptions}
fi

# create libvirt xml config file

cp ${templateDir}/config.xml  /tmp/config-$$.xml

memoryKB=$(( $memoryMB * 1024))
sed -i -e "s#NAME#${name}#" -e "s#MEMORY#${memoryKB}#" -e "s#CPU#${ncpu}#" -e "s#DISK#${targetDiskFileName}#" /tmp/config-$$.xml

echo /tmp/config-$$.xml


# create vm

virsh define /tmp/config-$$.xml

# clean up

rm /tmp/config-$$.xml
