#!/usr/bin/env python

import os
import sys
import getopt

from sys import stderr

import boto.ec2


_ec2 = None


def short_usage():
    print >>stderr, """Usage: ec2-host [-t TAG] [NAME]
    ec2-host django8 => ec2-XX-19-113-121.compute-1.amazonaws.com
Try `ec2-ssh --help' for more information."""


def full_usage():
    print >>stderr, """Usage: ec2-host [-t TAG] [NAME]
Prints server host name.

      --help                 display this help and exit
  -t, --tag TAG              Tag name for searching, defaults to 'Name'"""


def ec2_active_instances(label_tag, filters):
    instances = []
    kwargs = {}

    if filters:
        kwargs['filters'] = filters

    reservations = _ec2.get_all_instances(**kwargs)
    for reservation in reservations:
        for instance in reservation.instances:
            instance_name = instance.tags.get(label_tag)
            if instance.public_dns_name:
                pair = (instance_name, instance.public_dns_name)
                instances.append(pair)
    return instances


def main(argv):
    try:
        opts, args = getopt.getopt(argv, "hLt:",
                                         ["help", "tag="])
    except getopt.GetoptError, err:
        print >>sys.stderr, err
        short_usage()
        sys.exit(2)

    tag = "Name"

    for opt, arg in opts:
        if opt in ("-h", "--help"):
            full_usage()
            sys.exit()
        elif opt in ("-t", "--tag"):
            tag = arg

    global _ec2
    _ec2 = boto.ec2.connection.EC2Connection()

    argc = len(args)

    filters = {}
    if argc == 1:
        filters['tag:%s' % tag] = args[0]
    elif argc > 1:
        print >>stderr, "Warning: more than one name given"
        sys.exit(1)
        return

    instances = ec2_active_instances(tag, filters)

    numinstances = len(instances)

    if numinstances == 1:
        print instances[0][1]  # [1] = dns

        sys.exit(0)
        return
    elif numinstances == 0 or numinstances > 1:
        for pair in sorted(instances, key=lambda p: p[0]):
            print "%s\t%s" % pair

        sys.exit(0)
        return
    else:
        print >>stderr, 'Unable to match "%s"' % args[0]
        short_usage()

        sys.exit(1)
        return

if __name__ == "__main__":
    main(sys.argv[1:])
