#!/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(escape=lambda s: s)
template = os.path.join(os.path.dirname(__file__),
                        '..',
                        'puppet-stack-config.yaml.template')

context = {item: os.environ.get(item)
           for item in undercloud.InstackEnvironment.PUPPET_KEYS}

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)
