#!/bin/bash -e

echo -n Ubuntu Openstack Installer Uninstalling ...

WHAT=$(openstack-config install_type)
CONTAINER_NAME=$(openstack-config container_name)
CONTAINER_NETWORK=$(openstack-config lxc_network)

apt_purge() {
  DEBIAN_FRONTEND=noninteractive apt-get -yy purge $@
}

CFG_HOME=$(openstack-config cfg_path)
case $WHAT in
  "Landscape OpenStack Autopilot")
    echo Landscape OpenStack Autopilot environment
    JUJU_HOME="$CFG_HOME/juju" juju destroy-environment --yes --force maas || exit 1
    ;;
  Multi)
    echo Multi install environment

    JUJU_HOME="$CFG_HOME/juju" juju status  > /dev/null 2>&1
    if [ 0 = $? ]; then
	JUJU_HOME="$CFG_HOME/juju" juju destroy-environment --yes --force maas || \
	    { echo "error in destroy-environment, exiting without further cleanup"
	      exit 1
	    }
    else
	echo "Environment not bootstrapped, continuing with other cleanup."
    fi

    # Multi places backup network settings here.
    rm -rf /etc/openstack || true

    ;;
  Single)
    echo Single install path.
    echo "Destroying $CONTAINER_NAME"
    lxc-stop -n $CONTAINER_NAME || true
    lxc-destroy -n $CONTAINER_NAME || true
    if [ -n "$CONTAINER_NETWORK" ]; then
        echo "Deleting $CONTAINER_NETWORK"
        ip route del $CONTAINER_NETWORK || true
    else
        echo "No static route defined. Not changing routing tables."
    fi
    ;;
  *)
    echo Could not determine install type, was ~/.cloud-install removed prior to running the uninstallation?
    exit 1
    ;;
  esac


rm -rf ~/.cloud-install/juju || true
rm -f ~/.cloud-install/installed || true
