#!/bin/bash
# Program:
#   Deploy PXE PV VM to DRBL client
# Author: 
#   Jazz, Rock {jazz, rock}@nchc.org.tw
# Version:
#    1.0
# History:                                                                                          
#   2010/08/27  Rock    First release (1.0) 

# [Source]
source /opt/drbl-virt/conf/drbl-virt.conf
source $Work_Path/functions_drbl_virt
#source ./functions_drbl_PXE_PV-VM_create


# [Declation]
# = 1. Varibales declation =
vm_dir="/home/domains"


# = 2. Functions declation =
Usage(){
echo "Usage: drbl_PXE_PV-VM_deploy [options]"
echo "Options:"
echo "-h|--host      deploy vm to which host"
echo "-v|--vm        vm name"
echo "Example:"
echo "drbl_PXE_PV-VM_deploy -h drbl101 -v drbl131"
}


# [Main]
check_root
# = 1. Parse parameters = 
if [ $# -eq 0 ]; then
Usage && exit
fi

while [ $# -gt 0 ]; do
    case "$1" in
        -h|--host)
            shift 
            if [ -z "$(echo $1 |grep ^-.)" ]; then
                if [ -n "$(echo $1)" ]; then
                    client_name=$1
                else
                    echo "-h host_value is null"
                    Usage && exit 2
                fi
            shift 
            fi 
            ;; 
        -v|--vm_cfg)
            shift
            if [ -z "$(echo $1 |grep ^-.)" ]; then
                if [ -n "$(echo $1)" ]; then
                    vm_conf_file=${vm_dir}/${1}_PXE_PV-VM.cfg
                else
                    echo "-v vm_name is null"
                    Usage && exit 2
                fi
            shift
            fi
            ;;
 
        -*)
            echo "$0 $1 invalid option" >&2
            echo ""
            Usage >&2
            exit 2
            ;;
        *)  Usage >&2
            exit 2
            ;;
    esac
done


# = 2. Check null value =
[ -z $client_name ] && echo "[Error] no host" && Usage && exit 2
[ -z $vm_conf_file ] && echo "[Error] no VM configuration file" && Usage && exit 2


# = 3. Check exist
# VM configuration
[ ! -e "$vm_conf_file" ] && echo "[Error] Don't find $vm_conf_file" && exit 2
cat $Work_Home/etc/IP_HOST_TABLE | grep $client_name
if [ $? -ne 0 ]; then
    echo "[Error] This host is not DRBL client"
    exit 2
fi


# = 4. ssh host to deploy VM  =
# local varibales
host_IP=$(cat $Work_Home/etc/IP_HOST_TABLE | grep $client_name | awk '{print $1}')

# start ssh
ssh -o StrictHostKeyChecking=no $host_IP "xm create $vm_conf_file"

