#!/usr/bin/env python

# Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
# Copyright 2016 Red Hat, Inc.
# All Rights Reserved.
#
# 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.

# TODO(mandre)
# If possible get info from ironic for hosts prior to deployment

from __future__ import print_function

import os
import sys
import json

from heatclient import client as heat_client
from oslo_config import cfg
from six.moves import configparser

from tripleo_validations.inventory import TripleoInventory
from tripleo_validations.utils import get_auth_session


opts = [
    cfg.StrOpt('host', help='List details about the specific host'),
    cfg.BoolOpt('list', help='List active hosts'),
    cfg.StrOpt('static-inventory', help=('output the active hosts '
                                         'to a static inventory '
                                         'file.')),
    cfg.StrOpt('username', default=os.environ.get('OS_USERNAME')),
    cfg.StrOpt('password', default=os.environ.get('OS_PASSWORD')),
    cfg.StrOpt('auth-url', default=os.environ.get('OS_AUTH_URL')),
    cfg.StrOpt('auth-token', default=os.environ.get('OS_AUTH_TOKEN')),
    cfg.StrOpt('project-name', default=os.environ.get(
        'OS_PROJECT_NAME', os.environ.get('OS_TENANT_NAME'))),
    cfg.StrOpt('cacert', default=os.environ.get('OS_CACERT')),
    cfg.StrOpt('plan', default=os.environ.get('TRIPLEO_PLAN_NAME')),
    cfg.StrOpt('ansible_ssh_user', default=os.environ.get('ANSIBLE_SSH_USER',
        'heat-admin')),
]


def _parse_config():
    default_config = os.environ.get('TRIPLEO_INVENTORY_CONFIG')
    if default_config:
        default_config = [default_config]

    configs = cfg.ConfigOpts()
    configs.register_cli_opts(opts)
    configs(prog='tripleo-ansible-inventory',
            default_config_files=default_config)
    if configs.auth_url is None:
        print('ERROR: auth-url not defined and OS_AUTH_URL environment '
              'variable missing, unable to proceed.', file=sys.stderr)
        sys.exit(1)
    if '/v2.0' in configs.auth_url:
        configs.auth_url = configs.auth_url.replace('/v2.0', '/v3')
    if not configs.plan:
        configs.plan = 'overcloud'
    return configs


def write_static_inventory(inventory_file_path, inventory):
    with open(inventory_file_path, 'w') as inventory_file:
        config = configparser.ConfigParser(allow_no_value=True)
        # Keep case formating.
        config.optionxform = str
        for section_name, section in inventory.items():
            # NOTE(jaosorior): The section might be a list containing the
            # explicit list of nodes or a dict with several subsections. So
            # if it's a list, we process that and continue to the next
            # section.
            if isinstance(section, list):
                config.add_section(section_name)
                for host in section:
                    config.set(section_name, host)
                continue
            if 'hosts' in section:
                config.add_section(section_name)
                for host in section['hosts']:
                    config.set(section_name, host)
            if 'children' in section:
                children_section_name = "%s:%s" % (section_name, 'children')
                config.add_section(children_section_name)
                for child in section['children']:
                    config.set(children_section_name, child)
            if 'vars' in section:
                vars_section_name = "%s:%s" % (section_name, 'vars')
                config.add_section(vars_section_name)
                for var, value in section['vars'].items():
                    if value != None:
                        config.set(vars_section_name, var, value)
        config.write(inventory_file)


def main():
    configs = _parse_config()
    session = get_auth_session(configs.auth_url,
                               configs.username,
                               configs.project_name,
                               configs.password,
                               configs.auth_token,
                               configs.cacert)
    hclient = heat_client.Client('1', session=session)
    inventory = TripleoInventory(configs,
                                 session,
                                 hclient)
    if configs.list or configs.static_inventory:
        try:
            inventory_list = inventory.list()
            if configs.list:
                print(json.dumps(inventory_list))
            elif configs.static_inventory:
                write_static_inventory(configs.static_inventory,
                                       inventory_list)
        except Exception as e:
            print("Error creating inventory: {}".format(e.message),
                  file=sys.stderr)
            sys.exit(1)
    elif configs.host:
        print(json.dumps(inventory.host()))
    sys.exit(0)


if __name__ == '__main__':
    main()
