#!/usr/bin/env python3

# Usage: git loadkey
#
# Configuration format:
#   [
#     {
#       "match": ".*",
#       "keyname": "...",
#     }
#   ]

import sys
import re
import subprocess
import os.path
import json

CONFIG = os.path.expanduser('~/.config/git-committerconfig.json')


def main():
    try:
        repos = [x.split()[1] for x in subprocess.check_output(['git', 'remote', '-v'], universal_newlines=True).split('\n') if len(x.strip()) > 0]
    except:
        print('Could not find origin, not loading key.')
        return 0

    if os.path.isfile(CONFIG):
        combinations = json.loads(open(CONFIG).read())
    else:
        print('Config ({}) found.'.format(CONFIG))
        return 1

    required_keys = []

    for repo in sorted(set(repos)):
        for combi in combinations:
            if re.search(combi['match'], repo):
                required_keys.append(combi['keyname'])
                break

    for key in sorted(set(required_keys)):
        print('Loading key "{}"...'.format(key))
        subprocess.check_call(['vault-sshadd', key])

    return 0

if __name__ == "__main__":
    exit(main())
