#!/usr/bin/env python2
import json
import requests
# import logging
import sys
import getopt
from getpass import getuser
import os
import socket
import fileinput
from gridadmin_tools.tools import run_system_diag, get_nw_interfaces


def make_request(url, data={}):
    headers = {'Content-Type': 'application/json'}
    res = requests.post(url, headers=headers, data=json.dumps(data))
    if not res or res.status_code != 200:
        raise Exception('[ERROR] : Server could not be reached')
    return res


def register_server(host, iface="eth0", token=None, port=80, ssl=False):
    PREFIX = str('https') if ssl else str('http')
    BASE_URL = '%s://%s:%s/' % (PREFIX, host, port)
    url = BASE_URL + 'api/servers/fts/registration'
    data = dict()
    ip_addr = None
    nwi = get_nw_interfaces(run_system_diag())
    for interface in nwi:
        if interface['device'] == iface:
            ip_addr = interface['ipv4_addr']
    if not ip_addr:
        print("No such interface: " + iface + ". Specify one with -i")
        sys.exit(2)
    else:
        print("Using " + ip_addr + " as primary IP")
    data['host'] = socket.gethostname()
    if iface:
        data['primary_if'] = ip_addr
    if token:
        data['token'] = token
    try:
        res = make_request(url, data)
    except Exception as e:
        print('[ERROR]: Could not connect to host at', BASE_URL, e)
        sys.exit()
    return res.json()


def initiate_discovery(host, port=80, transac_key=None, ssl=False):
    PREFIX = str('https') if ssl else str('http')
    BASE_URL = '%s://%s:%s/' % (PREFIX, host, port)
    url = BASE_URL + 'api/servers/fts/discovery'
    data = dict()
    if transac_key:
        data['key'] = transac_key
        data['host'] = socket.gethostname()
    else:
        print("[ERROR]: Could not follow up on transaction: no key available.")
        sys.exit()
    try:
        res = make_request(url, data)
    except:
        print('[ERROR]: Could not connect to host at', BASE_URL)
        sys.exit()
    return res.status_code


def main(argv):
    kwargs = dict()
    try:
        opts, args = getopt.getopt(argv, "hsp:t:i:f:", ["iface="])
    except getopt.GetoptError:
        sys.exit('[ERROR] Invalid argument provided')

    ssh_file = None
    for opt, arg in opts:
        if opt in ('-h', '-help'):
            print('Usage: register.py (opts) [host]')
            print('Available options:')
            print(' -h,--help  : print this help menu and exit')
            print(' -p,--port : dashboard server port (default 80)')
            print(' -i,--iface : primary network interface to use')
            print(' -t,--token : server exchange token (if enabled)')
            print(' -f,--file : path to authorized_keys file')
            print(' -s,--secure : use SSL')
            sys.exit()
        elif opt in ('-i', '-iface'):
            kwargs['iface'] = arg
        elif opt in ('-t', '-token'):
            kwargs['token'] = arg
        elif opt in ('-p', '-port'):
            kwargs['port'] = arg
        elif opt in ('-f', '-file'):
            ssh_file = arg
        elif opt in ('-s', '-secure'):
            kwargs['ssl'] = True
        else:
            sys.exit('Invalid option: ', opt)
    if len(args) != 1:
        sys.exit('[ERROR] Please provide dashboard IP/DN (register.py [host])')
    kwargs['host'] = args[0]
    data = register_server(**kwargs)
    ssh_key = data.get('ssh_key', None)
    transac_key = data.get('transac_key', None)

    if ssh_file:
        path = ssh_file
    else:
        path = '/home/'+getuser()+'/.ssh/authorized_keys'
    if not os.path.exists(path):
        print('[ERROR]: Invalid path for ssh_key deployment: '+path)
        print('         Please use -f to specify the location of authorized_keys file')
        sys.exit(2)

    PRE = "# === THIS PART HAS BEEN GENERATED AUTOMATICALLY BY THE OPENIO DASHBOARD DEPLOYMENT SYSTEM === #"
    STR = ssh_key
    POST = "# === -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= === #"
    next = 0

    for line in fileinput.input(path, inplace=1):
        if next == 1:
            line = STR
            next = 2
        if line == PRE:
            next = 1

    if next == 0:
        with open(path, "a") as f:
            f.write(PRE+"\n"+STR+'\n'+POST)

    if kwargs.get('token', False):
        del kwargs['token']
    if kwargs.get('iface', False):
        del kwargs['iface']
    kwargs['transac_key'] = transac_key
    return initiate_discovery(**kwargs)

if __name__ == "__main__":
    main(sys.argv[1:])