import re, boto3, sys, paramiko, time

def find_asg(asgClient, asgName):
    suggestedAsgs = []
    asgs = asgClient.describe_auto_scaling_groups()
    print "Suggested ASG names:"
    for asg in asgs['AutoScalingGroups']:
        suggestedName = re.search(asgName, asg['AutoScalingGroupName'])
        if suggestedName != None:
            print suggestedName.string
    exit(1)


def complain(message):
    #prints complain message and quits program
    mention(message)

def mention(message):
    #prints complain message, does not quit
    sys.stderr.write(message + "\n")

def run_command(user, password, command, asgName, sleep):
    asg = boto3.client('autoscaling')
    ec2 = boto3.client('ec2')
    autoScalingGroups = asg.describe_auto_scaling_groups(AutoScalingGroupNames=[asgName])

    if len(autoScalingGroups['AutoScalingGroups']) == 0:
        find_asg(asg, asgName)

    if autoScalingGroups['AutoScalingGroups'][0]['MinSize'] == autoScalingGroups['AutoScalingGroups'][0]['DesiredCapacity']:
        print "Instance will not enter Standby because MinSize is not less than Desired Capacity "
        exit(1)

    instanceIds = []
    for instance in autoScalingGroups['AutoScalingGroups'][0]['Instances']:
        instanceIds.append(instance['InstanceId'])

    instances = ec2.describe_instances(InstanceIds=instanceIds, Filters=[{
        'Name': 'instance-state-name',
        'Values': ['running']
    }])
    for instance in instances['Reservations']:
        print "Running command on %s" % instance['Instances'][0]['InstanceId']
        asg.enter_standby(InstanceIds=[instance['Instances'][0]['InstanceId']], AutoScalingGroupName=asgName, ShouldDecrementDesiredCapacity=True)
        time.sleep(sleep)
        privateIpAddress = instance['Instances'][0]['PrivateIpAddress']
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(privateIpAddress, username=user, password=password)
        try:
            stdin, stdout, stderr = ssh.exec_command(command)
            print "read stdout"
            print stdout.readlines()
            print "read stderr"
            print stderr.readlines()
        except:
            message = "command failed on %s" %privateIpAddress
            complain(message)
        ssh.close()
        asg.exit_standby(InstanceIds=[instance['Instances'][0]['InstanceId']], AutoScalingGroupName=asgName)

