#!/usr/bin/env python
# Copyright 2015 Red Hat, Inc.
#
# 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 argparse
import os
import subprocess
import sys
import yaml

from oslo_config import cfg
from oslo_config import types
from oslo_log import log


from tripleo_common.image.build import ImageBuildManager

LOG = log.getLogger(__name__)
env = os.environ.copy()

CONF = cfg.CONF
log.register_options(CONF)
image_opt_group = cfg.OptGroup(name='image',
                               title='Image build options')
_opts = [
    cfg.MultiOpt('config-file',
                 item_type=types.String(),
                 default=['disk_images.yaml'],
                 help=("""Path to configuration file. Can be specified """
                       """multiple times"""),
                ),
    cfg.StrOpt('output-directory',
               default=env.get('TRIPLEO_ROOT', '.'),
               help=("""output directory for images. """
                     """Defaults to $TRIPLEO_ROOT, or current directory""")
              ),
    cfg.BoolOpt('skip',
                default=False,
                help="""Skip build if cached image exists."""
               ),
    cfg.BoolOpt('json-output',
                default=False,
                help="""Skip build and only output the configuration in a """
                     """structured JSON format."""),
    cfg.MultiOpt('name',
                 item_type=types.String(),
                 help="""Name of image to build. May be specified multiple """
                      """times. If unspecified, will build all images in """
                      """given YAML files."""),
]
CONF.register_group(image_opt_group)
CONF.register_cli_opts(_opts, group=image_opt_group)
CONF.set_default('use_stderr', True)
log.setup(CONF, 'build-overcloud-images')

def main(argv=sys.argv):
    CONF(argv[1:])
    LOG.info('Using config files at: %s' % CONF.image.config_file)

    manager = ImageBuildManager(CONF.image.config_file,
                                output_directory=CONF.image.output_directory,
                                skip=CONF.image.skip,
                                images=CONF.image.name)
    if CONF.image.json_output:
        manager.json_output()
    else:
        manager.build()

if __name__ == '__main__':
    sys.exit(main(sys.argv))
