#!/usr/bin/env python3
"""Image preparation command handler"""
# Copyright (C) 2019-2022 F5 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 sys

from image.image_controller import ImageController
from util.config import get_config_value
from util.logger import LOGGER
from util.misc import create_log_handler

def main():
    """main command handler"""

    parser = argparse.ArgumentParser(description='Prepare a cloud image from a virtual disk')
    parser.add_argument('-a', '--artifacts-dir', required=True,
                        help='Absolute path to the artifacts directory')
    parser.add_argument('-c', '--check-name', action="store_true",
                        help='Check cloud image name')
    parser.add_argument('-i', '--input', required=True,
                        help='Absolute path to the input virtual disk')
    parser.add_argument('-p', '--platform', required=True,
                        help='The cloud type (i.e. aws, gce, azure, alibaba)')
    parser.add_argument('-s', '--seed-image-name', default='',
                        help='Use supplied autogenerated seed cloud image name')
    parser.add_argument('-u', '--user-image-name', default='',
                        help='Use user-supplied cloud image name')

    args = parser.parse_args()

    # Check either seed or user cloud image name was provided
    if (args.seed_image_name == '' and args.user_image_name == '') or \
       (args.seed_image_name != '' and args.user_image_name != ''):
        raise Exception('You must provide either --seed-image-name or --user-image-name')

    # create log handler for the global LOGGER
    create_log_handler()

    if args.check_name:
        # Check name
        if args.user_image_name == '':
            raise Exception('--check-name can only be used with --user-image-name')

        ImageController.check_valid_name(args.platform, args.user_image_name)
    else:
        result = False
        try:
            # Prepare image
            image_controller = ImageController(args.artifacts_dir, args.platform,
                                               args.input)
            image_controller.prepare(args.seed_image_name, args.user_image_name)
            # If execution came so far, all is well.
            result = True
        except RuntimeError as runtime_exce:
            LOGGER.exception(runtime_exce)
        finally:
            # Clean-up image controller and other internal constructs it created.
            image_controller.clean_up()
            if result is True:
                LOGGER.info("SUCCESS: Image generation completed.")
            else:
                LOGGER.warning("FAILURE: Check the log file '%s' and fix the problem "
                               "before re-running.", get_config_value('LOG_FILE'))
                sys.exit(1)
    sys.exit(0)

if __name__ == "__main__":
    main()
