#!/usr/bin/python3.11


# Copyright 2022 SUSE LLC
#
# This file is part of ec2imgutils
#
# ec2imgutils is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ec2imgutils is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ec2uploadimg. If not, see <http://www.gnu.org/licenses/>.

import argparse
import json
import os
import sys
import signal

import ec2imgutils.ec2utils as utils
import ec2imgutils.ec2uploadimg as ec2upimg
from ec2imgutils.ec2imgutilsExceptions import (
    EC2AccountException,
    EC2UploadImgException
)
from ec2imgutils.ec2setup import EC2Setup

# Options that configure the donor instance of the root swap method. The
# default upload does not use such an instance and the options are ignored.
ROOT_SWAP_ONLY_OPTIONS = (
    ('amiID', '--ec2-ami'),
    ('instType', '--type'),
    ('runningID', '--instance-id'),
    ('useEnclave', '--use-enclave'),
    ('vpcSubnetId', '--vpc-subnet-id')
)
# Options that were used to upload the image to the donor instance with ssh.
# The image is uploaded with the EBS direct APIs, the donor instance is not
# accessed. The options have no effect with any method and are ignored.
DEPRECATED_OPTIONS = (
    ('channelTimeout', '--channel-timeout'),
    ('privateKey', '--private-key-file'),
    ('securityGroupIds', '--security-group-ids'),
    ('sshName', '--ssh-key-pair'),
    ('sshTimeout', '--ssh-timeout'),
    ('sshUser', '--user'),
    ('usePrivateIP', '--use-private-ip')
)

# Global variables
aborted = False
logger = None
setup = None
uploader = None


# ----------------------------------------------------------------------------
def print_ex(logger, msg=None):
    """Prints information about the exception currently handled
    """
    exc_type, value, tb = sys.exc_info()
    logger.debug(value, exc_info=True)

    if msg:
        logger.info(msg)
    else:
        logger.info("{}: {}".format(exc_type.__name__, value))


# ----------------------------------------------------------------------------
def signal_handler(signum, frame):
    """Handle signals and clean up resources properly"""
    global aborted
    if aborted:
        # if it got already aborted before,
        # we kill the upload without proper clean up
        sys.exit(1)
    aborted = True
    if uploader:
        uploader.abort()
    if not setup and not uploader:
        # if there is no setup and no uploader
        # there are no resources we need to cleanup
        # and we just exit
        sys.exit(1)


# ----------------------------------------------------------------------------
def parse_args(args):
    """Command argument parsing function"""
    parser = argparse.ArgumentParser(description='Upload image to Amazon EC2')
    parser.add_argument(
        '-a', '--account',
        dest='accountName',
        help='Account to use (Optional)',
        metavar='ACCOUNT_NAME'
    )
    parser.add_argument(
        '--access-id',
        dest='accessKey',
        help='AWS access key (Optional)',
        metavar='AWS_ACCESS_KEY'
    )
    help_msg = 'The backing store type, (mag|ssd), or one of the EBS '
    help_msg += 'storage IDs'
    parser.add_argument(
        '-B', '--backing-store',
        default='ssd',
        dest='backingStore',
        help=help_msg,
        metavar='EC2_BACKING_STORE'
    )
    parser.add_argument(
        '--billing-codes',
        dest='billingCodes',
        help='The BillingProduct codes, only available to some accounts',
        metavar='BILLING_CODES'
    )
    parser.add_argument(
        '--boot-kernel',
        dest='akiID',
        help='Deprecated and ignored, para-virtual images are no longer '
             'supported (Optional)',
        metavar='AWS_AKI_ID'
    )
    help_msg = 'Set the boot mode for the image, legacy-bios, uefi, '
    help_msg += 'or uefi-preferred (Optional)'
    parser.add_argument(
        '--boot-mode',
        dest='bootMode',
        help=help_msg,
        choices=['', 'legacy-bios', 'uefi', 'uefi-preferred'],
        metavar='BOOT_MODE'
    )
    parser.add_argument(
        '-d', '--description',
        dest='descript',
        help='Image description, will also be used for the snapshot',
        metavar='IMAGE_DESCRIPTION',
        required=True
    )
    parser.add_argument(
        '-e', '--ec2-ami',
        dest='amiID',
        help='AWS AMI id of the donor instance that provides the meta '
             'data of the image. Only used with --use-root-swap, ignored '
             'otherwise (Optional)',
        metavar='AWS_AMI_ID',
    )
    parser.add_argument(
        '--ena-support',
        action='store_true',
        default=False,
        dest='ena',
        help='The image supports the ENA network interface (Optional)'
    )
    parser.add_argument(
        '-f', '--file',
        default=os.sep.join(['~', '.ec2utils.conf']),
        dest='configFilePath',
        help='Path to configuration file, default ~/.ec2utils.conf (Optional)',
        metavar='CONFIG_FILE'
    )
    parser.add_argument(
        '--grub2',
        action='store_true',
        default=False,
        dest='grub2',
        help='Deprecated and ignored, para-virtual images are no longer '
             'supported (Optional)'
    )
    help_msg = 'Provide valid json or a file name of a list of dicts '
    help_msg += 'each dict having a "Key" and "Value" assignment '
    help_msg += 'representing the key and value of a tag to be applied to '
    help_msg += 'the image. (Optional)'
    parser.add_argument(
        '--image-tags',
        dest='imageTags',
        help=help_msg,
        metavar='IMAGE_TAGS'
    )
    help_msg = 'Set the protocol version to be used when instances are '
    help_msg += 'launched from the image, supported values 2.0/v2.0. '
    help_msg += '(Optional)'
    parser.add_argument(
        '--imds-support',
        dest='imdsVersion',
        help=help_msg,
        choices=['', '2.0', 'v2.0'],
        metavar='IMDS_VERSION'
    )
    parser.add_argument(
        '-i', '--instance-id',
        dest='runningID',
        help='ID of a running donor instance that provides the meta data '
             'of the image. Only used with --use-root-swap, ignored '
             'otherwise (Optional)',
        metavar='AWS_INSTANCE_ID',
    )
    parser.add_argument(
        '-m', '--machine',
        dest='arch',
        help='Machine architecture arm64|i386|x86_64 for the uploaded image',
        metavar='ARCH',
        required=True
    )
    parser.add_argument(
        '-n', '--name',
        dest='imgName',
        help='Image name',
        metavar='IMAGE_NAME',
        required=True
    )
    parser.add_argument(
        '-p', '--private-key-file',
        dest='privateKey',
        help='Deprecated and ignored, the image is uploaded without ssh '
             '(Optional)',
        metavar='PRIVATE_KEY'
    )
    parser.add_argument(
        '-r', '--regions',
        dest='regions',
        help='Comma separated list of regions for image upload',
        metavar='EC2_REGIONS',
        required=True
    )
    parser.add_argument(
        '--root-volume-size',
        dest='rootVolSize',
        help='Size of root volume for new image in GB (Optional)',
        metavar='ROOT_VOLUME_SIZE',
    )
    parser.add_argument(
        '--ssh-key-pair',
        dest='sshName',
        help='Deprecated and ignored, the image is uploaded without ssh '
             '(Optional)',
        metavar='AWS_KEY_PAIR_NAME'
    )
    parser.add_argument(
        '-s', '--secret-key',
        dest='secretKey',
        help='AWS secret access key (Optional)',
        metavar='AWS_SECRET_KEY'
    )
    help_msg = 'Deprecated and ignored, the image is uploaded without ssh '
    help_msg += '(Optional)'
    parser.add_argument(
        '--security-group-ids',
        default='',
        dest='securityGroupIds',
        help=help_msg,
        metavar='AWS_SECURITY_GROUP_IDS'
    )
    parser.add_argument(
        '--session-token',
        dest='sessionToken',
        help='AWS session token, for use of temporary credentials (Optional)',
        metavar='AWS_SESSION_TOKEN'
    )
    parser.add_argument(
        '--snaponly',
        action='store_true',
        default=False,
        dest='snapOnly',
        help='Stop after snapshot creation (Optional)'
    )
    parser.add_argument(
        '--sriov-support',
        action='store_true',
        default=False,
        dest='sriov',
        help='The image supports SRIOV network interface (Optional)'
    )
    parser.add_argument(
        'source',
        help='The path to the image source file'
    )
    help_msg = 'Deprecated and ignored, the image is uploaded without ssh '
    help_msg += '(Optional)'
    parser.add_argument(
        '--ssh-timeout',
        default=None,
        dest='sshTimeout',
        help=help_msg,
        metavar='SSH_TIME_OUT',
        type=int
    )
    help_msg = 'Deprecated and ignored, the image is uploaded without ssh '
    help_msg += '(Optional)'
    parser.add_argument(
        '--channel-timeout',
        default=None,
        dest='channelTimeout',
        help=help_msg,
        metavar='CHANNEL_TIME_OUT',
        type=int
    )
    help_msg = 'The image supports NitroTPM, supported values 2.0/v2.0'
    help_msg += ' (Optional)'
    parser.add_argument(
        '--tpm-support',
        dest='tpm',
        help=help_msg,
        choices=['', '2.0', 'v2.0'],
        metavar='TPM_SUPPORT'
    )
    parser.add_argument(
        '-t', '--type',
        dest='instType',
        help='Instance type of the donor instance. Only used with '
             '--use-root-swap, ignored otherwise (Optional)',
        metavar='AWS_UPLOAD_INST_TYPE'
    )
    parser.add_argument(
        '-u', '--user',
        dest='sshUser',
        help='Deprecated and ignored, the image is uploaded without ssh '
             '(Optional)',
        metavar='AWS_INSTANCE_USER'
    )
    parser.add_argument(
        '--use-private-ip',
        action='store_true',
        default=False,
        dest='usePrivateIP',
        help='Deprecated and ignored, the image is uploaded without ssh '
             '(Optional)'
    )
    parser.add_argument(
        '--use-snapshot',
        action='store_true',
        default=False,
        dest='useSnap',
        help='Create the image using an existing snapshot that is specified \
              as the source variable (Optional)'
    )
    parser.add_argument(
        '--use-root-swap',
        action='store_true',
        default=False,
        dest='rootSwapMethod',
        help='Use the root swap method to create the new image. The image '
             'is uploaded with the EBS direct APIs. A donor instance, that '
             'provides the meta data of the image, gets the new root volume '
             'and the image is created from it (Optional)'
    )
    help_msg = 'The virtualization type, only hvm is supported, default hvm '
    help_msg += '(Optional)'
    parser.add_argument(
        '-V', '--virt-type',
        default='hvm',
        dest='virtType',
        help=help_msg,
        metavar='AWS_VIRT_TYPE'
    )
    help_msg = 'Enable verbose output (Optional). Multiple -v options increase'
    help_msg += ' the verbosity. The maximum is 2.'
    parser.add_argument(
        '--verbose',
        '-v',
        action='count',
        default=0,
        dest='verbose',
        help=help_msg)
    parser.add_argument(
        '--version',
        action='version',
        version=utils.get_version(),
        help='Program version'
    )
    help_msg = 'The ID, starts with "subnet-" of the VPC subnet in which the '
    help_msg += 'donor instance should run. Only used with --use-root-swap, '
    help_msg += 'ignored otherwise (Optional)'
    parser.add_argument(
        '--vpc-subnet-id',
        default='',
        dest='vpcSubnetId',
        help=help_msg,
        metavar='VPC_SUBNET_ID'
    )
    help_msg = 'Start the donor instance that provides the meta data'
    help_msg += ' of the image as an AWS Enclave. Only used with'
    help_msg += ' --use-root-swap, ignored otherwise (Optional)'
    parser.add_argument(
        '--use-enclave',
        action='store_true',
        default=False,
        dest='useEnclave',
        help=help_msg,
    )

    help_msg = 'Number of threads writing blocks of the image to the '
    help_msg += 'snapshot in parallel, default 8. A value lower than 1 is '
    help_msg += 'replaced by 1 with a warning (Optional)'
    parser.add_argument(
        '--upload-workers',
        default=8,
        dest='uploadWorkers',
        help=help_msg,
        metavar='UPLOAD_WORKERS',
        type=int
    )

    help_msg = 'Number of attempts to write a block of the image to the '
    help_msg += 'snapshot before giving up, default 8. Failed attempts are '
    help_msg += 'retried with an increasing delay, useful for slow networks '
    help_msg += 'A value lower than 1 is replaced by the default with a '
    help_msg += 'warning (Optional)'
    parser.add_argument(
        '--upload-retries',
        default=8,
        dest='uploadRetries',
        help=help_msg,
        metavar='UPLOAD_RETRIES',
        type=int
    )
    help_msg = 'Timeout in seconds to wait for a response when writing a '
    help_msg += 'block of the image, default 300. Increase for slow '
    help_msg += 'networks. A value lower than 1 is replaced by the default '
    help_msg += 'with a warning (Optional)'
    parser.add_argument(
        '--upload-timeout',
        default=300,
        dest='uploadTimeout',
        help=help_msg,
        metavar='UPLOAD_TIMEOUT',
        type=int
    )

    help_msg = 'Write blocks containing only zeros to the snapshot, by '
    help_msg += 'default they are skipped (Optional)'
    parser.add_argument(
        '--write-zero-blocks',
        action='store_true',
        default=False,
        dest='writeZeroBlocks',
        help=help_msg,
    )

    help_msg = 'Read the snapshot back after the upload and compare it with '
    help_msg += 'the uploaded data. A snapshot that does not match is '
    help_msg += 'deleted and the upload fails. Needs the permissions '
    help_msg += 'ebs:ListSnapshotBlocks and ebs:GetSnapshotBlock (Optional)'
    parser.add_argument(
        '--verify-snapshot',
        action='store_true',
        default=False,
        dest='verifySnapshot',
        help=help_msg,
    )

    help_msg = 'Do not delete a snapshot that failed the verification, use '
    help_msg += 'with --verify-snapshot (Optional)'
    parser.add_argument(
        '--keep-snapshot-on-verify-failure',
        action='store_true',
        default=False,
        dest='keepSnapshotOnVerifyFailure',
        help=help_msg,
    )

    help_msg = 'Wait N-number of times for AWS operation timeout, default 1 '
    help_msg += ' = 600 seconds (Optional)'
    parser.add_argument(
        '--wait-count',
        default=1,
        dest='waitCount',
        help=help_msg,
        metavar='AWS_WAIT_COUNT',
        type=int
    )

    parsed_args = parser.parse_args(args)
    return parsed_args


