##
# Project: one.migration: Scripts for the migration from opennebula 1.4 to 2.0.1 
# Description:  This bash source file contains functions for the SQL migration.
#   
# @author Marlon Nerling, Abacus Research AG, 9301 Wittenbach, Schweiz http://www.abacus.ch Copyright (C) 2010.
#   
# @see The GNU Public License (GPL)
#
## 
# This program is free software; you can redistribute it and/or modify 
# it under the terms of the GNU General Public License as published by 
# the Free Software Foundation; either version 2 of the License, or 
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful, but 
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
# for more details.
# 
# You should have received a copy of the GNU General Public License along 
# with this program; if not, write to the Free Software Foundation, Inc., 
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#

ORIGINAL_DB=${ORIGINAL_DB?"Variable ORIGINAL_DB may be set"}
ONEMIGRATION_COMMON=${ONEMIGRATION_COMMON?"ONEMIGRATION_COMMON source (one.migration.common.sh) was not sourced"}

host.get_insert_text(){
	local host_id=${1?"[FAIL]:$FUNCNAME waits for a host id as parameter"};
	host_pool.get_insert_text $host_id
	host_shares.get_insert_text $host_id
}

host_shares.get_insert_text(){
	local host_id=${1?"[FAIL]:$FUNCNAME waits for a host id as parameter"};
	local oldfields='hid, disk_usage, mem_usage, cpu_usage,max_disk, max_mem, max_cpu, free_disk, free_mem, free_cpu,used_disk, used_mem, used_cpu, running_vms'
	local oldvalues=`query_sqlite_prepare " SELECT $oldfields FROM host_shares WHERE hid=$host_id ;"` 
	[ -z "${oldvalues}" ] && return 
	local allfields="$oldfields"
	local allvalues="$oldvalues"

	echo "INSERT INTO host_shares ( $allfields ) VALUES ( $allvalues );"
	echo 
}

host_pool.get_insert_text(){
	local host_id=${1?"[FAIL]:$FUNCNAME waits for a host id as parameter"};
	local oldfields='oid, host_name, state, im_mad, vm_mad, tm_mad, last_mon_time'
	
	local oldvalues=`query_sqlite_prepare " SELECT $oldfields FROM host_pool WHERE oid=$host_id ;"` 
	[ -z "${oldvalues}" ] && return 
	local allfields="$oldfields, cluster, template"
	local allvalues="$oldvalues, 0, '`host.get_template_text $host_id`'"
	
	echo "INSERT INTO host_pool ( $allfields ) VALUES ( $allvalues );"
	echo 
}

host.get_template_text(){
	local host_id=${1?"[FAIL]:$FUNCNAME waits for a host id as parameter"}
	via=`get_attributes host_attributes "$host_id"`
	local template_text='<TEMPLATE>';
	for complet in ${via[@]}
	do
		varia="${complet%=*}"
		value="${complet#*=}"
		template_text=$template_text"<$varia><![CDATA[$value]]></$varia>"
	done
	template_text=$template_text"</TEMPLATE>";
	echo -n ${template_text}
}
