# Copyright 2026 SigmaSRC, Inc. All Rights Reserved.

"""Gather RPM version information."""

# System imports
import os
import sys
import logging

# Local imports
from sigma.util import config

logger = logging.getLogger("gather.gather_rpms")

FIELDS = """
=NAME
=VERSION
=RELEASE
FILENAMES
FILESIZES
FILEMODES
FILEMTIMES
FILEUSERNAME
FILEGROUPNAME
FILEMD5S
""".split()

def Gather(collector):
    if sys.platform != "linux2":
        raise RuntimeError("can't gather RPM info on %s system" % sys.platform)
    fieldsubs = ["%%{%s}" % f for f in FIELDS]
    columns = len(fieldsubs)
    options = config.Options()
    if options.limit_gathers:
        logger.warning("Limiting rpms gathers to python")
        command = "rpm -q --qf '[%s\n]' python" % "".join(fieldsubs)
    else:
        command = "rpm -qa --qf '[%s\n]'" % "".join(fieldsubs)
    it = iter(os.popen(command, "r"))

    line = next(it)
    table = collector.table("rpms",
        """pkgname pkgversion pkgrelease filename size mode mtime
           username groupname md5""".split())
    for line in it:
        if line.endswith("\n"):
            line = line[:-1]
        fields = line.split("")
        if len(fields) == columns:
            table.add(fields)
        # else: #  Skip the entry and log the failure.
            # XXX_WAIT_FOR_LOG_FACILITY

def _test():
    from sigma.gather import gathering
    gathering.test(Gather)

if __name__ == "__main__":
    _test()
