#!/usr/bin/python -tt
# playbook runner by user group
# to be run by sudo

# - get euid of user
# - get list of user's groups
# - playbook/fn/glob to list of groups
#   ex: playbook.yml: ['group1','group2']
# - lookup the name of the playbook you are trying to run from the cli args
# - if the playbook doesn't isn't matched in any of the keys
# - then they cannot run it
# - if it does  - look up if the groups the user is in is allowed to run it
# - if so call the command w/ the rest of the specified options


import os
import sys
import pwd
import grp
import fnmatch
import subprocess

username = os.getlogin()
user = pwd.getpwnam(username)

groups = [ g.gr_name for g in grp.getgrall() if username in g.gr_mem ]
groups.append(grp.getgrgid(user.pw_gid).gr_name)

groups = set(groups)

# need to read acls in from somewhere
acl = { 'filename.yaml': ['mock'],
        '*foo': ['wheel'],
        '*': ['sysadmin-main'], }


can_run = False
fn = sys.argv[1]
# exact match quick route
if fn in acl:
    pb_groups = set(acl[fn])
    if groups.intersection(pb_groups):
        can_run = True

# not exact match - slow boat
else:
    for match in acl:
        if not '*' in match and not '?' in match and not '[' in match:
            continue
        if fnmatch.fnmatch(fn, match):
            pb_groups = set(acl[match])
            if groups.intersection(pb_groups):
                can_run = True
                break

if can_run:
    print "run ansible-playbook from here and stfu and make it a shell execution"
else:
    print "You go to hell! Hax0R!"
    sys.exit(1)