#!/usr/bin/python
#
# (c) Copyright 2016 Hewlett Packard Enterprise Development LP
# (c) Copyright 2017 SUSE LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
import re
import os
import yaml

# Construct directory monitoring configuration for profiles
#-------------------------------------------------------------------------------
def main():
    module = AnsibleModule(
        argument_spec=dict(
            profiles_dir = dict(default="roles/logging-common/vars")
        ),
        supports_check_mode=False
    )

    try:
        params = type('Params', (), module.params)

        # Get profiles from profiles directory
        profiles = {}
        for filename in sorted(os.listdir(params.profiles_dir)):
            if filename.endswith("-clr.yml"):
                with open(os.path.join(params.profiles_dir, filename), 'r') as strm:
                    profile = yaml.load(strm)['sub_service']
                    profiles[profile['name']] = profile

        # Generate monitoring configuration for profile ensuring uniqueness
        result = {}
        for profile in profiles.values():
            if 'monitoring' in profile and profile['monitoring']['enabled']:
                result[profile['monitoring']['logging_dir']] = {
                    'name': profile['monitoring']['external_name'],
                    'directory': profile['monitoring']['logging_dir']
                }

    except Exception, e:
        module.fail_json(msg="{}".format(e))
    finally:
        # Return list of dictionaries sorted by directory
        module.exit_json(result=sorted(result.values(), key=lambda x: x['directory']))

# Execute main as an Ansible module
#-------------------------------------------------------------------------------
from ansible.module_utils.basic import *
if __name__ == '__main__':
    main()
