#!/bin/bash
SERVERNAME=cdr-01-med-guest
CONFIG_VOLUME=2c3c3e5e-4ec3-4909-987f-5528623c7a34
DATA_VOLUME=fa5386cb-b947-4ad4-a37c-3fff327aa4d4

echo "Creating VM ${SERVERNAME}"

openstack server create  \
--image "ubuntu-16.04.0.2-amd64" \
--user-data data-${SERVERNAME}.yaml \
--key-name "Sebastian Rojo" \
--flavor m1.medium.sd \
--min 1 \
--max 1 \
--security-group DefaultSapian \
--security-group cdr-stats \
--availability-zone nuczone \
--nic net-id=41f72a3e-eecf-4c85-aec5-0007ad1a0201 \
--wait \
${SERVERNAME}

for RUN in {1..50}; do
    if [ "$(openstack server show ${SERVERNAME} | awk '/status/ {print $4}')" == "ACTIVE" ]
    then
      openstack server show ${SERVERNAME}
      echo "${SERVERNAME} Active. Attahing CONFIG_VOLUME ${CONFIG_VOLUME}..."
      openstack server add volume --device /dev/vdb ${SERVERNAME} ${CONFIG_VOLUME}
      echo "${SERVERNAME} Active. Attahing DATA_VOLUME ${DATA_VOLUME}..."
      openstack server add volume --device /dev/vdc ${SERVERNAME} ${DATA_VOLUME}
      openstack server add floating ip ${SERVERNAME} 172.16.253.114
      openstack volume show ${CONFIG_VOLUME}
      openstack volume show ${DATA_VOLUME}
      openstack server show ${SERVERNAME}
      openstack console url show ${SERVERNAME}
      exit 0
    else
      echo "VM ${SERVERNAME} is not active yet"
      sleep 2
    fi
done
