#!/usr/bin/env python

import os
import sys
import argparse

from jinja2 import Template


itype_files = {
    'searchproxy': {
        'reqans': {'log_name': 'searchproxy-reqans-searchproxy', 'streams': 1},
        'access': {'log_name': 'searchproxy-access-searchproxy', 'streams': 1},
    },
    'indexerproxy': {
        'index-disc': {'log_name': 'indexerproxy-index-indexerproxydisc', 'streams': 1},
    },
    'rtyserver': {
        'docfetcher': {'log_name': 'docfetcher-base', 'streams': 1},
        'index': {'log_name': 'index-base', 'streams': 1},
    }
}
additional_files = {
    'stable_refresh': {
        'rtyserver': {
            'timerlog': {'log_name': 'timerlog-rtyserver'},
        }
    },
}


template = Template(
'''network:
    master-addr: "logbroker.yandex.net"
    proto: pq
    tvm-client-id: 2027952
    tvm-server-id: 2001059
    tvm-secret-file: push_client_secret/client_secret
watcher-state: "{{ state_dir }}"
logger:
    mode: [file]
    file: {{ log_dir }}/current-log-pushclient{% if bsconfig_port > 0 %}-{{ bsconfig_port }}{% endif %}
    level: 5
    timeformat: "%d.%m.%Y-%H:%M:%S"
    remote: 0

files:
{% for log_type, log_file in files|dictsort %}
  - name: {{ log_dir }}/current-{{ log_file.log_name }}{% if bsconfig_port > 0 %}-{{ bsconfig_port }}{% endif %}
    {% if log_file.topic %}topic: {{ log_file.topic }}{% else %}topic: /saas/logs/{{ ctype }}/{{ itype }}-{{ log_type }}{% endif %}
    streams: {{ log_file.streams or 1 }}
{% endfor %}
'''
)


def get_ctype():
    try:
        with open('saas_ctype') as f:
            return f.read()
    except IOError:
        if 'CUSTOM_CTYPE' in os.environ:
            return os.environ['CUSTOM_CTYPE']
        else:
            raise RuntimeError('Nor CUSTOM_CTYPE env nor saas_ctype file found')


def store_config(config_content, config_file_name):
    with open(config_file_name, "w") as output_file:
        output_file.write(config_content)


def generate_pushclient_config(args):
    ctype = get_ctype()
    itype = args.itype
    files = itype_files[itype]
    if ctype in additional_files:
        if itype in additional_files[ctype]:
            files.update(additional_files[ctype][itype])
    
    final_content = template.render(
        state_dir=args.state_dir,
        log_dir=args.logs_dir,
        bsconfig_port=args.bsconfig_iport,
        ctype=ctype, 
        itype=itype,
        files=files
    )
    store_config(final_content, args.output_config_file)


def main(sys_args):
    parser = argparse.ArgumentParser(description='Build push-client.conf')
    parser.add_argument('-i', '--itype', dest='itype', metavar='ITYPE', type=str, help='Cluster itype', required=True)
    parser.add_argument('-o', '--output-config-file', dest='output_config_file', metavar='output-config', type=str, help='Output config filename', required=True)
    parser.add_argument('-s', '--state-dir', dest='state_dir', metavar='state-dir', type=str, help='State directory', required=True)
    parser.add_argument('-p', '--push-client-log', dest='push_client_log', metavar='push-client-log', type=str, help='push-client log file name', required=True)
    parser.add_argument('-l', '--logs-dir', dest='logs_dir', metavar='logs-dir', type=str, help='Logs directory', required=True)
    parser.add_argument('--bsconfig-iport', dest='bsconfig_iport', metavar='bsconfig-iport', type=int, help='Bsconfig instance port', required=False)
    parser.add_argument('--bsconfig-idir', dest='bsconfig_idir', metavar='bsconfig-idir', type=str, help='Bsconfig instance dir', required=False)

    args = parser.parse_args(sys_args)
    generate_pushclient_config(args)


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