#!/bin/bash
SERVERNAME=postgresql
DATA_VOLUME=39c1793f-0e3d-4da6-9b5b-c91bcf047b28

echo "Creating VM ${SERVERNAME}"

openstack server create  \
--image ubuntu-16.04-amd64 \
--user-data data-${SERVERNAME}.yaml \
--key-name "Sebastian Rojo" \
--flavor m1.medium.md \
--min 1 \
--max 1 \
--security-group default \
--availability-zone nuczone \
--nic net-id=7a9ae8e9-8425-4084-94cc-fb70c069e957,v4-fixed-ip=172.16.253.178 \
--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 DATA_VOLUME ${DATA_VOLUME}..."
      openstack server add volume --device /dev/vdb ${SERVERNAME} ${DATA_VOLUME}
      openstack volume show ${DATA_VOLUME}
      openstack server show ${SERVERNAME}
      exit 0
    else
      echo "VM ${SERVERNAME} is not active yet"
      sleep 2
    fi
done
