#!/usr/bin/python
# Copyright 2015 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.

import os
import subprocess
import tempfile

import pystache

from instack_undercloud import undercloud

renderer = pystache.Renderer()
template = os.path.join(os.path.dirname(__file__),
                        '..',
                        'puppet-stack-config.yaml.template')

# Only variables that are not oslo.config opts need to be added here
context = {
    'INSPECTION_COLLECTORS': os.environ['INSPECTION_COLLECTORS'],
    'INSPECTION_KERNEL_ARGS': os.environ['INSPECTION_KERNEL_ARGS'],
    'TRIPLEO_INSTALL_USER': os.environ['TRIPLEO_INSTALL_USER'],
    'TRIPLEO_UNDERCLOUD_CONF_FILE':
        os.environ['TRIPLEO_UNDERCLOUD_CONF_FILE'],
    'TRIPLEO_UNDERCLOUD_PASSWORD_FILE':
        os.environ['TRIPLEO_UNDERCLOUD_PASSWORD_FILE'],
    'MEMBER_ROLE_EXISTS': os.environ.get('MEMBER_ROLE_EXISTS', 'false'),
}

# Include all config opts in the context
for _, group in undercloud.list_opts():
    for opt in group:
        upper_name = opt.name.upper()
        context[upper_name] = os.environ[upper_name]

endpoint_context = {}
for k, v in os.environ.items():
    if k.startswith('UNDERCLOUD_ENDPOINT_'):
        endpoint_context[k] = v
context.update(endpoint_context)

with open(template) as f:
    puppet_stack_config_yaml = renderer.render(f.read(), context)

puppet_stack_config_yaml_path = '/etc/puppet/hieradata/puppet-stack-config.yaml'

if not os.path.exists(os.path.dirname(puppet_stack_config_yaml_path)):
    os.makedirs(os.path.dirname(puppet_stack_config_yaml_path))
with open(puppet_stack_config_yaml_path, 'w') as f:
    f.write(puppet_stack_config_yaml)

# Secure permissions
os.chmod(os.path.dirname(puppet_stack_config_yaml_path), 0750)
os.chmod(puppet_stack_config_yaml_path, 0600)
