#!/usr/bin/env python2
from getpass import getuser
import os
import sys
import socket
import fileinput
from gridadmin_tools.utils import make_parser, make_request
from gridadmin_tools.tools import run_system_diag, get_nw_interfaces

sys.stderr = sys.stdout


def register_server(address, interface="eth0", token=None,
                    port=80, conf_file=None, secure=False, namespace=None, rack=None, file=None, monitoring=False):
    route = 'api/servers/fts/registration'

    ip_addr = None
    nwi = get_nw_interfaces(run_system_diag())
    for iface in nwi:
        if iface['device'] == interface:
            ip_addr = iface['ipv4_addr']
            break
    if not ip_addr:
        raise ValueError("Invalid interface %s" % interface)

    data = dict(host=socket.gethostname().split('.')[0], fqdn=socket.getfqdn())
    if interface:
        data['primary_if'] = ip_addr
    if token:
        data['token'] = token
    if rack:
        data['rack'] = rack
    if conf_file:
        data['conf_file'] = conf_file
    if monitoring:
        data['monitoring'] = True
    dsecure = 'ssl' if secure else 'http'
    data['dashboard_addr'] = "%s:%s:%s" % (dsecure, address, port)

    res = make_request(address, port, route, data, secure=secure)
    return res.json(), data


def do_discover(host, port=80, key=None, secure=False, namespace=None, puppet_path=None):
    route = 'api/namespaces/_null/jobs/dsk'
    data = dict()
    if key:
        data['key'] = key
        data['host'] = socket.gethostname().split('.')[0]
        data['fqdn'] = socket.getfqdn()
    else:
        raise KeyError('No transaction key received')

    # Namespace import V2
    if namespace and puppet_path:
        data['namespace'] = namespace
        data['puppet_path'] = puppet_path

    res = make_request(host, port, route, data, secure=secure)
    return res.status_code, data['host']


def print_table_row(values, l):
    string = " | ".join(values)
    l = l - len(string) - 2
    print("| %s%s|" % (string, ' '*l))


def print_table(rows):
    l = []
    for r in rows:
        l.append(len("".join(r)))


def main():

    (args, options) = make_parser([
        ('interface', 'primary interface | eth0', False),
        ('address', 'dashboard IP Address', True),
        ('port', 'dashboard server port | 80', False),
        ('conf_file', 'path to puppet file to import', False),
        ('namespace', 'namespace to deploy', False),
        (':monitoring', 'allow monitoring management by the dashboard', False),
        ('rack', 'rack to deploy onto', False),
        ('token', 'server exchange token', False),
        ('file', 'path to authorized_keys', False),
        (':secure', 'use HTTPS to access the API', False)
    ], remove_null=True)

    ssh_file = None

    data, req = register_server(**args)
    ssh_key = data.get('ssh_key', None)
    transac_key = data.get('transac_key', None)

    path = ssh_file if ssh_file else '/home/%s/.ssh/authorized_keys' % getuser()

    if not os.path.exists(path):
        ValueError("Path %s for authorized_keys is not valid" % path)

    if args.get('conf_file', None) and not os.path.exists(args['conf_file']):
        ValueError("Couldn't find puppet file at %s" % args['conf_file'])

    PRE = "# === THIS PART HAS BEEN GENERATED AUTOMATICALLY\
           BY THE OPENIO DASHBOARD DEPLOYMENT SYSTEM === #"
    KEY = ssh_key
    POST = "# === -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\
            -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= === #"

    next = 0
    for line in fileinput.input(path, inplace=1):
        if next == 1:
            line = KEY
            next += 1
        if line == PRE:
            next += 1

    if next == 0:
        with open(path, "a") as f:
            f.write("%s\n%s\n%s" % (PRE, KEY, POST))

    namespace = args.get('namespace', None)
    conf_file = args.get('conf_file', None)

    res = do_discover(args['address'], args['port'], transac_key,
                      args['secure'], namespace, conf_file)
    if res[0] == 200:
        print('+----------  Summary  ----------------------------+')
        print_table_row(('Hostname', res[1]), 50)
        print_table_row(('Interface', args['interface'], req['primary_if']), 50)
        if namespace:
            print_table_row(('Importing from file', namespace), 50)
        print('+------------------------------------------------ +')


if __name__ == "__main__":
    main()
