#!/usr/bin/env python
#
# Remove all monitoring checks in the current region.

import pyrax
import os

region = os.environ['RAX_REGION']

pyrax.set_setting("identity_type", "rackspace")
pyrax.set_setting("region", region.upper())
pyrax.set_credential_file(os.path.expanduser("~/.rackspace_cloud_credentials"))

prefix = region.lower()

cm = pyrax.cloud_monitoring

def attempt_nuke(monitor_element):
    try:
        monitor_element.delete()
        print("DELETED {}".format(monitor_element))
    except Exception as e:
        print("Can't delete {}".format(monitor_element))
        print(e)

print ">> ENTITIES ::"
for e in cm.list_entities():
    if e.label.startswith(prefix):
        attempt_nuke(e)

print ">> CHECKS ::"
for e in cm.list_entities():
    if e.label.startswith(prefix):
        checks = e.list_checks()
        if len(checks) > 0:
            print "- %s" % e.label
        for c in e.list_checks():
            attempt_nuke(c)

print ">> NOTIFICATIONS ::"
for n in cm.list_notifications():
    if n.label.startswith(prefix):
        attempt_nuke(n)

print ">> NOTIFICATION PLANS ::"
for np in cm.list_notification_plans():
    if n.label.startswith(prefix):
        attempt_nuke(np)

print ">> ALARMS ::"
for e in cm.list_entities():
    if e.label.startswith(prefix):
        alarms = e.list_alarms()
        if len(alarms) > 0:
            print "- %s" % e.label

        for a in e.list_alarms():
            attempt_nuke(a)