# ----------------------------------------------------------------------------
def check_required_arguments_and_constraints(args, logger):
    """This function is used to assure the additional requirements over
    arguments (which ones are mandatory, etc.) are met.
    """
    check_virt_type(args, logger)
    check_snapshot_arguments(args, logger)
    check_supported_arch_argument(args, logger)
    all_arm64_images_to_support_ENA(args, logger)
    check_sriov_image_is_hvm(args, logger)
    check_ena_image_is_hvm(args, logger)
    check_amiID_or_runningID_provided(args, logger)
    check_regions_parameter(args, logger)
    check_tpm_support_has_allowed_boot_options(args, logger)
    check_image_tags(args, logger)
    check_upload_workers(args, logger)
    check_upload_retries(args, logger)
    check_upload_timeout(args, logger)
    check_keep_snapshot_option(args, logger)
    warn_deprecated_arguments(args, logger)
    warn_root_swap_only_arguments(args, logger)
    warn_para_virtual_arguments(args, logger)


# ----------------------------------------------------------------------------
def check_upload_workers(args, logger):
    """This function checks that at least one upload worker is requested.
    Make a best effort and use 1 worker with a warning otherwise, the upload
    works with a single worker"""
    if args.uploadWorkers < 1:
        logger.warning(
            'The number of upload workers must be at least 1, got %d, '
            'using 1 upload worker' % args.uploadWorkers
        )
        args.uploadWorkers = 1


