#!/opt/cloudlinux/venv/bin/python3 -bb
# -*- coding: utf-8 -*-

# Copyright © Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2019 All Rights Reserved
#
# Licensed under CLOUD LINUX LICENSE AGREEMENT
# http://cloudlinux.com/docs/LICENSE.TXT

from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import os
import sys

import yaml
from future.utils import iteritems


def merge(source, destination):
    """
    Simple merge dictionaries
    @param `source` dict: what need merge
    @param `destination` dict: where need merge
    """
    for key, value in iteritems(source):
        if isinstance(value, dict):
            # get node or create one
            node = destination.setdefault(key, {})
            merge(value, node)
        else:
            destination[key] = value

    return destination


def main(source_file, original_file, target_file):
    """
    Run script for load and merge yaml locales files
    @param `source_file` str: file with CL locale
    @param `original_file` str: original yaml file with locales.
                                merge source with it
    @param `target_file` str: file for write merged locales
    """
    if not os.path.exists(source_file) or not os.path.exists(original_file) \
            or not os.path.isdir(os.path.dirname(target_file)):
        return 1

    with open(source_file, "r") as f:
        try:
            source_data = yaml.safe_load(f)
        except Exception as e:
            print("New locale file is broken, wasn't merged")
            source_data = {}

    with open(original_file, "r") as f:
        try:
            destination_data = yaml.safe_load(f)
        except Exception as e:
            print("Original locale file is broken, was replaced with new one")
            destination_data = source_data


    result = merge(source_data, destination_data)

    #
    # Valid keywords for the method yaml.dump(data, stream=None, Dumper=Dumper, **kwds)
    # default_style : indicates the style of the scalar. Possible values are None, '', '\'', '"', '|', '>'.
    # default_flow_style :  indicates if a collection is block or flow. The possible values are None, True, False.
    # canonical : if True export tag type to the output file
    # indent :  sets the preferred indentation
    # width : set the preferred line width
    # allow_unicode : allow unicode in output file
    # line_break : specify the line break you need
    # encoding : output encoding, defaults to utf-8
    # explicit_start : if True, adds an explicit start using '-'
    # explicit_end: if True, adds an explicit end using '-'
    # version : version of the YAML parser, tuple (major, minor), supports only major version 1
    #

    yaml_data = yaml.dump(result, default_flow_style=False, default_style='"',
                          allow_unicode=True, width=sys.maxsize)
    with open(target_file, "r") as f:
        exists_data = f.read()

    if yaml_data != exists_data:
        with open(target_file, "w") as f:
            f.write(yaml_data)

    return 0


if "__main__" == __name__:
    if len(sys.argv) < 4:
        print("Usage: {} <source> <original> <target>".format(sys.argv[0]))
        sys.exit(1)

    sys.exit(main(*sys.argv[1:]))
