#!/usr/bin/python
# -*- coding: utf-8 -*-
from boto.dynamodb2.fields import HashKey, RangeKey
from boto.dynamodb2.table import Table
from boto.ec2.blockdevicemapping import BlockDeviceType, BlockDeviceMapping
from boto.exception import JSONResponseError
from datetime import datetime
from pprint import pprint
from time import sleep
import base64
import boto.ec2
import json
import sys

# Amazon Linux AMI 2013.09.2 [us-east-1]
paravirtual_ami = 'ami-83e4bcea'
# Amazon Linux AMI (HVM) 2013.09.2 [us-east-1]
hvm_ami = 'ami-d1bfe4b8'

# Confirm ~/.boto exists and contains credentials
region = 'us-east-1'
k_name = 'iomz@cisco-macbook'
s_grp = 'default'

# Iperf server info
iperfs = {
    'i-39ceba17' : 'us-east-1',
    'i-3250c43a' : 'us-west-2'
}

def start_benchmark_instance(conn, instance, u_data, bdm):
    if 'paravirtual' in instance:
        ami = paravirtual_ami
    else:
        ami = hvm_ami
    if 'ebs' in instance:
        ebs = True
    else:
        ebs = False
    size = instance.split('_')[0]

    try:
        i = conn.run_instances(
            ami,
            instance_type=size,
            key_name=k_name,
            max_count=1,
            security_groups=[s_grp],
            user_data=u_data,
            ebs_optimized=ebs,
            block_device_map=bdm
            ).instances[0]
    except:
        print "%s launch failed" % (instance)
        return None, None
    print "{0}({1}) launched at: {2}".format(instance, i.id, i.launch_time)
    sleep(5) # Wait before tagging
    conn.create_tags([i.id], {"Name": instance})
    return instance, i.id

def wait_until_next(step, minute):
    t = datetime.today()
    if minute > t.minute:
        if t.hour == 23:
            if step == 0:
                day = t.day
                hour = 23
            elif step == 1:
                day = t.day + 1
                hour = 0
        elif t.hour != 23: