#!/usr/bin/python3

import boto3
import sys, os
import random
import time

def getami(glob):
    return [
        i for i in ec2.images.filter(
            Filters=[ {'Name': 'name', 'Values': [glob]} ]
        )
    ]


def getvpc(glob):
	return [
		i for i in ec2.vpcs.filter(
			Filters=[ {'Name': 'tag:Name', 'Values': [glob]} ]
		)
	]

def create_eip_alloc_id():
	my_dict = 'abcdefghijklmnopqrstuvwxyz0123456789'
	alloc_id = "eipalloc-"
	alloc_id += ''.join(random.choice(my_dict) for i in range(7))
	return alloc_id

def associate_eip_with_instance(instance_id, allocation_id):

	alloc_id = create_eip_alloc_id()
	address = ec2.VpcAddress(allocation_id)
	address.associate(InstanceId=instance_id)
	return address.public_ip

INSTANCE_STATES = {'pending': 0, 'running':16, 'shutting_down':32, 'terminated': 48, 'stopping': 64, 'stopped': 80}

profile 	= 'default'
my_key		= 'vijayaws'
instance_name	= 'vijayxmstest'
owner_email 	= 'vijay.shastry@citrix.com'
vpc_filter 	= 'XMS_vijay*'
ami_filter	= 'XMS_Aston_Martin*'
build_id 	= '10.3.6.124'
eip_id 		= 'eipalloc-15da6b70'


network_params 	= {}
s = boto3.session.Session(profile_name = profile)
ec2 = s.resource('ec2')
ami_list = getami(ami_filter)

my_ami = None 
for ami in ami_list:
	if build_id in ami.name:
		my_ami = ami
		break

debug = 0
if debug:
	print(my_ami.name + ': ' + my_ami.id)
network_params['ami_id'] = my_ami.id

my_subnet_id = ''
vpc_list = getvpc(vpc_filter)
my_vpc = None
for vpc in vpc_list:
	if debug:
		print(vpc)
	for tag in vpc.tags:
		if 'Name' in tag['Key']:
			if debug:
				print(tag['Key'], tag['Value'], vpc.id)
			network_params['vpc_id'] = vpc.id

			subnets = list(vpc.subnets.all())
			if debug:
				for subnet in subnets:	
					print(subnet.cidr_block +': ' + subnet.id)
			network_params['subnet_id'] = subnets[0].id
			break


sg_filter = 'launch'

vpc = ec2.Vpc(network_params['vpc_id'])
sg_list = vpc.security_groups.all()
for group in sg_list:
	name = group.group_name
	if sg_filter in name.lower():
		network_params['sg_id'] = group.group_id
		break


print(network_params)

instance_list = ec2.create_instances(
    DryRun=False,
    ImageId=network_params['ami_id'],
    MinCount=1,
    MaxCount=1,
    KeyName=my_key,
    SecurityGroupIds=[
        network_params['sg_id']
    ],
    InstanceType='m3.medium',
    SubnetId=network_params['subnet_id'],
    DisableApiTermination=False,
    InstanceInitiatedShutdownBehavior='stop',
    EbsOptimized=False
)

n_instances = 0
my_instance = None 
for instance in instance_list:

	print('Instance ID: %s'%(instance.instance_id))
	my_instance  = instance

	tag = instance.create_tags(
		DryRun=False,
		Tags=[
			{
				'Key': 'Name',
				'Value': instance_name
			},
			{
				'Key': 'Owner',
				'Value': owner_email
			}
		]
	)


	n_instances+=1
	if n_instances >= 0:
		break	

state = my_instance.state
while state['Code'] != INSTANCE_STATES['running']:

	print('Sleeping 30 seconds....')	
	time.sleep(30)
	my_instance.reload()
	state = my_instance.state
	print('Instance: %s is in State: %s'%(my_instance.instance_id, state))

elastic_ip = associate_eip_with_instance(instance.instance_id, eip_id)
print('Instance: %s has Elastic IP: %s'%(my_instance.instance_id, elastic_ip))

sys.exit(0)


