#!/usr/local/bin/python3
import boto3
import sys, subprocess
import pprint 

keyPath = " -i /Users/path/.ssh/"
user = "ec2-user"
userBis = "ubuntu"
liste = []

ec2 = boto3.resource('ec2')

if len(sys.argv) == 2:
    my_tag = '*' + str(sys.argv[1]) + '*'
else:
    my_tag = "*"

instances = ec2.instances.filter(
    Filters=[{'Name': 'instance-state-name', 'Values': ['running']},{'Name': 'tag:Name', 'Values': [my_tag]}])

for instance in instances:
    for tags in instance.tags:
        if tags["Key"] == 'Name':
            instancename = tags["Value"]
            tempo = instancename + "~" + str(instance.public_ip_address) + "~" +  str(instance.key_name)
            liste.append(tempo)

if len(liste) == 1:
    try:
        subprocess.check_call(['ssh '+user+'@'+liste[0].split("~")[1]+keyPath+liste[0].split("~")[2]], shell=True)
    except:
        subprocess.call(['ssh '+userBis+'@'+liste[0].split("~")[1]+keyPath+liste[0].split("~")[2]], shell=True)
else:
    if len(liste) % 2 != 0:
        liste.append(" ")
    split = int(len(liste)/2)
    print(split)
    l1 = liste[0:int(split)]
    l2 = liste[int(split):]
    i = 0
    for key, value in zip(l1,l2):
        print("[{2}]-> {0:<50s} [{3}]-> {1}".format(key.split("~")[0], value.split("~")[0], str(i), str(i+1)))
        i = i+2
    server = int(input('Choose a server [0] : '))

    if (int(server) % 2 == 0):
        try:
            print('ssh -v '+user+'@'+l1[int(server/2)].split("~")[1]+keyPath+l1[int(server/2)].split("~")[2])
            subprocess.check_call(['ssh -v'+user+'@'+l1[int(server/2)].split("~")[1]+keyPath+l1[int(server/2)].split("~")[2]])
        except:
            subprocess.call(['ssh '+userBis+'@'+l1[int(server/2)].split("~")[1]+keyPath+l1[int(server/2)].split("~")[2]], shell=True)
    else:
        try:
            subprocess.check_call(['ssh '+user+'@'+l2[int(server/2)].split("~")[1]+keyPath+l2[int(server/2)].split("~")[2]], shell=True)
        except:
            subprocess.call(['ssh '+userBis+'@'+l2[int(server/2)].split("~")[1]+keyPath+l2[int(server/2)].split("~")[2]], shell=True)
