#!/usr/bin/env python

from __future__ import print_function
import pyrax
import os
from docopt import docopt

USAGE = """Destroy a demo environment

Usage:
  destroy-environment.py APP_NAME ENVIRONMENT [--domain_name=<d>]
  destroy-environment.py (-h | --help)
  destroy-environment.py --version

Arguments:
  APP_NAME              The application namespace. Should be unique within a Public Cloud Account.
  ENVIRONMENT           The name of the environment (e.g. stg, prd)

Options:
  -h --help             Show this screen.
  --domain_name=<d>     A base domain name to use for subdomains

Environment variables:
  OS_REGION             A Rackspace Public Cloud region [default: LON]
  OS_USERNAME           A Rackspace Public Cloud username
  OS_API_KEY            A Rackspace Public Cloud API key
"""

# Parse our CLI arguments
arguments = docopt(USAGE, version='1.0.0')

# Set convenience variables from arguments/environment
app_name = arguments['APP_NAME']
environment_name = arguments['ENVIRONMENT']
domain_name = arguments['--domain_name']

# Authenticate
pyrax.set_setting("identity_type", "rackspace")
pyrax.set_setting("region", os.environ.get('OS_REGION', "LON"))
pyrax.set_credentials(os.environ.get('OS_USERNAME'), os.environ.get('OS_API_KEY'))

# Set up some aliases
clb = pyrax.cloud_loadbalancers
au = pyrax.autoscale
dns = pyrax.cloud_dns

# Derived names
asg_name = app_name + "-" + environment_name
lb_name = asg_name + '-lb'
subdomain_name = asg_name

# Try to find the ASG by naming convention.
# This is brittle and we should be rummaging in the launch_configuration metadata
filtered = (node for node in au.list() if
            node.name == asg_name)

for sg in filtered:
    print("Deleting ASG", repr(sg))
    sg.update(min_entities=0, max_entities=0)
    sg.delete()

# Find the LB by naming convention
filtered = (node for node in clb.list() if
            node.name == lb_name)

for lb in filtered:
    print("Deleting LB", repr(lb))
    lb.delete()

if domain_name is not None and domain_name is not '':
    filtered = (dom for dom in dns.list() if dom.name == domain_name)
    for dom in filtered:
        # Delete existing DNS records if any exist
        rec_iter = dns.get_record_iterator(dom)
        for rec in rec_iter:
            if rec.name == subdomain_name + '.' + domain_name:
                print("Deleting DNS Record", repr(rec))
                rec.delete()

print("Done")