#!/usr/bin/env python2
from gridadmin_tools.utils import make_parser, make_request
from gridadmin_tools.tools import run_system_diag, get_system_info,\
                                get_nw_interfaces, get_disk_info
# from gridadmin_tools.migration import Migration
import sys
import traceback

sys.stderr = sys.stdout


def main():
    (args, options) = make_parser([
        ('ip', 'Dashboard IP address', True),
        ('port', 'Dashboard port', False),
        ('key', 'Dashboard transaction key', True),
        ('namespace', 'Namespace to migrate on the dashboard', False),
        ('conf_file', 'Path to the puppet configuration file', False),
        ('location', 'Path to location file that defines namespace paths', False),
        (':secure', 'use HTTPS to access the API', False)
    ])

    stats = run_system_diag()
    devices, mounts = get_disk_info(stats)

    fqdn = stats.get('ansible_fqdn', None)
    hostname = stats.get('ansible_hostname', None)

    key = args.get('key', None)
    data = dict(
        key=key,
        fqdn=fqdn,
        hostname=hostname,
        sysinfo=get_system_info(stats),
        network=get_nw_interfaces(stats),
        devices=devices,
        mounts=mounts
    )

    ROUTE = "api/servers/"
    ip = args.get('ip', None)
    port = args.get('port', None)
    secure = args.get('secure', False)
    make_request(ip, port, ROUTE, data, secure)

    # Namespace import V2
    if args.get('namespace', None) and args.get('conf_file', None):
        req_body = None
        with open(args['conf_file']) as f:
            req_body = dict(puppet=f.read().rstrip())
        route = 'api/v2/namespaces/%s/servers/%s/import' % (args['namespace'], hostname)
        make_request(ip, port, route, req_body, secure=secure)


try:
    main()
except Exception as e:
    print "An exception occured while performing discovery job"
    print traceback.format_exc(e)
    print "Discovery has failed"
    exit(2)
