# Copyright 2026 SigmaSRC, Inc. All Rights Reserved.

"""Reader and writer for the enterprise flag.

When we are an enterprise agent, at least one of $AVCONF/enterprise or
$AVCONF/golden must exist; when we are not an enterprise agent,
neither file must exist.

XXX Should get rid of 'golden' once all installers are fixed.

"""

import os
import logging

from sigma.util import config

logger = logging.getLogger("util.enterprise")
options = config.Options()

FILE1 = os.path.join(options.agentconf, "enterprise")
FILE2 = os.path.join(options.agentconf, "golden")

def readEnterpriseFlag():
    """Reads the enterprise flag."""
    return os.path.exists(FILE1) or os.path.exists(FILE2)

def writeEnterpriseFlag(flag):
    """Persists the enterprise flag."""
    if flag:
        if not os.path.exists(FILE1):
            f = open(FILE1, "w")
            f.close()
    else:
        if os.path.exists(FILE1):
            remove(FILE1)
        if os.path.exists(FILE2):
            remove(FILE2)

def remove(fn):
    """Tries to remove a file, logging errors.  Won't raise os.error."""
    try:
        os.remove(fn)
    except os.error as err:
        log.error("Can't remove %s: %s", fn, err)
