#!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')


        mount_point = cfg['mount_point']
        cwd = os.getcwd()
        base = os.path.basename(cwd)
        pem_file = '{}/{}.pem'.format(xbow.XBOW_CONFIGDIR, name)
        cmd_change = 'export PS1="\[\e[34;1m\]\u\[\e[0m\]@\[\e[32;1m\]xbow\[\e[0m\]:\w> "'

        launch_command = "ssh -t -i {} {}@{} -oStrictHostKeyChecking=no 'cd {}/{} && exec bash -l'".format(pem_file, username, instance.public_dns_name, mount_point, base)
        #print(launch_command)
        subprocess.call(launch_command, shell=True)
     

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