#!/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 shutil
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')

keystone_pki_dir = tempfile.mkdtemp()
subprocess.check_call(['generate-keystone-pki', '-d', keystone_pki_dir])

# 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'],
    'KEYSTONE_SIGNING_CERTIFICATE':
        open(os.path.join(keystone_pki_dir, 'signing_cert.pem')).read(),
    'KEYSTONE_SIGNING_KEY':
        open(os.path.join(keystone_pki_dir, 'signing_key.pem')).read(),
    'KEYSTONE_CA_CERTIFICATE':
        open(os.path.join(keystone_pki_dir, 'ca_cert.pem')).read(),
    'KEYSTONE_CA_KEY':
        open(os.path.join(keystone_pki_dir, 'ca_key.pem')).read(),
}

# 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)
