#!/usr/bin/python3 -u

import glob
import importlib.util
import os
import sys
import subprocess


def load_source(name, path):
    spec = importlib.util.spec_from_file_location(name, path)
    module = importlib.util.module_from_spec(spec)
    sys.modules[name] = module
    spec.loader.exec_module(module)
    return module


data = sys.stdin.readlines()

if (os.path.isdir('hooks/post-receive.d')):
    for hook in os.listdir('hooks/post-receive.d'):
        hook = os.path.join('hooks/post-receive.d', hook)
        if (hook.endswith(('~','.bak','.rpmsave','.rpmnew')) or
                not (os.path.isfile(hook) and os.access(hook, os.X_OK))):
            continue
        hook_process = subprocess.Popen([hook], stdin=subprocess.PIPE)
        try:
            for line in data:
                hook_process.stdin.write(line.encode('utf-8'))
        except IOError:
            pass
        hook_process.communicate()

for pluginfile in glob.glob('hooks/post-receive.python.d/*.py'):
    plugin = load_source(os.path.basename(pluginfile), pluginfile)
    plugin.run(data)
