#!/usr/bin/env python
from __future__ import print_function

import xbow
import boto3
import subprocess
import os, yaml

cfg_file = os.path.join(xbow.XBOW_CONFIGDIR, "settings.yml")

with open(cfg_file, 'r') as ymlfile:
    cfg = yaml.load(ymlfile)

def login_instance(name=None, instance_id=None, region=None):
    """
    returns a string that could be used to log in to the selected instance
    """
    if name is None and instance_id is None:
        raise ValueError('Error - either the name or instance_id must be provided')

    ec2 = boto3.resource('ec2', region_name=region)
    if name is not None:
        instances = list(ec2.instances.filter(Filters=[{'Name': 'key-name', 'Values': [name]}, {'Name': 'instance-state-name', 'Values': ['running']}]))
    else:
        instances = list(ec2.instances.filter(InstanceIds=[instance_id]))

    if len(instances) == 0:
        raise ValueError('Error - no such instance')
    elif len(instances) > 1:
        raise ValueError('Error - more than one instance has that name')
    else:
        instance = instances[0]
        name = instance.key_name
        username = None
        if instance.tags is not None:
            for tag in instance.tags:
                if tag['Key'] == 'username':
                    username = tag['Value']
        if username is None:
            print('Warning: cannot determine username, assuming it is ubuntu')

        pem_file = '{}/{}.pem'.format(xbow.XBOW_CONFIGDIR, name)
        launch_command = 'ssh -i {} {}@{} -oStrictHostKeyChecking=no'.format(pem_file, username, instance.public_dns_name)
        #return launch_command
	#print(launch_command)
	subprocess.call(launch_command, shell=True)
     

try:
    result = login_instance(name=cfg['scheduler_name'])
except ValueError as e:
    print(e)
