#!/bin/bash
set -e
set -o xtrace
temp_dir=`mktemp`; rm -rf $temp_dir; mkdir -p $temp_dir
TOPDIR=$(cd $(dirname "$0") && pwd)

function _create_mac_file(){
mac_temp=$TOPDIR/mac_temp
cat <<"EOF" >$mac_temp
# This file was automatically generated by the /lib/udev/write_net_rules
# program, run by the persistent-net-generator.rules rules file.
#
# You can modify it, as long as you keep each rule on a single
# line, and change only the value of the NAME= key.
# PCI device 0x10ec:0x8139 (8139cp)
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="%MAC%", ATTR{type}=="1", KERNEL=="eth*", NAME="eth0"
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="%MAC2%", ATTR{type}=="1", KERNEL=="eth*", NAME="eth1"
EOF
}

function _create_net_file(){
net_temp=$TOPDIR/net_temp
cat <<"EOF">$net_temp
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet dhcp

auto eth1
iface eth1 inet static
    address 192.168.1.%IP%
    netmask 255.255.255.0
    broadcast 192.168.1.1
    gateway 192.168.1.1
EOF
}

function __mount_qcow2_disk(){
    modprobe nbd  max_part=63
    qemu-nbd -c /dev/nbd0 $TOPDIR/ubuntu-$1.qcow2
    sleep 1
    kpartx -a /dev/nbd0
    sleep 1
    mount /dev/mapper/nbd0p1 $temp_dir
}

function __umount_qcow2_disk(){
    umount $temp_dir
    qemu-nbd -d /dev/nbd0
}

function _create_image(){
    ip=$1; mac=$2; mac2=$3; HOST_NAME=ubuntu-${ip}
    qemu-img create -f qcow2 -o \
       cluster_size=2M,backing_file=/image/ubuntu-12.04.raw ubuntu-$ip.qcow2 40G

    __mount_qcow2_disk $ip
    mac_file=$temp_dir/etc/udev/rules.d/70-persistent-net.rules
    net_file=$temp_dir/etc/network/interfaces
    cp -rf $TOPDIR/mac_temp $mac_file
    cp -rf $TOPDIR/net_temp $net_file
    sed -i "s,%MAC%,$mac,g"     $mac_file
    sed -i "s,%MAC2%,$mac2,g"   $mac_file
    sed -i "s,%IP%,$ip,g" $net_file
    sed -i "s,127.0.1.1.*,127.0.1.1   $HOST_NAME,g"  $temp_dir/etc/hosts
    echo "$HOST_NAME" > $temp_dir/etc/hostname
    __umount_qcow2_disk
}

function create_xml(){
    ip=$1
    xml_file=ubuntu-${ip}.xml
    cp -rf $TOPDIR/template.xml $xml_file
    sed -i "s,%VM_NAME%,ubuntu-${i},g" $xml_file
    UUID=`uuidgen`
    sed -i "s,%UUID%,$UUID,g" $xml_file
    MAC="fa:95:$(dd if=/dev/urandom count=1 2>/dev/null \
           | md5sum | sed 's/^\(..\)\(..\)\(..\)\(..\).*$/\1:\2:\3:\4/')"
    sed -i "s,%MAC%,$MAC,g" $xml_file
    MAC2="52:54:$(dd if=/dev/urandom count=1 2>/dev/null \
           | md5sum | sed 's/^\(..\)\(..\)\(..\)\(..\).*$/\1:\2:\3:\4/')"
    sed -i "s,%MAC2%,$MAC2,g" $xml_file
    _create_image $ip $MAC $MAC2
    
    IMAGE_PATH="${TOPDIR}/ubuntu-${i}.qcow2"
    sed -i "s,%IMAGE_PATH%,$IMAGE_PATH,g" $xml_file
}

_create_mac_file
_create_net_file
for i in 233 235 190; do
    create_xml $i
    virsh define ubuntu-${i}.xml
    virsh start ubuntu-${i}
done

set +o xtrace
