#!/usr/bin/python3
#
# License: GPLv2+
# Author: Andrew Heath <aheath1992@gmail.com>

import subprocess
import argparse
import sys

# Dictionary that holds the list of users and groups.
args_dict = {}

def parse_commandline(args):
    parser = argparse.ArgumentParser(
            description='Generate an ssh authorized_keys file')
    parser.add_argument('users', metavar='USERS', type=str, nargs='+',
            help='FAS usernames and FAS group names preceeded by "@".'
            ' For example: toshio skvidal @gitfas')
    parsed = parser.parse_args(args)

    users = set()
    groups = set()
    for entry in parsed.users:
        if entry.startswith('@'):
            groups.add(entry[1:])
        elif entry == sys.argv[0]:
            continue
        else:
            users.add(entry)
# adding User list and group list to the Dictionary.
    args_dict['users'] = users
    args_dict['groups'] = groups

    return args_dict

# Function looks up group(s) provided and gets a list of the users
# and appends the them to the users list.

def group_users():
    for group in args_dict['groups']:
        list_users = subprocess.check_output(['getent', 'group', group ])
        splitlines = list_users.decode().split(':')[3]
        users = splitlines.strip()
        users = users.split(',')
        args_dict['users'].update(users)

# Takes all users in the Dictionary and gets their ssh-keys

if __name__ == '__main__':
    args = parse_commandline(sys.argv)
    group_users()
    for i in args_dict['users']:
        keys = subprocess.check_output(['sss_ssh_authorizedkeys', i])
        keys = keys.decode().strip()
        print(keys)
