#!/usr/bin/python3
#
# Univention Monitoring Plugin
#  check_univention_ad_connector: check Active Directory connector status
#
# SPDX-FileCopyrightText: 2011-2025 Univention GmbH
# SPDX-License-Identifier: AGPL-3.0-only

import re
import subprocess

from univention.config_registry import ucr
from univention.monitoring import Alert


RE_REJECT = re.compile(r'^ *[1-9]+: *(AD|UCS) DN:.*')


class ADConnector(Alert):

    def write_metrics(self):
        connectors = ('connector %s' % ucr.get('connector/listener/additionalbasenames', '')).split(' ')
        for connector in connectors:
            if not connector:
                continue
            self.write_connector_metrics(len(connectors), connector)

    def write_connector_metrics(self, connectors, connector):
        # check whether we can connect to the AD
        # CRITICAL: in case we cannot connect to the AD
        rc = self.exec_command(['univention-adsearch', '-c', connector, 'cn=users'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)[0]
        self.write_metric('univention_ad_connector_ad_reachable', 1 if rc == 0 else 0, connector=connector)

        # check whether the AD connector is running; for this, get the exact command
        # that was used to launch the process; remove multiple whitespaces and quotes
        # in order to match the command via check_procs
        # WARNING: if not exactly the number of configured connectors is running
        # CRITICAL: if no process is running
        rc, output = self.exec_command(['/usr/lib/nagios/plugins/check_procs', '-w', '%d:%d' % (connectors, connectors), '-c', '1:', '--ereg-argument-array', '^([^ ]+)?python3.*univention.connector.ad.main'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        if rc == 1:
            rc2, output = self.exec_command(['/usr/lib/nagios/plugins/check_procs', '-w', '%d' % (connectors,), '-c', '1:', '--ereg-argument-array', '^([^ ]+)?python3.*univention.connector.ad.main'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            output = {
                1: 'More than the %s configured AD connectors are running!' % (connectors,),
                2: 'Less than the %s configured AD connectors are running!' % (connectors,),
            }.get(rc2, 'Unknown state!')
        elif rc == 2:
            output = 'No AD connector is running!'
        else:
            output = 'Unknown state!'
        self.log.debug(output)
        self.write_metric('univention_ad_connector_running', rc if rc in (0, 1, 2) else -1, connector=connector)

        # count rejects by parsing the output of univention-adconnector-list-rejected
        # WARNING: if there are any rejects
        rc, output = self.exec_command(['univention-adconnector-list-rejected', '-c', connector])
        rejects = sum(1 for line in output.splitlines() if RE_REJECT.match(line))

        self.write_metric('univention_ad_connector_rejects', rejects, connector=connector)
        if rejects:
            self.log.debug('Found %d reject(s)! Please check output of univention-adconnector-list-rejected.', rejects)


if __name__ == '__main__':
    ADConnector.main()
