#!/usr/bin/env python2

import os
import sys
import subprocess
import yaml

CONFIG = '/etc/yandex/statbox-push-client/push-client.yaml'
CONFIG_OLD = '/etc/yandex/statbox-push-client/push-client.yaml.old'

YANDEX_ENV_FILE = '/etc/yandex/environment.type'
YANDEX_ENV_SANDOX_FILE = '/etc/yandex/environment.direct_sandbox'
YANDEX_ENV_DEFAULT = 'development'

DEFAULT_TEMPLATE_NETWORK = {
	'network': {	'master-addr': 'logbroker-pre.yandex.net',
			'proto': 'pq',
			'tvm-server-id': 2001059,
         		'tvm-client-id': 2001806,
         		'tvm-secret-file': '/etc/direct-tokens/tvm2_direct-push-client'
         }
}

DEFAULT_TEMPLATE_WATCHER = {
         'watcher': {'state': '/local/cache/push-client'}
}

DEFAULT_TEMPLATE_FILES = {
         'files': []
}

logbroker_servers = {
        'production': 'logbroker.yandex.net',
        'sandbox': 'logbroker.yandex.net',
        'testing': 'logbroker-pre.yandex.net',
        'development': 'logbroker-pre.yandex.net'
}


def create_mkdirs(path):
    if not os.path.exists(path): 
        os.makedirs(path)
    return

def saved_old_config():
    if os.path.exists(CONFIG):
        os.rename(CONFIG, CONFIG_OLD)
    return

def get_yandex_env():
    if os.path.exists(YANDEX_ENV_SANDOX_FILE):
        return open(YANDEX_ENV_SANDOX_FILE).read().strip().lower()
    if os.path.exists(YANDEX_ENV_FILE):
        return open(YANDEX_ENV_FILE).read().strip().lower()
    return YANDEX_ENV_DEFAULT

def generate_audit_config(instance):
    template_audit = {
                      'name': '/opt/mysql.{0}/data/audit.log'.format(instance),
                      'ident': 'direct',
                      'log_type': 'mysql-audit-log'
    }
    return template_audit

def generate_ptkill_config(instance):
    template_ptkill = {
                      'name': '/var/log/mysql.{0}/ptkill-query.log'.format(instance),
                      'ident': 'direct',
                      'log_type': 'mysql-ptkill-log'
    }
    return template_ptkill

def generate_files_config():
    result = DEFAULT_TEMPLATE_FILES
    try:
        cmd = ['/usr/local/bin/lm', '--complete']
        proc = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
        stdout, stderr = proc.communicate()
        if len(stderr):
            raise ValueError('error msg: {0}'.format(stderr))
        if len(stdout) == 0:
            raise ValueError('empty instances')
    except Exception as err:
        print '[{0}] {1}'.format(' '.join(cmd), err)
    else:
        instances = stdout.split()
        result['files'].extend([ generate_audit_config(i) for i in instances ])
        result['files'].extend([ generate_ptkill_config(i) for i in instances ])
    return result

if __name__ == '__main__':
    enviroment = get_yandex_env()
    head = '#this is config generated automaticaly script {0}\n---'.format(sys.argv[0])
    template_network = DEFAULT_TEMPLATE_NETWORK
    if logbroker_servers.has_key(enviroment):
        template_network['network']['master-addr'] = logbroker_servers[enviroment]
    template_watcher = DEFAULT_TEMPLATE_WATCHER
    template_files = generate_files_config()
    y = lambda x: yaml.dump(x, default_flow_style=False)
    create_mkdirs(os.path.dirname(CONFIG))
    saved_old_config()
    with open(CONFIG, 'w') as fd:
        data = '\n'.join([head, y(template_network), y(template_watcher), y(template_files)])
        fd.write(data)
