# Copyright 2026 SigmaSRC, Inc. All Rights Reserved.

"""Gather MD5 checksums from the filesystem."""

import os
import re
import logging

from sigma.util import config
from sigma.gather import fswalker

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

options = config.Options()
limited = options.limit_gathers

if os.name == "nt":
    # XXX I betcha this doesn't work on Win98
    systemdrive = os.popen("echo %systemdrive%").read().strip()
    ROOTS = [systemdrive + "\\"]
    if limited:
        ROOTS = ["C:\\Python23"]
elif os.name == "mac":
    # XXX Need to figure out how to collect the local hard drives
    ROOTS = ["???:"]
else:
    # Unix
    assert os.sep == "/"
    ROOTS = ["/"]
    if limited:
        ROOTS = ["/usr/local/lib/python2.3"]

def Gather(collector):
    skips = makeskips()
    if limited:
        logger.warn("Limiting md5 gathers to %r", ROOTS)
    fsw = fswalker.FileSystemWalker(collector, skips)
    for root in ROOTS:
        fsw.walk(root)

# fs types we skip
SKIPTYPES = ["smbfs", "swap", "auto", "devpts", "proc", "usbdevfs",
             "tmpfs", "nfs", "ncpfs"]

def makeskips():
    """Return list of pathnames to skips, for example NFS mount points."""
    if os.name != "posix":
        logger.debug("Not a posix system, let's hope for no mount points")
        return []
    if  not os.path.exists("/bin/mount"):
        logger.warn("/bin/mount not found -- can't exclude mount points")
        return []
    skips = []
    for line in os.popen("/bin/mount", "r"):
        m = re.match(r"^(.*) on (.*) type (.*) \((.*)\)$", line)
        if m is None:
            logger.warn("Can't parse mount output line %r", line)
        else:
            device, mountpoint, type, mode = m.groups()
            if type in SKIPTYPES:
                logger.debug("Skip %r", mountpoint)
                skips.append(mountpoint)
    return skips

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

if __name__ == "__main__":
    _test()
