#!/usr/bin/python3

# Copyright 2018 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 ec2removeimg. If not, see <http://www.gnu.org/licenses/>.

import argparse
import os
import sys

import ec2imgutils.ec2utils as utils
import ec2imgutils.ec2removeimg as ec2rmimg
from ec2imgutils.ec2imgutilsExceptions import (
    EC2AccountException,
    EC2RemoveImgException
)

# Set up command line argument parsing
argparse = argparse.ArgumentParser(description='Remove images in EC2')
argparse.add_argument(
    '-a', '--account',
    dest='account_name',
    help='Account to use',
    metavar='ACCOUNT_NAME',
)
argparse.add_argument(
    '--access-id',
    dest='access_key',
    help='AWS access key (Optional)',
    metavar='AWS_ACCESS_KEY'
)
argparse.add_argument(
    '--all',
    action='store_true',
    default=False,
    dest='all',
    help='Delete all images that match the search criteria'
)
help_msg = 'Do not perform any action, print information about actions that '
help_msg += 'would be performed instead (Optional)'
argparse.add_argument(
    '-n', '--dry-run',
    action='store_true',
    default=False,
    dest='dry_run',
    help=help_msg
)
argparse.add_argument(
    '-f', '--file',
    default=os.sep.join(['~', '.ec2utils.conf']),
    dest='config_file_path',
    help='Path to configuration file, default ~/.ec2utils.conf (Optional)',
    metavar='CONFIG_FILE'
)
# Note, one of the arguments in the group is required if --version is
# not specified. However setting this behavior through the parser
# also requires one argument to be specified even if --version is specified
# This parser behavior is true even if --version and the group are part of the
# same subgroup
remove_image_condition_group = argparse.add_mutually_exclusive_group()
remove_image_condition_group.add_argument(
    '--image-id',
    dest='image_id',
    help='The AMI ID of the image to be removed (Optional)',
    metavar='AMI_ID'
)
remove_image_condition_group.add_argument(
    '--image-name',
    dest='image_name',
    help='The image name of the image to be removed (Optional)',
    metavar='IMAGE_NAME'
)
help_msg = 'An image name fragment to match the image name of the image to be '
help_msg += 'removed (Optional)'
remove_image_condition_group.add_argument(
    '--image-name-frag',
    dest='image_name_frag',
    help=help_msg,
    metavar='IMAGE_NAME_FRAGMENT'
)
help_msg = 'A regular expression to match the image name of the image to be '
help_msg += 'removed (Optional)'
remove_image_condition_group.add_argument(
    '--image-name-match',
    dest='image_name_match',
    help=help_msg,
    metavar='REGEX'
)
argparse.add_argument(
    '--confirm',
    action='store_true',
    default=False,
    dest='confirm',
    help='Remove matched images with confirmation of action'
)
argparse.add_argument(
    '--preserve-snap',
    action='store_true',
    default=False,
    dest='preserve_snap',
    help='Do not remove the snapshot associated with the image'
)
help_msg = 'Comma separated list of regions for removing, all integrated '
help_msg += 'regions if not given (Optional)'
argparse.add_argument(
    '-r', '--regions',
    dest='regions',
    help=help_msg,
    metavar='EC2_REGIONS'
)
argparse.add_argument(
    '-s', '--secret-key',
    dest='secret_key',
    help='AWS secret access key (Optional)',
    metavar='AWS_SECRET_KEY'
)
argparse.add_argument(
    '--verbose',
    action='store_true',
    default=False,
    dest='verbose',
    help='Enable on verbose output'
)
argparse.add_argument(
    '--version',
    action='version',
    version=utils.get_version(),
    help='Program version'
)

args = argparse.parse_args()

logger = utils.get_logger(args.verbose)

# Explicit check required to to the group issue, see comment above
if (
        not args.image_id and not
        args.image_name and not
        args.image_name_frag and not
        args.image_name_match):
    error_msg = 'ec2removeimg: error: one of the arguments '
    error_msg += '--image-id --image-name --image-name-frag '
    error_msg += '--image-name-match is required'
    logger.error(error_msg)
    sys.exit(1)


config_file = os.path.expanduser(args.config_file_path)
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:
    logger.error(e)
    sys.exit(1)

access_key = args.access_key
if not access_key:
    try:
        access_key = utils.get_from_config(args.account_name,
                                           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)

secret_key = args.secret_key
if not secret_key:
    try:
        secret_key = utils.get_from_config(args.account_name,
                                           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)

if not args.regions:
    regions = utils.get_regions(args, access_key, secret_key)
else:
    regions = args.regions.split(',')

remover = ec2rmimg.EC2RemoveImage(
    access_key=access_key,
    image_id=args.image_id,
    image_name=args.image_name,
    image_name_fragment=args.image_name_frag,
    image_name_match=args.image_name_match,
    keep_snap=args.preserve_snap,
    confirm=args.confirm,
    remove_all=args.all,
    secret_key=secret_key,
    log_callback=logger
)

if args.dry_run:
    logger.info('Dry run, the following images would be removed')
try:
    for region in regions:
        remover.set_region(region)
        if args.dry_run:
            remover.print_remove_info()
        else:
            remover.remove_images()
except EC2RemoveImgException as e:
    logger.error(e)
    sys.exit(1)
except Exception as e:
    logger.exception(e)
    sys.exit(1)
