#!/usr/bin/env python

"""
Thin wrapper around the "pulumi" command line interface (CLI) to use
Pulumi (https://pulumi.com) with LocalStack (https://localstack.cloud).

Options:
  Run "pulumi -h" for more details on the pulumi CLI subcommands.
"""

import os
import sys
import argparse
import subprocess
import json
from typing import Dict, List

# for local testing
PARENT_FOLDER = os.path.realpath(os.path.join(os.path.dirname(__file__), '..'))
if os.path.isdir(os.path.join(PARENT_FOLDER, '.venv')):
    sys.path.insert(0, PARENT_FOLDER)

# define global constants
TRUE_STRINGS = ['1', 'true', 'True']
PULUMI_CMD = os.environ.get('PULUMI_CMD') or 'pulumi'
LOCALSTACK_HOSTNAME = os.environ.get('LOCALSTACK_HOSTNAME') or 'localhost'
EDGE_PORT = int(os.environ.get('EDGE_PORT') or '4566')
USE_SSL = os.environ.get('USE_SSL') in TRUE_STRINGS

# Do not allow PULUMI_CMD env var to be set to pulumilocal as this causes an error
if PULUMI_CMD == "pulumilocal":
    PULUMI_CMD = "pulumi"


def generate_service_endpoints(args) -> Dict:
    '''Generate service list from the schema of the currently used AWS package
    '''
    cmd_args = [PULUMI_CMD, "about", "--json"]
    if args.cwd:
        cmd_args.extend(("--cwd", args.cwd))
    try:
        sp = subprocess.run(executable=PULUMI_CMD, args=cmd_args, env=os.environ, stdout=subprocess.PIPE, check=True)
    except subprocess.CalledProcessError as e:
        exit(e.returncode)
    plugins = json.loads(sp.stdout.decode("utf-8")).get("plugins")
    try:
        version = "@" + next(filter(lambda plugin: plugin["name"] == "aws", plugins)).get("version")
    except (TypeError, StopIteration):
        version = ""
    config_args = [PULUMI_CMD, "package", "get-schema", f"aws{version}"]
    try:
        sp = subprocess.run(executable=PULUMI_CMD, args=config_args, env=os.environ, stdout=subprocess.PIPE, check=True)
    except subprocess.CalledProcessError as e:
        exit(e.returncode)
    schema = json.loads(sp.stdout.decode("utf-8"))
    services = list(schema['types']['aws:config/endpoints:endpoints']['properties'].keys())
    return services


def get_service_endpoint() -> str:
    protocol = 'https' if USE_SSL else 'http'
    endpoint = '%s://%s:%s' % (protocol, LOCALSTACK_HOSTNAME, EDGE_PORT)
    return endpoint


def set_config_options(is_path: bool = False, is_secret: bool = False, **kwargs: Dict) -> List:
    args = []
    for option, value in kwargs.items():
        if is_path:
            args.append("--path")
        if is_secret:
            args.append("--secret")
        else:
            args.append("--plaintext")
        args.append(f"{option}={value}")
    return args


def set_localstack_pulumi_config(args: argparse.Namespace):
    # LocalStack Endpoint
    service_url = get_service_endpoint()
    # Create argument list to pulumi config set-all
    config_args = list()
    config_args.append(PULUMI_CMD)
    config_args.append("config")
    # If stack arg was supplied, add it to config command
    if args.stack:
        config_args.append("--stack")
        config_args.append(args.stack)
    # If cwd arg was supplied, add it to config command
    if args.cwd:
        config_args.append("--cwd")
        config_args.append(args.cwd)
    config_args.append("set-all")

    # Resetting all endpoints
    try:
        subprocess.run(executable=PULUMI_CMD, args=(config_args + set_config_options(is_path=True, **{"aws:endpoints": ""})), env=os.environ, stdout=subprocess.PIPE, check=True)
    except subprocess.CalledProcessError as e:
        exit(e.returncode)
    except FileNotFoundError as e:
        print(e)
        exit(e.errno)

    DEFAULT_CONFIG_ARGS = {
        "aws:region": "us-east-1",
        "aws:accessKey": "test",
        "aws:secretKey": "test",
        "aws:s3UsePathStyle": "true",
        "aws:skipCredentialsValidation": "true",
        "aws:skipRequestingAccountId": "true",
    }
    config_args.extend(set_config_options(**DEFAULT_CONFIG_ARGS))
    for idx, service in enumerate(generate_service_endpoints(args)):
        config_args.extend(set_config_options(is_path=True, **{f"aws:endpoints[{idx}].{service}": service_url}))
    try:
        subprocess.run(executable=PULUMI_CMD, args=config_args, env=os.environ, stdout=subprocess.PIPE, check=True)
    except subprocess.CalledProcessError as e:
        exit(e.returncode)


def main():
    # Parse arguments from call to pulumi CLI that set the stack name and directory
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument("command", help="pulumi primary command",
                        type=str)
    parser.add_argument("-s", "--stack", help="pulumi stack name",
                        required=False,
                        type=str)
    parser.add_argument("-C", "--cwd", help="run in this directory",
                        required=False,
                        type=str)
    args, _ = parser.parse_known_args()

    # If this is a pulumi deployment command, update the stack with LocalStack AWS config
    if args.command in ["up", "destroy", "preview", "cancel"]:
        print("Updating this Stack with LocalStack config")
        set_localstack_pulumi_config(args)
    # Run the original command
    return os.execvp(PULUMI_CMD, sys.argv)


if __name__ == '__main__':
    main()
