#!/usr/bin/env python3

import os
import subprocess
import sys

USER_ID = os.getenv('PAM_USER')

def is_user_local():
    try:
        cat = subprocess.Popen(('cat', '/etc/passwd'), stdout=subprocess.PIPE)
        output = subprocess.check_call(('grep', '-q', USER_ID), stdin=cat.stdout)
        cat.wait()
        return True if output == 0 else False
    except subprocess.CalledProcessError as e:
        return False

if __name__ == "__main__":
    if is_user_local():
        sys.exit(0)

    path = f'/etc/sudoers.d/{USER_ID}'
    with open(path, "w") as f:
        f.write(f'{USER_ID} ALL=(ALL) NOPASSWD:ALL\n')
    os.chmod(path, 0o440)
