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

"""Show directives.

Usage: %prog [directiveID] ...

By default all directives are shown; if one or more directive ids are
given, only those are shown.

"""

import os
import sys
import time
import optparse

from sigma.util import config
from sigma.util.errors import error, usage
from sigma.util import compliance
from sigma.protocol import xmlproto

options = config.Options()

parser = optparse.OptionParser(usage=__doc__.strip())
parser.add_option("-q", "--quick", dest="quick", action="store_true",
                  help="show show directives only, skip rules")

def main(args=None):
    opts, args = parser.parse_args(args)
    policydir = options.datapath("policy")
    if not os.path.exists(policydir):
        print("No policy directory")
        return 0
    names = [name for name in os.listdir(policydir)
                  if os.path.normcase(name).startswith("dir.")]
    if not names:
        print("No directives")
        return 0
    compl = compliance.Compliance(options)
    names.sort()
    first = True
    shown = []
    sts = 0
    for name in names:
        fn = os.path.join(policydir, name)
        try:
            directive = xmlproto.load_directive(fn)
        except Exception as err:
            print("%s: %s: %s" % (name, err.__class__.__name__, err))
            sts = 1
            continue
        if args and directive.id not in args:
            continue
        shown.append(directive.id)
        if directive.task:
            secs = directive.task.freq
        else:
            secs = None
        if first:
            first = False
        elif not opts.quick:
            print()
        print("Directive %s.%s: %s (freq=%s, enf=%s, pw-mode=%s)" % (
            directive.id or "pw", directive.version, directive.name,
            secs, directive.enforce, directive.poliwall_mode))
        key = "%s.%s" % (directive.id, directive.version)
        record = compl.get(key)
        if record is not None:
            t = time.ctime(record[0]), record[1], record[2], record[3]
            print("   Last run: %s; %d rules, %d compliant, %d N/A" % t)
        if opts.quick:
            continue
        for rule in directive.rules:
            if directive.enforce in (None, True):
                s = "(%.1s)" % rule.enforce
            else:
                s = ""
            print("%s/%s%s: %s" % (rule.id, rule.template_id, s, rule.name))
            if rule.parameters:
                print(" "*8, end=" ")
                for param in rule.parameters:
                    print("%s=%s" % (param.name, param.value), end=" ")
                print()
    if args:
        for arg in args:
            if arg not in shown:
                print("Directive %s not found." % arg)
                sts = 1
    return sts

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