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

. ./common-vars
. ./admin-credentials.rc

PARTICIPANT=${1}

OPENSTACK_USER=hackfest-$1
PROJECT=$OPENSTACK_USER
PASSWORD=hackfest

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
    echo "Removing Networks"
    openstack --os-username=$OPENSTACK_USER --os-password=$PASSWORD --os-project-id=$PROJECT_ID network list -f value -c ID| xargs openstack --os-username=$OPENSTACK_USER --os-password=$PASSWORD --os-project-id=$PROJECT_ID network delete

    #for RBAC in `openstack network rbac list -f value -c ID`; do
    #    openstack network rbac show $RBAC -f value | grep $PROJECT_ID 2> /dev/null
    #    if [ $? -eq 0 ] ; then
    #        echo "Deleting RBAC policy $RBAC"
    #        openstack network rbac delete $RBAC &
    #    fi
    #done

    echo "Deleting OpenStack project: $PROJECT"
    . ./admin-credentials.rc
    openstack project purge --project ${PROJECT_ID}
fi

echo "Deleting OpenStack User: $OPENSTACK_USER"
openstack user delete --domain ${ADMIN_DOMAIN} ${OPENSTACK_USER}

echo $0 $@ complete at $(date)