#!/usr/bin/env python
# -*- coding: utf-8 -*-

import subprocess
import botocore.session
import json
from sys import exit,argv

help_text = '''NAME
    ec2tagread - Check tags from an ec2 instance

SYNOPSYS
    ec2tagread --list

    ec2tagread --all

    ec2tagread --json

    ec2tagread --help

    ec2tagread <tag>

DESCRIPTION
    ec2tagread list or return tag values within an EC2 instance (ubuntu/debian
    atm.), it requres ''ec2metada'' executable and botocore library. It uses
    current instance''s id to get tags, so it cannot be used for check tags for
    arbitrary instance ids or be used outside an AWS instance. Instance or
    active IAM User must be capable of read tags either by aws credentials or
    IAM instance roles (EC2 DescribeTags permission).

PARAMETERS
    --list
        list all available tags

    --all
        list all tags and values on a human readable way

    --json
        list all tags and values in a json array

    --help
        shows this help text

    <tag>
        returns the value of the specified tag


AUTHOR
    Carlos Peñas San José <https://github.com/theist>

COPYRIGHT
    Copyright ©2016 The Cocktail Experience S.L.U

    Lic. GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

    This is free software: you are free to change and redistribute it. There is
    NO WARRANTY, to the extent permitted by law.
'''
if len(argv) < 2 or argv[1] == '--help':
    print help_text
    exit(0)

try:
    instance_id = subprocess.check_output(["ec2metadata", "--instance-id"]).rstrip()
except:
    print "failed to get ec2 metadata"
    exit(1)

try:
    session = botocore.session.get_session()
    client = session.create_client('ec2', region_name='eu-west-1')
    tags = client.describe_tags(Filters=[{'Name': 'resource-id', 'Values': [instance_id]}])
except:
    print "error reading tags"
    exit(1)

if argv[1] == '--all':
    for tag in tags['Tags']:
        print(tag['Key'] + ':"' +  tag['Value'] + '"')
    exit(0)

if argv[1] == '--list':
    for tag in tags['Tags']:
        print tag['Key']
    exit(0)

if argv[1] == '--json':
    tagdict = {}
    for tag in tags['Tags']:
        tagdict[tag['Key']] = tag['Value']
    print json.dumps(tagdict)
    exit(0)

# else tag
for tag in tags['Tags']:
    if tag['Key'] == argv[1]:
        print tag['Value']
        exit(0)

print "Tag " + argv[1] + " not found"
exit(1)

