#!/usr/bin/env python
#

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

from __future__ import absolute_import, print_function

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

try:
    import gterm
except ImportError:
    import graphterm.bin.gterm as 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(config_info, file=sys.stderr)
    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>%(taglist)s<td><a class="gterm-link gterm-click" href="" data-gtermmime="" data-gtermcmd="ec2ssh ubuntu@%(arg)s">%(public_dns)s</a><td>%(state)s<td><a class="gterm-link gterm-click" href="" data-gtermmime="" data-gtermcmd="ec2list --kill %(id)s" data-gtermconfirm="Terminate instance %(id)s (%(taglist)s)?">%(killstr)s</a>'

Column_headers = ["Id", "Tags", "Connect", "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("No instances to kill", file=sys.stderr)
        sys.exit(1)

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

for props in props_list:
    pdict = props.copy()
    pdict["arg"] = gterm.CMD_ARG
    pdict["taglist"] = ",".join(list(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 = list(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("Failed to remove DNS record for ", instance_tag, file=sys.stderr)
            
    killid_list = [x["id"] for x in props_list]
    ec2common.kill(instance_ids=killid_list)
    print("Killed", killid_list, file=sys.stderr)
