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

import xbow
import boto3
import subprocess
import os, yaml
from xbow.instances import get_by_name

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

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

def launch_notebook(name=None, instance_id=None, region=None):
    """
    Launches  a Jupyter notebook on the 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 = get_by_name(name, region)
    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 {} -L 8888:localhost:8888 {}@{} -oStrictHostKeyChecking=no jupyter notebook --no-browser --port=8888".format(pem_file, username, instance.public_dns_name)
        result = subprocess.call(launch_command, shell=True)
try:
    result = launch_notebook(name=cfg['scheduler_name'])
except ValueError as e:
    print(e)