# ----------------------------------------------------------------------------
def check_upload_retries(args, logger):
    """This function checks that at least one attempt to write a block is
    allowed. Make a best effort and use the default of 8 with a warning
    otherwise"""
    if args.uploadRetries < 1:
        logger.warning(
            'The number of upload retries must be at least 1, got %d, '
            'using the default 8' % args.uploadRetries
        )
        args.uploadRetries = 8


# ----------------------------------------------------------------------------
def check_upload_timeout(args, logger):
    """This function checks that the upload timeout is a positive value.
    Make a best effort and use the default of 300 seconds with a warning
    otherwise"""
    if args.uploadTimeout < 1:
        logger.warning(
            'The upload timeout must be at least 1 second, got %d, '
            'using the default 300 seconds' % args.uploadTimeout
        )
        args.uploadTimeout = 300


# ----------------------------------------------------------------------------
def check_keep_snapshot_option(args, logger):
    """This function warns if the snapshot is requested to be kept on a
    failed verification without verifying the snapshot"""
    if args.keepSnapshotOnVerifyFailure and not args.verifySnapshot:
        logger.warning(
            '--keep-snapshot-on-verify-failure has no effect without '
            '--verify-snapshot'
        )


# ----------------------------------------------------------------------------
def check_virt_type(args, logger):
    """This function rejects virtualization types other than hvm,
    para-virtual images are no longer supported and ignoring the option would
    create a different image than requested
    """
    if args.virtType != 'hvm':
        logger.error(
            'Only hvm images are supported, the virtualization type "%s" '
            'is no longer supported' % args.virtType
        )
        sys.exit(1)


