#!/bin/bash

TOPDIR=$(cd $(dirname "$0") && pwd)


if [[ $# -eq 0 ]]; then
    echo "There must be one parameters"
    exit 0
fi


set -e
set -o xtrace

[[ `dpkg -l kpartx | wc -l` -eq 0 ]] && apt-get install -y --force-yes kpartx lvm2
mkdir -p $1
qemu-img create -f qcow2 -o cluster_size=2M,backing_file=/cloud/_base/ubuntu-12.10.raw $1/ubuntu-$1.qcow2 40G

cp _base/back $1/$1
HOST_NAME=$1
uuid=`uuidgen`
sed -i "s,%UUID%,$uuid,g" $1/$1
sed -i "s,%VM_NAME%,$1,g" $1/$1

add_disk=0
for n in $@; do
    if [[ "$n"x = "disk"x ]]; then
        qemu-img create -f raw $1/ubuntu-raw-disk.raw 30G
        RAW_DISK_PATH=$TOPDIR/$1/ubuntu-raw-disk.raw
        sed -i "s,%RAW_DISK_PATH%,$RAW_DISK_PATH,g" $1/$1
        let "add_disk = $add_disk + 1"
        break
    fi
    if [[ "$n"x = "-disk"x ]]; then
        qemu-img create -f raw $1/ubuntu-raw-disk.raw 30G
        RAW_DISK_PATH=$TOPDIR/$1/ubuntu-raw-disk.raw
        sed -i "s,%RAW_DISK_PATH%,$RAW_DISK_PATH,g" $1/$1
        let "add_disk = $add_disk + 1"
        break
    fi
done

if [[ $add_disk -eq 0 ]]; then
    sed -i "34,40d" $1/$1
fi



machine=`qemu-system-x86_64 -M ? | grep default | awk '{print $1}'`
sed -i "s,pc-0.14,$machine,g" $1/$1

# Gen MAC address
MACADDR="fa:92:$(dd if=/dev/urandom count=1 2>/dev/null | md5sum | sed 's/^\(..\)\(..\)\(..\)\(..\).*$/\1:\2:\3:\4/')";
echo $MACADDR
sed -i "s,%MAC%,$MACADDR,g" $1/$1

MACADDR2="52:54:$(dd if=/dev/urandom count=1 2>/dev/null | md5sum | sed 's/^\(..\)\(..\)\(..\)\(..\).*$/\1:\2:\3:\4/')";
echo $MACADDR2
sed -i "s,%MAC2%,$MACADDR2,g" $1/$1

MACADDR3="52:54:$(dd if=/dev/urandom count=1 2>/dev/null | md5sum | sed 's/^\(..\)\(..\)\(..\)\(..\).*$/\1:\2:\3:\4/')";
echo $MACADDR2
sed -i "s,%MAC3%,$MACADDR3,g" $1/$1



sed -i "s,%IMAGE_PATH%,/cloud/$1/ubuntu-$1.qcow2,g" $1/$1

modprobe nbd  max_part=63

dev_number=1
qemu-nbd -c  /dev/nbd${dev_number} /cloud/$1/ubuntu-$1.qcow2
sleep 3
kpartx -a /dev/nbd${dev_number}
sleep 1
nbd_dev=`ls /dev/mapper | grep nbd${dev_number} | tail -1`
temp_file=`mktemp`; rm -rf $temp_file; mkdir -p $temp_file
sleep 1

for root_path in `ls /dev/mapper | grep -v nbd | grep -v control`; do
    mount /dev/mapper/$root_path $temp_file
    sleep 1
    if [[ `ls $temp_file | grep root | wc -l` -gt 0 ]]; then
        umount $temp_file
        break;
    fi
    umount $temp_file
done
mount /dev/mapper/$root_path $temp_file

echo $temp_file

# Change network configuration.
#----------------------------------------------
file=$temp_file/etc/udev/rules.d/70-persistent-net.rules
cat <<"EOF" >$temp_file/etc/udev/rules.d/70-persistent-net.rules
# 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"
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="%MAC3%", ATTR{type}=="1", KERNEL=="eth*", NAME="eth2"

EOF

sed -i "s,%MAC%,$MACADDR,g" $file
sed -i "s,%MAC2%,$MACADDR2,g" $file
sed -i "s,%MAC2%,$MACADDR3,g" $file

file=$temp_file/root/.vimrc
cat <<"EOF">$file
set shiftwidth=4
set tabstop=4
set expandtab
set noswapfile
syntax on
EOF


file=$temp_file/root/proxy
cat <<"EOF">$file
export https_proxy="http://proxy.pd.intel.com:911"
export http_proxy=$https_proxy
export ftp_proxy=$https_proxy
EOF

file=$temp_file/etc/network/interfaces


cat <<"EOF">$file
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet %USE_DHCP%

auto eth1
iface eth1 inet static
    address 192.168.222.%IP1%
    netmask 255.255.255.0
    broadcast 192.168.222.1
    gateway 192.168.222.1

auto eth2
iface eth2 inet static
    address 192.168.111.%IP2%
    netmask 255.255.255.0
    broadcast 192.168.111.1
    gateway 192.168.111.1

EOF
function _get_ip() {
    rm -rf /tmp/ret
    prefix=$1
    for n in `find $TOPDIR -name "*" | grep -v raw | grep -v qcow | grep -v vm.sh | grep -v test.sh`; do
        if [[ ! -d $n ]]; then
            grep -Hn $prefix $n  >> /tmp/ret
        fi
    done
    cat /tmp/ret | awk '{print $5}' > /tmp/res
    n=4
    while [[ n -le 254 ]]; do
        cnt=`cat /tmp/res | grep "$prefix.$n" | wc -l`
        if [[ $cnt -eq 0 ]]; then
            echo $n
            break;
        fi
        let "n=$n + 1"
    done
    rm -rf /tmp/ret /tmp/res
}

sed -i "s,%USE_DHCP%,manual,g" $file
for n in $@; do
    if [[ "$n"x = "--dhcp"x ]]; then
        sed -i "s,manual,dhcp,g" $file
    fi
    if [[ "$n"x = "-d"x ]]; then
        sed -i "s,manual,dhcp,g" $file
    fi
done

IP1=`_get_ip 192.168.222`
sed -i "s,%IP1%,$IP1,g" $file
sed -i "s,%IP1%,$IP1,g" $1/$1

IP2=`_get_ip 192.168.111`
sed -i "s,%IP2%,$IP2,g" $file
sed -i "s,%IP2%,$IP2,g" $1/$1


sed -i "s,127.0.1.1.*,127.0.1.1    $HOST_NAME,g"  $temp_file/etc/hosts
sed -i "/exit/d" $temp_file/etc/rc.local
echo "route add default gw 10.239.82.1 eth0" > $temp_file/etc/rc.local
echo "exit 0" >> $temp_file/etc/rc.local
echo "$HOST_NAME" > $temp_file/etc/hostname



#----------------------------------------------
umount $temp_file
qemu-nbd -d /dev/nbd${dev_number}

for n in `ls /dev/mapper | grep -v control | grep -v nbd`; do
    dmsetup clear /dev/mapper/$n
    dmsetup remove /dev/mapper/$n
done

for n in `ls /dev/mapper | grep -v control | sort -r`; do
    dmsetup clear /dev/mapper/$n
    dmsetup remove /dev/mapper/$n
done

rmmod nbd
virsh define $1/$1
virsh start $1
set +o xtrace
