#!/usr/bin/python3
import os, subprocess, sys

def gated_requires(full, boot):
    seen = set(boot)
    out = []
    for item in full:
        if item not in seen and item not in out:
            out.append(item)
    return out

def unmet(reqs, probe):
    return [req for req in reqs if not probe(req)]

def cmdline_of(pid):
    try:
        raw = open("/proc/%s/cmdline" % pid, "rb").read().split(b"\0")
    except OSError:
        return []
    return [a.decode("utf-8", "replace") for a in raw if a]

def ppid_of(pid):
    try:
        for line in open("/proc/%s/status" % pid, "r", encoding="utf-8"):
            if line.startswith("PPid:"):
                return int(line.split()[1])
    except (OSError, ValueError, IndexError):
        return 0
    return 0

def spec_from_argv():
    for arg in sys.argv[1:]:
        if arg.endswith(".spec") and os.path.isfile(arg):
            return os.path.abspath(arg)
    return ""

def spec_from_parents():
    pid = os.getppid()
    seen = set()
    for _ in range(12):
        if not pid or pid in seen:
            break
        seen.add(pid)
        for arg in cmdline_of(pid):
            if arg.endswith(".spec") and os.path.isfile(arg):
                return os.path.abspath(arg)
        pid = ppid_of(pid)
    return ""

def spec_from_builddir():
    for folder in (
        os.environ.get("RPM_SOURCE_DIR"),
        "/builddir/build/SPECS",
        "/builddir/build/SOURCES",
        os.getcwd(),
    ):
        if not folder or not os.path.isdir(folder):
            continue
        hits = sorted(
            os.path.join(folder, name)
            for name in os.listdir(folder)
            if name.endswith(".spec")
        )
        if len(hits) == 1:
            return hits[0]
    return ""

def sources_dir_for(spec):
    """mock keeps local SourceN under SOURCES, git keeps them beside the .spec"""
    specdir = os.path.dirname(os.path.abspath(spec))
    for folder in (
        os.environ.get("RPM_SOURCE_DIR"),
        "/builddir/build/SOURCES",
        specdir,
    ):
        if folder and os.path.isdir(folder):
            return folder
    return specdir

def spec_dir_for(spec):
    specdir = os.path.dirname(os.path.abspath(spec))
    for folder in (
        os.environ.get("RPM_SPEC_DIR"),
        "/builddir/build/SPECS",
        specdir,
    ):
        if folder and os.path.isdir(folder):
            return folder
    return specdir

def buildrequires(spec, extra):
    sourcedir = sources_dir_for(spec)
    specdir = spec_dir_for(spec)
    cmd = [
        "rpmspec", "-q", "--buildrequires",
        "--define", "_sourcedir " + sourcedir,
        "--define", "_specdir " + specdir,
        "--define", "oreon_bootstrap %{nil}",
        "--define", "oreon_bootstrap_probe 1",
        *extra, spec,
    ]
    r = subprocess.run(cmd, capture_output=True, text=True)
    if r.returncode != 0:
        return None
    return [line.strip() for line in r.stdout.splitlines() if line.strip()]

def available(req):
    """True only if dnf can depsolve an install from configured repos."""
    import shutil
    import tempfile
    name = req.split()[0]
    if not name or name.startswith(("%", "(")):
        return False
    try:
        import dnf
        import dnf.exceptions
    except ImportError:
        return False
    tmp = tempfile.mkdtemp(prefix="oreon-bootstrap-")
    base = dnf.Base()
    try:
        base.conf.install_weak_deps = False
        base.conf.best = False
        base.conf.cachedir = os.path.join(tmp, "cache")
        base.conf.persistdir = os.path.join(tmp, "persist")
        base.conf.logdir = os.path.join(tmp, "log")
        base.read_all_repos()
        base.fill_sack(load_system_repo=False)
        base.install(req)
        base.resolve()
        return True
    except (dnf.exceptions.PackageNotFoundError, dnf.exceptions.MarkingError,
            dnf.exceptions.DepsolveError, dnf.exceptions.Error, Exception):
        return False
    finally:
        try:
            base.close()
        except Exception:
            pass
        shutil.rmtree(tmp, ignore_errors=True)

def main():
    spec = spec_from_argv() or spec_from_parents() or spec_from_builddir()
    if not spec:
        return 0
    full = buildrequires(spec, [])
    boot = buildrequires(spec, ["--with", "bootstrap"])
    if boot is None:
        boot = buildrequires(spec, ["--define", "perl_bootstrap 1"])
    # full parses, bootstrap mode does not → still need bootstrap (real
    # rpmbuild has the right _sourcedir for %include, the probe may not)
    if full is not None and boot is None:
        print("1")
        return 0
    if full is None or boot is None:
        return 0
    gap = gated_requires(full, boot)
    if unmet(gap, available):
        print("1")
    return 0

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