# ----------------------------------------------------------------------------
def warn_para_virtual_arguments(args, logger):
    """This function warns about the arguments that were only used for
    para-virtual images, they are ignored"""
    ignored = [
        option for attr, option in (
            ('akiID', '--boot-kernel'), ('grub2', '--grub2')
        ) if getattr(args, attr, None)
    ]
    if ignored:
        logger.warning(
            'The following options are deprecated and ignored, para-virtual '
            'images are no longer supported: %s' % ', '.join(ignored)
        )


# ----------------------------------------------------------------------------
def warn_deprecated_arguments(args, logger):
    """This function warns about the arguments that were used to upload the
    image with ssh, they have no effect anymore"""
    ignored = [
        option for attr, option in DEPRECATED_OPTIONS
        if getattr(args, attr, None)
    ]
    if ignored:
        logger.warning(
            'The following options are deprecated and ignored: %s'
            % ', '.join(ignored)
        )


# ----------------------------------------------------------------------------
def warn_root_swap_only_arguments(args, logger):
    """This function warns about arguments that only have an effect with the
    root swap method, the default method does not use a donor instance
    """
    if args.rootSwapMethod:
        return
    ignored = [
        option for attr, option in ROOT_SWAP_ONLY_OPTIONS
        if getattr(args, attr, None)
    ]
    if ignored:
        logger.warning(
            'The following options are ignored, the image is uploaded with '
            'the EBS direct APIs without a donor instance. They are only '
            'used with --use-root-swap: %s' % ', '.join(ignored)
        )


# ----------------------------------------------------------------------------
def check_image_tags(args, logger):
    """This function determines if a file path is provided and if this
    is the case loads the json from the file. Set the argument to the
    resulting json object. If the json is provided as a string create the
    json object"""
    imgTags = None
    error = ''
    usr_img_tags = args.imageTags
    if usr_img_tags:
        if 'Key' in usr_img_tags and 'Value' in usr_img_tags:
            try:
                imgTags = json.loads(usr_img_tags)
            except json.decoder.JSONDecodeError:
                error = 'Decode'
        # The given argument is not valid json it could be a file path with
        # Key abd Value as part of the file name
        if not imgTags:
            if os.path.isfile(os.path.expanduser(usr_img_tags)):
                try:
                    imgTags = json.loads(open(usr_img_tags, 'r').read())
                except PermissionError:
                    error = 'File'
                except json.decoder.JSONDecodeError:
                    error = 'Decode'
                except Exception:
                    error = 'Unknown'
            else:
                error = 'File'

        if not imgTags:
            if error == 'File':
                err_msg = 'Attempted to load file %s but the file could '
                err_msg += 'not be found or read'
                logger.error(err_msg % usr_img_tags)
                sys.exit(1)
            elif error == 'Decode':
                logger.error('Provided json for tags is invalid')
                sys.exit(1)
            else:
                logger.error('Unknown error processing image-tags argument')
                sys.exit(1)

    args.imageTags = imgTags


