#!/usr/bin/env python
import click
import panoptes.cloud_authentication
import panoptes.cloud_providers
import panoptes.cloud_output


def generate_analysis_output(analysis, output):
    output_options = {
        "json": panoptes.cloud_output.aws_output.output_json,
        "yml": panoptes.cloud_output.aws_output.output_yml,
        "human": panoptes.cloud_output.aws_output.output_human,
    }
    output_options[output](analysis=analysis)
    return None


@click.group()
def cli():
    """Welcome to Panoptes - The multi cloud security group analyzer

    This project is stored on GitHub and open sourced under Apache 2.0

    To start using it, read the docs at:
    https://github.com/tioxy/panoptes
    """
    pass


@cli.group(
    'aws',
    help='Amazon Web Services'
)
def aws():
    pass


@cli.group(
    'gcp',
    help='Google Cloud Plataform'
)
def gcp():
    pass


@aws.command(
    'analyze',
    help="Generate the analysis file"
)
@click.option(
    '--region',
    required=True,
    help='AWS Region to list the security groups',
    metavar='<region_id>'
)
@click.option(
    '--profile',
    default='default',
    help='AWS CLI configured profile which will be used',
    metavar='<profile_name>'
)
@click.option(
    '--output',
    default='human',
    help='Which kind of output you want the analysis',
    type=click.Choice(['human', 'json', 'yml']),
)
@click.option(
    '--whitelist',
    help='Whitelist with declared safe IPs and CIDR',
    metavar='<path>'
)
def aws_analyze_command(region, profile, output, whitelist=None):
    if whitelist is None:
        whitelist_file = None
    else:
        whitelist_file = read_whitelist_file(whitelist)

    aws_authentication = panoptes.cloud_authentication.aws.get_client(
        region=region,
        profile=profile,
    )

    if aws_authentication["Error"] is not None:
        print(aws_authetication["Error"])
    else:
        aws_client = aws_authentication["Client"]
        analysis = panoptes.cloud_providers.aws.aws_panoptes.analyze_security_groups(
            aws_client,
            whitelist_file,
        )
        generate_analysis_output(
            analysis=analysis,
            output=output,
        )
    return None


def read_whitelist_file(whitelist):
    with open(whitelist, 'r') as whitelist_file:
        whitelist = whitelist_file.read().splitlines()
    return whitelist


if __name__ == "__main__":
    cli()
    exit()
