# Path: installer/helpers/destroyprep.py
# def destroyprep(stackname, identity, region, all=False):
#     # Delete the identity policy  - Created in terraform/scripts/ses.sh
#     client = boto3.client('ses', region_name=region)
#     cloudfront_client = boto3.client('cloudfront', region_name=region)
#     lambda_client = boto3.client('lambda', region_name=region)
#     cloudformation_client = boto3.client('cloudformation', region_name=region)
#     client.delete_identity_policy(
#         Identity=identity,
#         PolicyName="Policy-{0}".format(stackname)
#     )
# 
#     print("Destroy all: {0} for stack {1}".format(all, stackname))
#     # run python scripts to teardown
#     if all:
#         delete_event_source_mapping(stackname, lambda_client)
#         delete_platform_services(stackname, cloudformation_client, True)
#         delete_cf_dists(stackname, cloudfront_client, True)
#     else:
#         delete_event_source_mapping(stackname, lambda_client)
#         delete_platform_services(stackname, cloudformation_client, False)
# 
# Path: installer/helpers/terraform.py
# def exec_terraform_destroy():
#     tfCommand = [
#             'terraform', 'destroy', '--auto-approve'
#     ]
# 
#     if not tee_check_output(tfCommand, workdir=get_terraform_folder()):
#         print(
#             colors.FAIL + datetime.datetime.now().strftime('%c') + '\n' + colors.ENDC)
# 
#         print(
#             colors.FAIL + 'Terraform destroy failed! You can try re-running the uninstall' + colors.ENDC)
#     else:
#         print(
#             colors.OKGREEN + datetime.datetime.now().strftime('%c') + '\n' + colors.ENDC)
# 
#         print(
#             colors.OKGREEN + 'Terraform finished! AWS resources destroyed\n' + colors.ENDC)
# 
# def get_terraform_output_var(varname):
#     try:
#         return check_output(['terraform', 'output', varname], workdir=get_terraform_folder()).rstrip().decode('utf8')
#     except subprocess.CalledProcessError:
#         print("Failed getting output variable {0} from terraform!".format(varname))
#         sys.exit()


import click
import os
from installer.helpers.destroyprep import destroyprep
from installer.helpers.terraform import exec_terraform_destroy, get_terraform_output_var
@click.command()
@click.option(
    '--mode',
    type=click.Choice(['all', 'frameworkonly']),
    help='`all` to remove Jazz and all deployed services, \
    `frameworkonly` to remove Jazz but leave deployed services alone',
    required=True
)
@click.option('--aws_access_key', prompt=True, envvar='AWS_ACCESS_KEY_ID')
@click.option('--aws_secret_key', prompt=True, envvar='AWS_SECRET_ACCESS_KEY')
def uninstall(mode, aws_access_key, aws_secret_key):
    """Uninstalls the Jazz Stack."""
    click.secho('\n\nConfiguring uninstall', fg='blue')
    click.secho('\nLogging to `uninstall.log`', fg='green')
    os.environ['AWS_ACCESS_KEY_ID'] = aws_access_key
    os.environ['AWS_SECRET_ACCESS_KEY'] = aws_secret_key
    click.secho('\n\n Collecting terraform output vars from existing install...', fg='blue')
    stackprefix = get_terraform_output_var("jazzprefix")
    identity = get_terraform_output_var("jazzusername")
    region = get_terraform_output_var("region")
    click.secho(
        '\nRunning destroy prep with option: {0}, prefix: {1}, and identity: {2}'
        .format(mode, stackprefix, identity), fg='green')

    if mode == "all":
        destroyprep(stackprefix, identity, region, True)
    else:
        destroyprep(stackprefix, identity, region, False)

    click.secho('\nRunning terraform destroy', fg='green')

# Path: installer/helpers/destroyprep.py
# def destroyprep(stackname, identity, region, all=False):
#     # Delete the identity policy  - Created in terraform/scripts/ses.sh
#     client = boto3.client('ses', region_name=region)
#     cloudfront_client = boto3.client('cloudfront', region_name=region)
#     lambda_client = boto3.client('lambda', region_name=region)
#     cloudformation_client = boto3.client('cloudformation', region_name=region)
#     client.delete_identity_policy(
#         Identity=identity,
#         PolicyName="Policy-{0}".format(stackname)
#     )
# 
#     print("Destroy all: {0} for stack {1}".format(all, stackname))
#     # run python scripts to teardown
#     if all:
#         delete_event_source_mapping(stackname, lambda_client)
#         delete_platform_services(stackname, cloudformation_client, True)
#         delete_cf_dists(stackname, cloudfront_client, True)
#     else:
#         delete_event_source_mapping(stackname, lambda_client)
#         delete_platform_services(stackname, cloudformation_client, False)
# 
# Path: installer/helpers/terraform.py
# def exec_terraform_destroy():
#     tfCommand = [
#             'terraform', 'destroy', '--auto-approve'
#     ]
# 
#     if not tee_check_output(tfCommand, workdir=get_terraform_folder()):
#         print(
#             colors.FAIL + datetime.datetime.now().strftime('%c') + '\n' + colors.ENDC)
# 
#         print(
#             colors.FAIL + 'Terraform destroy failed! You can try re-running the uninstall' + colors.ENDC)
#     else:
#         print(
#             colors.OKGREEN + datetime.datetime.now().strftime('%c') + '\n' + colors.ENDC)
# 
#         print(
#             colors.OKGREEN + 'Terraform finished! AWS resources destroyed\n' + colors.ENDC)
# 
# def get_terraform_output_var(varname):
#     try:
#         return check_output(['terraform', 'output', varname], workdir=get_terraform_folder()).rstrip().decode('utf8')
#     except subprocess.CalledProcessError:
#         print("Failed getting output variable {0} from terraform!".format(varname))
#         sys.exit()


# Path: installer/cli/uninstallcli.py
import click
import os
from installer.helpers.destroyprep import destroyprep
from installer.helpers.terraform import exec_terraform_destroy, get_terraform_output_var

@click.command()
@click.option(
    '--mode',
    type=click.Choice(['all', 'frameworkonly']),
    help='`all` to remove Jazz and all deployed services, \
    `frameworkonly` to remove Jazz but leave deployed services alone',
    required=True
)
@click.option('--aws_access_key', prompt=True, envvar='AWS_ACCESS_KEY_ID')
@click.option('--aws_secret_key', prompt=True, envvar='AWS_SECRET_ACCESS_KEY')
def uninstall(mode, aws_access_key, aws_secret_key):
    """Uninstalls the Jazz Stack."""
    click.secho('\n\nConfiguring uninstall', fg='blue')
    click.secho('\nLogging to `uninstall.log`', fg='green')
    os.environ['AWS_ACCESS_KEY_ID'] = aws_access_key
    os.environ['AWS_SECRET_ACCESS_KEY'] = aws_secret_key
    click.secho('\n\n Collecting terraform output vars from existing install...', fg='blue')
    stackprefix = get_terraform_output_var("jazzprefix")
    identity = get_terraform_output_var("jazzusername")
    region = get_terraform_output_var("region")
    click.secho(
        '\nRunning destroy prep with option: {0}, prefix: {1}, and identity: {2}'
        .format(mode, stackprefix, identity), fg='green')

    if mode == "all":
        destroyprep(stackprefix, identity, region, True)
    else:
        destroyprep(stackprefix, identity, region, False)

    click.secho('\nRunning terraform destroy', fg='green')

    exec_terraform_destroy()