#!/usr/bin/env python
# -*- coding: utf-8 -*-

__author__ = 'just@yandex-team.ru'

import socket
import httplib
import json
import sys
import argparse


def main(options):
    #: Simply get machine.properties from conductor
    try:
        conductor_host = 'c.yandex-team.ru'
        conductor_query = '/api/hosts/{fqdn}?format=json'

        backbone = 'disk.yandex.net'
        fastbone = 'fb.disk.yandex.net'

        fqdn = socket.getfqdn()
        fb_fqdn = fqdn.replace(backbone, fastbone)

        try:
            #: address info is ok // using this fqdn as fastbone
            socket.getaddrinfo(fb_fqdn, None)
        except socket.gaierror as e:
            #: host has another fastbone? shit...using backbone as fastbone
            fb_fqdn = fqdn

        conn = httplib.HTTPSConnection(conductor_host, timeout=10)
        conn.request('GET', conductor_query.format(fqdn=fqdn))

        response = conn.getresponse()

        if response.status == 200:
            properties = json.loads(response.read()).pop()
            properties['fastbone_fqdn'] = fb_fqdn

            outfile = open(options.outfile or sys.stdout, 'w')
            for key in ('datacenter', 'root_datacenter', 'group', 'fqdn', 'fastbone_fqdn'):
                value = properties.get(key, 'NULL')
                value = '"{}"'.format(value) if options.outfile.endswith('.conf') else value
                print >> outfile, '{key}={value}'.format(key=key, value=value)
        else:
            raise Exception(response.reason)

    except Exception as e:
        print >> sys.stderr, 'Unhandled exception while getting properties => ', e


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Utility for generating `/etc/yandex/machine.properties`'
    )

    #: Basic argument => debugging
    flagged = parser.add_argument_group('Boolean flags arguments')
    flagged.add_argument('--debug', '-d', dest='debug', help='Enable debugging', action='store_true', required=False)

    arguments = parser.add_argument_group('Named arguments')
    arguments.add_argument(
        '-O',
        help='Output filename',
        type=str,
        dest='outfile',
        required=True,
        metavar='`machine.properties` location'
    )

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    options = parser.parse_args()
    main(options)
