#!/usr/bin/env python
"""
Load hivemind services structure from a directory tree with files
in it containing rules information.
"""
import os
import argparse

import yaml
from pymongo import MongoClient

from genisys.web.model import MongoStorage


def traverse_dirs(structure_path):
    for dirpath, dirnames, filenames in os.walk(structure_path):
        secpath = os.path.relpath(dirpath, structure_path).replace('/', '.')
        if secpath == '.':
            continue
        rulefilenames = sorted([os.path.join(dirpath, filename)
                                for filename in filenames])
        yield secpath, rulefilenames


def create_section(storage, username, secpath, rulefilenames):
    if '.' in secpath:
        parent_path, secname = secpath.rsplit('.', 1)
    else:
        parent_path = ''
        secname = secpath
    parent = storage.get_section_subtree(parent_path, max_depth=0)
    storage.create_section(username, parent_path, parent['revision'],
                           secname, desc='', owners=[], stype='yaml',
                           stype_options=None)


def create_rule(storage, username, secpath, rulefile):
    rule_info = yaml.load(open(rulefile))
    config_source = rule_info['config'].strip()
    if rule_info.get('all_hosts'):
        selector = None
    else:
        selector = rule_info['selector'].strip()
        assert selector
    config = yaml.load(config_source)
    desc = ''
    rulename = rule_info['name'].strip()
    section = storage.get_section_subtree(secpath, max_depth=0)
    storage.create_rule(username, secpath, old_revision=section['revision'],
                        parent_rule=None, rulename=rulename, desc=desc,
                        editors=[], selector=selector, config=config,
                        config_source=config_source)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('-u', '--user', required=True,
                        help="Name of user on whose behalf new sections will "
                             "be created. Must be one of root section owners.")
    parser.add_argument('structure_path')
    parser.add_argument('--mongo-uri', '-m', default='mongodb://127.0.0.1',
                        help='mongodb connection uri')
    parser.add_argument('--db-name', '-n', default='genisys',
                        help='database name (defaults to "genisys")')
    args = parser.parse_args()
    mongo_client = MongoClient(args.mongo_uri)
    storage = MongoStorage(mongo_client, args.db_name)
    for secpath, rulefilenames in traverse_dirs(args.structure_path):
        create_section(storage, args.user, secpath, rulefilenames)
        for rulefile in rulefilenames:
            create_rule(storage, args.user, secpath, rulefile)


if __name__ == '__main__':
    main()
