# Copyright 2026 SigmaSRC, Inc. All Rights Reserved.

"""Gather upgrade status information."""

if __name__ == "__main__":
    import os
    import sys
    try:
        import sigma
    except ImportError:
        sys.path.append(os.path.join(os.pardir, os.pardir))
    del sys
    del os

import os

from sigma.util import config

options = config.Options()

def Gather(collector):
    t = collector.table("upgrade", ["version", "status"])
    active_version = read_active_version()
    if active_version:
        t.add([active_version, "active"])
    dn = options.agentversions
    try:
        names = os.listdir(dn)
    except os.error as msg:
        return
    for name in names:
        # XXX Should we report incomplete versions?
        version = read_version(os.path.join(dn, name))
        # If version.txt exists, the version was loaded successfully
        if version and version != active_version:
            t.add([version, "loaded"])

def read_active_version():
    return read_version(options.agentactive)

def read_version(dirname):
    if not os.path.isdir(dirname):
        return None
    try:
        f = open(os.path.join(dirname, "version.txt"))
    except IOError as err:
        return None
    try:
        line = f.readline()
    finally:
        f.close()
    line = line.strip()
    if line:
        return line
    return None

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

if __name__ == "__main__":
    _test()
