#!/usr/bin/env python3
# Copyright 2026 SigmaSRC, Inc. All Rights Reserved.

"""Show matrix contents.

Usage: %prog [-s] [pattern] ...

If one or more pattern arguments are present, only host groups whose
name matches at least one of the patterns.  Patterns may be regular
expressions; in the simplest case, think of them as substrings.

"""

import re
import sys
from optparse import OptionParser

from sigma.util.errors import usage
from sigma.runtime.rtlib import Host
from sigma.runtime.pwall import RangeSet
from sigma.runtime.matrix import loadmatrix

parser = OptionParser(usage=__doc__.strip())
parser.add_option("-s", "--short", dest="short", action="store_true",
                  help="show group names and counts only")

def main(args=None):
    opts, args = parser.parse_args(args)
    patterns = [re.compile(arg, re.IGNORECASE) for arg in args]
    m = loadmatrix()
    print("Matrix ID =", m.getid())
    names = list(m.gethostgroupnames())
    names.sort()
    for name in names:
        if patterns:
            for p in patterns:
                if p.search(name):
                    break # pattern matching loop
            else:
                continue # outer loop
        group = m.gethostgroup(name)
        if group is None:
            print(name, "(none)")
        else:
            # Can't use len(group) -- somehow it overflows!
            name += " (%d)" % int(group.__len__())
            if opts.short:
                print(name)
            elif isinstance(group, RangeSet):
                format(name, str(group).lstrip("{").rstrip("}"))
            else:
                group = list(group)
                group.sort()
                x = list(map(str, group))
                format(name, ", ".join(x))

def format(label, value, max=79):
    label += ":"
    # This used to use textwrap, but it was too slow
    print(label, end=" ")
    col = len(label)
    for word in value.split():
        col += 1 + len(word)
        if col > max:
            print()
            print(" "*3, end=" ")
            col = 4 + len(word)
        print(word, end=" ")
    print()

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