#!/usr/bin/env python

import argparse
import six

from subprocess import check_output, Popen, PIPE, STDOUT
import sys
import re

def run_argparser():
    p = argparse.ArgumentParser(description='Forwards onto either the CodeCommit Credential Helper or the OS X Keychain Credential Helper depending on URL')
    p.add_argument('verb', action='store', nargs=1, type=six.text_type, help='the verb to pass onto the credential helper', metavar='V')
    p.add_argument('--profile','-p', action='store', nargs=1, type=six.text_type, help='the configured profile to use with the credential helper', metavar='P', required=False)
    a = p.parse_args()
    if a.profile:
        profile = a.profile[0]
    else:
        profile = None
    return a.verb[0], profile

def get_host(stdin):
    request = stdin.split('\n')
    for line in request:
        try:
            item, value = line.split('=', 1)
        except ValueError:
            return None
        if item == 'host':
            return value
    return None

def is_codecommit(stdin):
    host = get_host(stdin)
    if host and re.match('^git-codecommit\.([a-z0-9\-])+\.amazonaws\.com$', host):
        return True
    else:
        return False

def get_osxkeychain_helper():
    return check_output(['git','--exec-path']).decode().strip() + '/git-credential-osxkeychain'

def call_codecommit_helper(verb, profile, stdin):
    command = ['aws', 'codecommit', 'credential-helper', verb]
    if profile:
        command.append('--profile')
        command.append(profile)

    process = Popen(command,stdout=PIPE, stdin=PIPE)
    out, err = process.communicate(input=stdin.encode())
    print(out.decode())
    exit(process.wait())

def call_osxkeychain_helper(verb, stdin):
    command = [ get_osxkeychain_helper(), verb ]
    process = Popen(command,stdout=PIPE, stdin=PIPE)
    out, err = process.communicate(input=stdin.encode())
    print(out.decode())
    exit(process.wait())

def main():
    verb, profile = run_argparser()
    stdin = sys.stdin.read()

    if is_codecommit:
        call_codecommit_helper(verb, profile, stdin)
    else:
        call_osxkeychain_helper(verb, stdin)

if __name__ == '__main__':
    sys.exit(main())
