#!/usr/bin/env python
#
# Copyright 2011-2017 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Refer to the README and COPYING files for full details of the license
#
# Based on vdsm project: lib/vdsm/config.py.in
import argparse
import os
import glob

from six.moves import configparser


def read_configs(cfg, sosreport_path):
    """This function is reading config files in a specific scheme

    The function reads - for one component - config files from several
    locations and in addition it is also reading configuration snippets
    from drop-in directories.
    This scheme allows to store the vendor provided (default) configuration
    in a different directory, and override it using either defaults from
    other packages which can then be put into the vendor drop-in dir,
    or users can overwrite the defaults, by placing a complete or partial
    configuration file into /etc or a drop-in directory.
    """
    _DROPPIN_BASES = (
        sosreport_path + "/usr/lib/",
        sosreport_path + "/run/",
        sosreport_path + "/etc"
    )

    cfg.read(sosreport_path + "/etc/vdsm/vdsm.conf")

    dropins = []
    for path in _DROPPIN_BASES:
        pattern = os.path.join(
            sosreport_path,
            'vdsm',
            'vdsm' + '.conf.d',
            '*.conf'
        )
        dropins.extend(glob.glob(pattern))

    dropins.sort(key=os.path.basename)
    cfg.read(dropins)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter
    )

    parser.add_argument('--sos-report-path',
                        dest='path_sosreport',
                        help='path for sosreport')

    output = ""
    args = parser.parse_args()

    if args.path_sosreport:
        vdsm_config_from_sosreport = configparser.ConfigParser()
        read_configs(vdsm_config_from_sosreport, args.path_sosreport)

        for section_name in vdsm_config_from_sosreport.sections():
            for name, value in vdsm_config_from_sosreport.items(section_name):
                if 'ssl' in name and value == 'true':
                    continue
                elif 'management_port' in name and value == '54321':
                    continue
                output+='%s=%s ' % (name, value)

        if output:
            print(output)
