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

"""
Синхронизирует данные в zookeeper в виде /ppcinv/fqdns, /ppcinv/hosts
"""

import argparse
import getpass
import sys
sys.path.extend(['share/pyshared', '/usr/local/share/pyshared'])

from ppcinv.helpers import *
from ppcinv.external_sources import *
from ppcinv.svn_storage import PPCInvSvnStorage
from ppcinv.zk_storage import *

if __name__ == '__main__':
    parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=__doc__)
    parser.add_argument('--log-level', type=str, required=False, choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], default='ERROR', help='Logging level')
    parser.add_argument('--log-file', type=str, required=False, default=None, help='Log file')
    parser.add_argument('--zk-hosts', type=str, required=True, help='Comma separated zookeeper hosts list')
    parser.add_argument('--db-path', type=str, required=False, default='~/ppcinv-db', help='Path to db with hosts metadata')
    parser.add_argument('--cluster-str-id', type=str, nargs='+', required=False, default=None, help='Update only specified clusters, like "direct/production/scripts-java"')
    args = parser.parse_args()

    logger = init_root_logger(args)

    svn = PPCInvSvnStorage(db_path=os.path.expanduser(args.db_path), svn_user=getpass.getuser(), svn_scheme='svn+ssh', svn_host='svn.yandex.ru', svn_path='direct-utils/ppcinv-db', cleanup_existing=True)
    clusters = svn.load_clusters()

    for cluster_conf in clusters:
        cluster_str_id = '/'.join(get_cluster_path_list(cluster_conf))
        if args.cluster_str_id and (cluster_str_id not in args.cluster_str_id):
            logger.debug('Skipping cluster ' + cluster_str_id)
            continue

        svn_hosts = svn.load_hosts(cluster_conf)
        zk_hosts = zk_load_hosts(cluster_conf, args.zk_hosts)

        logging.debug('hosts: %s\n old_hosts: %s\n' % (str(svn_hosts), str(zk_hosts)))

        actions = cluster_hosts_get_merge_actions(svn_hosts, zk_hosts)

        logging.debug('actions: %s\n' % (str(actions),))
        zk_merge_hosts(actions, args.zk_hosts)

