#!/bin/bash


echo "Downloading and decompressing vm imaage"

if [ -f debian10-ssh.img ]; then 
  echo "  -> Alreday done using cached version"
else
  wget https://immfly-infra-technical-test.s3-eu-west-1.amazonaws.com/debian10-ssh.img.tar.xz
  tar xf debian10-ssh.img.tar.xz
  rm -f debian10-ssh.img.tar.xz
fi

#Fix the route in the vm file
sed "s+\${PATH_TO_VM_DISK_FILE}+$PWD/debian10-ssh.img+" assets/vm.xml > vm.xml

echo "Start the VM"
virsh create vm.xml

#We get the ip
IP=`virsh domifaddr immfly-debian10 | grep ipv4 | awk '{ print $4 }' | sed 's/\/.*//'`
echo "VM ip obtained: $IP"

#Pequeño hack para asegurar que la conexion ssh se ha levantado
until ssh-keyscan $IP ; do sleep 3 ; done

#Upgrade the ansible inventory
sed "s/VM_IP/$IP/" assets/inventory.yml > ansible/inventory.yml

#Run the playbook
cd ansible
ansible-playbook -i inventory.yml -v tech-test-infra.yml
