#!/bin/bash
echo $0 started at $(date)

PARTICIPANT=${1}
. ./common-vars
. ./openstack_credentials.rc PARTICIPANT

OPENSTACK_USER=hackfest15group${PARTICIPANT}
PROJECT=hackfest15group${PARTICIPANT}
PASSWORD=hackfest15group-${PARTICIPANT}!
echo Cleaning up ${OPENSTACK_USER}

PROJECT_ID=`openstack project list | grep "${PROJECT} " | awk '{print $2}'`
if [ "${PROJECT_ID}" != "" ]; then

    unset OS_PROJECT_NAME
    echo "Removing Router Ports"
    for ROUTER in $(openstack --os-username=$OPENSTACK_USER --os-password=$PASSWORD --os-project-id=$PROJECT_ID router list -f value -c ID); do
        openstack --os-username=$OPENSTACK_USER --os-password=$PASSWORD --os-project-id=$PROJECT_ID router unset --external-gateway ${ROUTER}
        PORT=$(openstack --os-username=$OPENSTACK_USER --os-password=$PASSWORD --os-project-id=$PROJECT_ID router show ${ROUTER} -f json -c interfaces_info | jq .interfaces_info[0].port_id -r)
        while [ "${PORT}" != "null" -a "${PORT}" != "" ] ; do
            openstack --os-username=$OPENSTACK_USER --os-password=$PASSWORD --os-project-id=$PROJECT_ID router remove port ${ROUTER} ${PORT}
            PORT=$(openstack --os-username=$OPENSTACK_USER --os-password=$PASSWORD --os-project-id=$PROJECT_ID router show ${ROUTER} -f json -c interfaces_info | jq .interfaces_info[0].port_id -r)
        done
    done

    echo "Removing VMs"
    openstack --os-username=$OPENSTACK_USER --os-password=$PASSWORD --os-project-id=$PROJECT_ID server list -f value -c ID | xargs openstack --os-username=$OPENSTACK_USER --os-password=$PASSWORD --os-project-id=$PROJECT_ID server delete
    echo "Removing Routers"
    openstack --os-username=$OPENSTACK_USER --os-password=$PASSWORD --os-project-id=$PROJECT_ID router list -f value -c ID | xargs openstack --os-username=$OPENSTACK_USER --os-password=$PASSWORD --os-project-id=$PROJECT_ID router delete
    echo "Removing Ports"
    openstack --os-username=$OPENSTACK_USER --os-password=$PASSWORD --os-project-id=$PROJECT_ID port list -f value -c ID   | xargs openstack --os-username=$OPENSTACK_USER --os-password=$PASSWORD --os-project-id=$PROJECT_ID port delete
fi


echo $0 $@ complete at $(date)