# ----------------------------------------------------------------------------
def check_snapshot_arguments(args, logger):
    """This function checks that the --use-snapshot argument cannot be
    specified with other incompatible options
    """
    if (
        args.useSnap and
        (args.snapOnly or
         args.rootSwapMethod)
    ):
        logger.error('The options --use-snapshot cannot be specified \
             with --snaponly or --use-root-swap')
        sys.exit(1)

    if not args.useSnap:
        if not os.path.isfile(args.source):
            logger.error('Could not find specified image file: %s'
                         % args.source)
            sys.exit(1)


# ----------------------------------------------------------------------------
def check_supported_arch_argument(args, logger):
    """This function checks that the value provided for the --machine argument
    is valid
    """
    supported_arch = ['arm64', 'i386', 'x86_64']
    if args.arch not in supported_arch:
        logger.error(
            'Specified architecture must be one of %s' % str(supported_arch)
        )
        sys.exit(1)


# ----------------------------------------------------------------------------
def all_arm64_images_to_support_ENA(args, logger):
    """Function to assure all arm64 images must support ENA.
    Choosing to assume the image has a sufficiently new kernel with the
    ENA driver rather than to error out
    """
    if args.arch == 'arm64':
        if not args.ena:
            logger.info('Enabling ENA support, required by arm64')
            args.ena = True


# ----------------------------------------------------------------------------
def check_sriov_image_is_hvm(args, logger):
    """This function checks that if sriov option is included, virtualization
    type has to be 'hvm'
    """
    if args.sriov and args.virtType != 'hvm':
        logger.error('SRIOV support is only possible with HVM images')
        sys.exit(1)


# ----------------------------------------------------------------------------
def check_ena_image_is_hvm(args, logger):
    """This function checks that if ena option is included, virtualization
    type has to be 'hvm'
    """
    if args.ena and args.virtType != 'hvm':
        logger.error('ENA is only possible with HVM images')
        sys.exit(1)


# ----------------------------------------------------------------------------
def check_amiID_or_runningID_provided(args, logger):
    """This function checks that amiID or runningID are provided"""
    if args.amiID and args.runningID:
        logger.error(
            'Specify either AMI ID to start instance or running '
            ' ID to use already running instance'
        )
        sys.exit(1)


# ----------------------------------------------------------------------------
def check_tpm_support_has_allowed_boot_options(args, logger):
    """This function checks that in case tpm is enabled, boot options are
    correct
    """
    # AWS rejects uefi-preferred with TPM support when registering the image
    tpm_boot_options = ['uefi']
    if args.tpm and args.bootMode not in tpm_boot_options:
        logger.error(
            'TPM can only be set with --boot-mode set to %s' % str(
                tpm_boot_options)
        )
        sys.exit(1)


# ----------------------------------------------------------------------------
def check_regions_parameter(args, logger):
    """This function checks that the provided regions parameter is allowed"""
    regions = args.regions.split(',')
    # The options are only meaningful with a donor instance
    region_specific = []
    if args.rootSwapMethod:
        region_specific += [args.amiID, args.runningID, args.vpcSubnetId]
    if len(regions) > 1 and any(region_specific):
        logger.error('Incompatible arguments: multiple regions specified')
        logger.error('Cannot process region unique argument for --ec2-ami,')
        logger.error('--instance-id, or --vpc-subnet-id')
        sys.exit(1)


# ----------------------------------------------------------------------------
def get_config(args, logger):
    """Function to the the configutation parsed from the configuration file
    provided as an argument (or the default path)
    """
    config_file = os.path.expanduser(args.configFilePath)
    config = None
    if not os.path.isfile(config_file):
        logger.error('Configuration file "%s" not found.' % config_file)
        sys.exit(1)
    try:
        config = utils.get_config(config_file)
    except Exception as e:
        print_ex(logger, e)
        sys.exit(1)
    return config


# ----------------------------------------------------------------------------
def get_access_key(args, config, logger):
    """Function to get the access_key to AWS with the data provided as command
    line args and configuration
    """
    access_key = args.accessKey
    if not access_key:
        try:
            access_key = utils.get_from_config(
                args.accountName,
                config,
                None,
                'access_key_id',
                '--access-id'
            )
        except EC2AccountException as e:
            logger.error(e)
            sys.exit(1)

    if not access_key:
        logger.error('Could not determine account access key')
        sys.exit(1)
    return access_key


