##
# 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"}

vnet.get_insert_text(){
	local vn_id=${1?"[FAIL]:$FUNCNAME waits for a vm id as parameter"};
	local oldfields='oid, uid, name, type, bridge' 
	
	local oldvalues=`query_sqlite_prepare " SELECT $oldfields FROM network_pool WHERE oid=$vn_id ;"` 
	debug old_values=$oldvalues
	[ -z "${oldvalues}" ] && return 
	local allfields="$oldfields, public, template"
	local newvalues=
#	while read value
#	do
#		newvalues=$newvalues", $value"
#	done  < <( echo $oldvalues )
#	newvalues=${newvalues:0:${#newvalues}-1}
	local allvalues="$oldvalues, 0, '`vnet.get_template_text $vn_id`'"
	
	echo "INSERT INTO network_pool ( $allfields ) VALUES ( $allvalues );"
}

vnet.get_template_text(){
	local vm_id=${1?"[FAIL]:$FUNCNAME waits for a vm id as parameter"}
	previa=`query_sqlite "SELECT id FROM vm_attributes WHERE value=$vm_id AND name='VMID';"`
	template_text='<TEMPLATE>';
	local NIC_count=0
	local HD_count=0
	while read complet 
	do
		varia="${complet%%=*}"
		value="${complet#*=}"
#		debug varia=\"$varia\"
		template_text=$template_text"
    <$varia>
       <![CDATA[$value]]>
    </$varia>"
	done < <( get_attributes vn_template $previa )
	template_text=$template_text"
</TEMPLATE>";
#	echo -n ${template_text} | sed -e 's:>\ :>:g'
	cat  << EOF
${template_text}
EOF
}
