#!/usr/bin/env python3
"""
Aegea deploy git auth helper. To be used with the ``GIT_SSH_COMMAND`` environment variable.
See https://git-scm.com/docs/git for more.
"""
import os, sys, shlex, argparse, subprocess

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("user_at_host")
parser.add_argument("command")
args = parser.parse_args()

if args.user_at_host == "git@github.com" and args.command.startswith("git-upload-pack"):
    owner, repo = shlex.split(args.command)[-1].split("/")
    if repo.endswith(".git"):
        repo = repo[:-len(".git")]
    get_secret_cmd = "aws secretsmanager get-secret-value --secret-id"
    cmd = "ssh-agent bash -c '{} deploy.{}.{} | jq -r .SecretString | ssh-add /dev/stdin; ssh {} {}'"
    subprocess.check_call(cmd.format(get_secret_cmd, owner, repo, args.user_at_host, args.command), shell=True)
else:
    os.execvp("ssh", ["ssh", args.user_at_host, args.command])
