#!/bin/bash
source /root/envsetup/global-conf.sh

KEY=~/.ssh/ubicast_support
VM_HYPER=$(grep VM_HYPER ${CONF} | awk -F "=" '{print$2}')
VM_STORE=$(grep VM_STORE ${CONF} | head -1 | awk -F "=" '{print$2}')
VM_STORE_LOCAL=$(grep VM_STORE_LOCAL ${CONF} | awk -F "=" '{print$2}')

if ( test -z $VM_NAME ); then
    VM_NAME=$(cat ${CONF} | egrep ^ETC_HOSTNAME | head -1 | awk -F "=" '{print$2}')
else
    VM_NAME=$(grep VM ${CONF} | awk -F "=" '{print$2}')
fi

ssh -i ${KEY} -o User=root ${VM_HYPER} "VBoxManage export ${VM_NAME} -o ${VM_STORE}/${VM_NAME}.ovf --ovf10"

# vbox conf file created

# generating vmware conf file
cp ${VM_STORE_LOCAL}/${VM_NAME}.ovf ${VM_STORE_LOCAL}/${VM_NAME}_vmware.ovf
sed -i "s@<vssd:VirtualSystemType>virtualbox-2.2</vssd:VirtualSystemType>@<vssd:VirtualSystemType>vmx-07</vssd:VirtualSystemType>@" ${VM_STORE_LOCAL}/${VM_NAME}_vmware.ovf
sed -i "s@<rasd:Caption>sataController0</rasd:Caption>@<rasd:Caption>SCSIController</rasd:Caption>@" ${VM_STORE_LOCAL}/${VM_NAME}_vmware.ovf
sed -i "s@<rasd:Description>SATA Controller</rasd:Description>@<rasd:Description>SCSIController</rasd:Description>@" ${VM_STORE_LOCAL}/${VM_NAME}_vmware.ovf
sed -i "s@<rasd:ElementName>sataController0</rasd:ElementName>@<rasd:ElementName>SCSIController</rasd:ElementName>@" ${VM_STORE_LOCAL}/${VM_NAME}_vmware.ovf
sed -i "s@<rasd:ResourceSubType>AHCI</rasd:ResourceSubType>@<rasd:ResourceSubType>lsilogic</rasd:ResourceSubType>@" ${VM_STORE_LOCAL}/${VM_NAME}_vmware.ovf
sed -i "s@<rasd:ResourceType>20</rasd:ResourceType>@<rasd:ResourceType>6</rasd:ResourceType>@" ${VM_STORE_LOCAL}/${VM_NAME}_vmware.ovf

# recherche n° ligne paragraphe à supp.
LIG=$(grep -n '<rasd:AddressOnParent>3</rasd:AddressOnParent>' ${VM_STORE_LOCAL}/${VM_NAME}_vmware.ovf | awk -F ":" '{print$1}')
LIG0=$(( $LIG - 1 ))
LIG1=$(( $LIG0 + 9 ))
sed -i "${LIG0},${LIG1}d" ${VM_STORE_LOCAL}/${VM_NAME}_vmware.ovf

# converting disk to qemu image
qemu-img convert -c -O qcow2 ${VM_STORE_LOCAL}/${VM_NAME}-disk1.vmdk ${VM_STORE_LOCAL}/${VM_NAME}.qcow2

echo -e "${CYAN}Files are available at ${VM_STORE_LOCAL}${NC}"