# ----------------------------------------------------------------------------
def get_secret_key(args, config, logger):
    """Function to get the secret_key to AWS with the data provided as command
    line args and configuration
    """
    secret_key = args.secretKey
    if not secret_key:
        try:
            secret_key = utils.get_from_config(
                args.accountName,
                config,
                None,
                'secret_access_key',
                '--secret-key'
            )
        except EC2AccountException as e:
            logger.error(e)
            sys.exit(1)

    if not secret_key:
        logger.error('Could not determine account secret access key')
        sys.exit(1)
    return secret_key


# ----------------------------------------------------------------------------
def get_amiID(args, config, region, logger):
    """Function to get the amiID if not available yet"""
    try:
        ami_id = utils.get_from_config(
            args.accountName,
            config,
            region,
            'ami',
            '--ec2-ami'
        )
        return ami_id
    except Exception as e:
        logger.error('Could not determine helper AMI-ID')
        logger.error(e)
        sys.exit(1)


# ----------------------------------------------------------------------------
def get_vpc_subnet_id(args, config, region, setup,  logger):
    """Function to get the vpn_subnet parameter"""
    vpc_subnet_id = args.vpcSubnetId
    base_log_msg = 'Using VPC subnet: %s'

    if vpc_subnet_id:
        logger.debug(base_log_msg % vpc_subnet_id)
        return vpc_subnet_id

    if not (args.amiID or args.runningID):
        # Depending on instance type an instance may possibly only
        # launch inside a subnet. Look in the config for a subnet if
        # no subnet ID is given and the AMI to use was not
        # specified on the command line
        try:
            vpc_subnet_id = utils.get_from_config(
                args.accountName,
                config,
                region,
                'subnet_id_%s' % region,
                '--vpc-subnet-id'
            )
        except Exception:
            pass
        try:
            # falls back to setup.create_vpc_subnet()
            vpc_subnet_id = vpc_subnet_id or setup.create_vpc_subnet()
            logger.debug(base_log_msg % vpc_subnet_id)
            return vpc_subnet_id
        except Exception:
            msg = (
                'Not using a subnet-id, none given on the '
                'command line, none found in config for '
                '"subnet_id_%s" value '
                'and unable to create a VPC Subnet'
            )
            logger.error(msg % region)
            setup.clean_up()
            sys.exit(1)


# ----------------------------------------------------------------------------
def get_inst_type(args, config, region, logger):
    """Function to get the inst_type parameter"""
    inst_type = args.instType
    if not inst_type:
        try:
            inst_type = utils.get_from_config(
                args.accountName,
                config,
                region,
                'instance_type',
                '--type'
            )
        except Exception:
            print_ex(logger, 'Could not find instance_type in config')
            sys.exit(1)
    return inst_type


# ----------------------------------------------------------------------------
def get_sriov_type(args):
    """Function to get the sriov_type parameter"""
    sriov_type = args.sriov
    if sriov_type:
        sriov_type = 'simple'
    return sriov_type


# ----------------------------------------------------------------------------
def get_root_volume_size(args):
    """Function to get the root_volume_size parameter"""
    root_volume_size = 10
    if args.rootVolSize:
        root_volume_size = args.rootVolSize
    return root_volume_size


# ----------------------------------------------------------------------------
def get_root_swap_arguments(
        args,
        config,
        region,
        setup,
        logger
):
    """Function to get the arguments of the EC2ImageUploader that describe the
    donor instance, only the root swap method needs one. The donor instance
    provides the meta data for the new image, it is not accessed
    """
    ami_id = args.amiID
    running_id = args.runningID

    if not ami_id and not running_id:
        ami_id = get_amiID(args, config, region, logger)
        if not ami_id:
            logger.error('Could not determine helper AMI-ID')
            sys.exit(1)

    # No instance is launched for a running donor, the type is not needed
    inst_type = None
    if not running_id:
        inst_type = get_inst_type(args, config, region, logger)
        if not inst_type:
            logger.error('Could not determine the instance type')
            sys.exit(1)

    vpc_subnet_id = get_vpc_subnet_id(
        args,
        config,
        region,
        setup,
        logger
    )

    return {
        'launch_ami': ami_id,
        'launch_inst_type': inst_type,
        'running_id': running_id,
        'vpc_subnet_id': vpc_subnet_id,
        'use_enclave': args.useEnclave
    }


