#!/usr/bin/python
#
# (c) Copyright 2016,2017 Hewlett Packard Enterprise Development LP
# (c) Copyright 2017-2018 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

# Determine which logging profiles apply to the current hosts
#-------------------------------------------------------------------------------
def main():
    module = AnsibleModule(
        argument_spec=dict(
            host            = dict(required=True),                           # inventory_hostname
            hosts           = dict(required=True),                           # verb_hosts
            groups          = dict(required=True),                           # groups
            profiles_dir    = dict(default="roles/logging-common/vars"),     # profile directory
            config_dir      = dict(default="roles/kronos-logrotation/vars")  # config directory
        ),
        supports_check_mode=False
    )

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

        profiles = {}
        uf_profiles = {}  # unfiltered profiles

        # Load rotation_config from a file
        with open(os.path.join(params.config_dir, 'rotation_config.yml'), 'r') as config_file:
            rotation_config = yaml.load(config_file)

        # Load all logging profiles from the specified directory
        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']
                    uf_profiles[os.path.basename(filename)] = profile

        for key, profile in uf_profiles.iteritems():
            group_regexps = profile['hosts'].split(':')

            # Filter possible host groups down to only those that are active
            # e.g. LOG-SVR matches LOG-SVR-ccp
            matched_groups = []
            for group in params.hosts.values():
                for group_regexp in group_regexps:
                    if re.search(group_regexp, group):
                        matched_groups.append(group)
                        break

            for group in matched_groups:
                # Map into groups to get list of hosts to match against
                if group in params.groups and params.host in params.groups[group]:
                    profiles[key] = profile
                    break

    except Exception, e:
        module.fail_json(msg="{}".format(e))
    finally:
        module.exit_json(result=profiles, rotation_config=rotation_config)

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