#!/usr/bin/env python
#

"""
ec2list: Launch Amazon AWS EC2 instances
"""

import boto
import json
import os
import sys
import time
from optparse import OptionParser

import gterm
import ec2common

usage = "usage: %prog [...] [<instance_id|tag_name|wildcard>]"
parser = OptionParser(usage=usage)
parser.add_option("-f", "--fullpage", dest="fullpage", default=False,
                  help="Fullpage display", action="store_true")

parser.add_option("-t", "--text", dest="text", default=False,
                  help="Text output", action="store_true")

parser.add_option("", "--kill", dest="kill", default=False,
                  help="Kill single matching instance", action="store_true")

parser.add_option("", "--killall", dest="killall", default=False,
                  help="Kill all matching instances", action="store_true")


(options, args) = parser.parse_args()

tag_name = args[0] if args else ""

if not os.path.exists(os.path.expanduser("~/.boto")):
    print >> sys.stderr, config_info
    sys.exit(1)

params = {"display": "block", "scroll": "top", "current_directory": os.getcwd()}
if options.fullpage:
    params["display"] = "fullpage"

headers = {"content_type": "text/html"}
headers["x_gterm_response"] = "pagelet"
headers["x_gterm_parameters"] = params

Props_format = "Instance: id=%(id)s, domain=%(public_dns)s, key=%(key)s, tags=%(taglist)s, state=%(state)s"

Row_format = '<tr><td>%(id)s<td>%(public_dns)s<td>%(key)s<td>%(taglist)s<td>%(state)s<td><a class="gterm-link" href="" data-gtermmime="" data-gtermcmd="ec2list --kill %(id)s" data-gtermconfirm="Terminate instance %(id)s?">%(killstr)s</a>'

Column_headers = ["Id", "Public DNS", "Key", "Tags", "State", "Action"]

Table_list = ['<table frame=none border=0>',
              '<colgroup colspan=%d width=1*>' % (len(Column_headers),),
              '<tr>']

for header in Column_headers:
    Table_list.append('<td><b>%s</b>' % header)

props_list = ec2common.get_instance_props(name=tag_name)

if options.kill or options.killall:
    if not props_list:
        print >> sys.stderr, "No instances to kill"
        sys.exit(1)

    if len(props_list) > 1 and not options.killall:
        print >> sys.stderr, "Specify --killall to kill multiple instances"
        sys.exit(1)

for props in props_list:
    pdict = props.copy()
    pdict["taglist"] = ",".join(props["tags"].keys())
    pdict["killstr"] = "Kill" if props["state"] == "running" else ""
    if options.text:
        print Props_format % pdict
    else:
        Table_list.append(Row_format % pdict)

if not options.text:
    Table_list.append('</table>')
    html = "\n".join(Table_list) + "\n"
    gterm.write_pagelet(html, display=("fullpage" if options.fullpage else "block"))

if options.kill or options.killall:
    for props in props_list:
        if len(props["tags"]) == 1:
            instance_tag = props["tags"].keys()[0]
            instance_name, sep, domain = instance_tag.partition(".")
            if domain:
                route53conn = ec2common.Route53Connection()
                hosted_zone = ec2common.get_hosted_zone(route53conn, domain)
                if hosted_zone:
                    try:
                        ec2common.cname(route53conn, hosted_zone, instance_tag, props["public_dns"], remove=True)
                        try:
                            ec2common.cname(route53conn, hosted_zone, "*."+instance_tag, props["public_dns"], remove=True)
                        except Exception:
                            pass
                    except Exception:
                        print >> sys.stderr, "Failed to remove DNS record for ", instance_tag
            
    killid_list = [x["id"] for x in props_list]
    ec2common.kill(instance_ids=killid_list)
    print >> sys.stderr, "Killed", killid_list