# ----------------------------------------------------------------------------
def get_uploader(
        args,
        region,
        config,
        access_key,
        secret_key,
        setup,
        logger
):
    """Function to get the ec2imgutils.EC2ImageUploader instance"""
    try:
        if not aborted:
            sriov_type = get_sriov_type(args)
            root_volume_size = get_root_volume_size(args)

            uploader_args = {}
            if args.rootSwapMethod:
                uploader_args = get_root_swap_arguments(
                    args,
                    config,
                    region,
                    setup,
                    logger
                )

            uploader = ec2upimg.EC2ImageUploader(
                access_key=access_key,
                backing_store=args.backingStore,
                billing_codes=args.billingCodes,
                ena_support=args.ena,
                image_arch=args.arch,
                image_description=args.descript,
                image_name=args.imgName,
                region=region,
                root_volume_size=root_volume_size,
                secret_key=secret_key,
                session_token=args.sessionToken,
                sriov_type=sriov_type,
                wait_count=args.waitCount,
                log_callback=logger,
                boot_mode=args.bootMode,
                tpm_support=args.tpm,
                imds_support=args.imdsVersion,
                image_tags=args.imageTags,
                upload_workers=args.uploadWorkers,
                upload_retries=args.uploadRetries,
                upload_timeout=args.uploadTimeout,
                write_zero_blocks=args.writeZeroBlocks,
                verify_snapshot=args.verifySnapshot,
                keep_snapshot_on_verify_failure=(
                    args.keepSnapshotOnVerifyFailure
                ),
                **uploader_args
            )
            return uploader
    except EC2UploadImgException as e:
        logger.exception(e)
        sys.exit(1)
    except Exception as e:
        logger.exception(e)
        sys.exit(1)


# ----------------------------------------------------------------------------
def log_aborted(logger):
    """Tell that nothing was created, the upload was aborted"""
    logger.warning('The upload was aborted, no snapshot or image created')


# ----------------------------------------------------------------------------
def upload_image_to_region(
        args,
        region,
        config,
        access_key,
        secret_key,
        logger
):
    """ Function to upload the image to a region"""
    errors = 0
    global setup
    global uploader
    try:
        setup = EC2Setup(
            access_key,
            region,
            secret_key,
            args.sessionToken,
            log_callback=logger
        )

        uploader = get_uploader(
            args,
            region,
            config,
            access_key,
            secret_key,
            setup,
            logger
        )

        if not aborted:
            if args.snapOnly:
                snapshot = uploader.create_snapshot(args.source)
                if snapshot:
                    msg = 'Created snapshot: {}'.format(
                        str(snapshot['SnapshotId'])
                    )
                    logger.info(msg)
                else:
                    log_aborted(logger)
            else:
                if args.rootSwapMethod:
                    ami = uploader.create_image_use_root_swap(args.source)
                elif args.useSnap:
                    ami = uploader.create_image_from_snapshot(args.source)
                else:
                    ami = uploader.create_image(args.source)
                if ami:
                    logger.info('Created image: {}'.format(str(ami)))
                else:
                    log_aborted(logger)
    except EC2UploadImgException as e:
        print_ex(logger, e)
        errors += 1
    except Exception as e:
        print_ex(logger, e)
        errors += 1
    finally:
        # avoid unclean termination in case of issues in the cleanup routine
        try:
            setup.clean_up()
        except Exception as e:
            print_ex(logger, e)
            errors += 1
        finally:
            if errors > 0:
                sys.exit(1)


# ----------------------------------------------------------------------------
def main(args):
    """ Main function """
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    args = parse_args(args)
    logger = utils.get_logger(args.verbose)
    check_required_arguments_and_constraints(args, logger)

    config = get_config(args, logger)
    access_key = get_access_key(args, config, logger)
    secret_key = get_secret_key(args, config, logger)

    regions = args.regions.split(',')

    for region in regions:
        upload_image_to_region(
            args,
            region,
            config,
            access_key,
            secret_key,
            logger
        )


# ----------------------------------------------------------------------------
if __name__ == '__main__':
    main(sys.argv[1:])
