#!/usr/bin/env python

"""
Thin wrapper around the "aws" command line interface (CLI) for use with LocalStack.

The "awslocal" CLI allows you to easily interact with your local services without
having to specify "--endpoint-url=http://..." for every single command.

Example:
Instead of the following command ...
aws --endpoint-url=https://localhost:4568 --no-verify-ssl kinesis list-streams
... you can simply use this:
awslocal kinesis list-streams

Options:
  Run "aws help" for more details on the aws CLI subcommands. 
"""

import os
import sys
import subprocess

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)

from localstack_client import config


def get_service():
    for param in sys.argv[1:]:
        if not param.startswith('-'):
            return param


def get_service_endpoint():
    service = get_service()
    if service == 's3api':
        service = 's3'
    return config.get_service_endpoints().get(service)

def usage():
    print(__doc__.strip())


def main():
    if len(sys.argv) > 1 and sys.argv[1] == '-h':
        return usage()

    endpoint = get_service_endpoint()
    if not endpoint:
        print('ERROR: Unable to find LocalStack endpoint for service "%s"' % get_service())
        return
    args = list(sys.argv)
    args[0] = 'aws'
    args.insert(1, '--endpoint-url=%s' % endpoint)
    if 'https' in endpoint:
        args.insert(2, '--no-verify-ssl')

    env_dict = os.environ.copy()
    env_dict['PYTHONWARNINGS'] = 'ignore:Unverified HTTPS request'
    process = subprocess.Popen(args, stderr=subprocess.STDOUT,
        stdout=subprocess.PIPE, stdin=subprocess.PIPE, env=env_dict)
    while True:
        nextline = process.stdout.readline()
        if nextline == '' and process.poll() is not None:
            break
        sys.stdout.write(nextline)
        sys.stdout.flush()


if __name__ == "__main__":
    main()
