#!/usr/bin/env python3
'''special agent call file'''
# -*- mode: Python; encoding: utf-8; indent-offset: 4; autowrap: nil -*-

# (c) Michael Honkoop <mhonkoop@comsolve.nl>

# License: GNU General Public License v2

import sys
import ldap
from cmk_addons.plugins.edirectory_monitor.lib import (
    print_sections,
)

def main():
    args = sys.argv[1:]
    if len(args) < 3:
        print("Usage: script.py <LDAP_URI> <BIND_DN> <PASSWORD>")
        sys.exit(1)

    ldap_uri = args[0]
    binddn = args[1] 
    pw = args[2]
    basedn = "cn=Monitor"
    searchFilter = "(objectClass=*)"
    searchAttribute = ["*"]
    searchScope = ldap.SCOPE_SUBTREE

    try:
        # ignore TLS certificate checking
        ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
        # Create LDAPObject instance with given uri
        l = ldap.initialize(ldap_uri)
        # Set LDAP protocol version used
        l.protocol_version = ldap.VERSION3
    except ldap.LDAPError as e:
        print(f"Failed to initialize LDAP connection: {e}")
        sys.exit(1)

    try:
        # Attempt to bind with given credentials
        l.simple_bind_s(binddn, pw)
    except ldap.INVALID_CREDENTIALS:
          print("Authentication to the LDAP host has failed.")
          sys.exit(1)
    except ldap.LDAPError as e:
        print(f"LDAP error during bind: {e}")
        sys.exit(1)

    try:
        ldap_result_id = l.search(basedn, searchScope, searchFilter, searchAttribute)
        result_set = []

        while True:
            result_type, result_data = l.result(ldap_result_id, 0)
            if (result_data == []):
                break
            elif result_type == ldap.RES_SEARCH_ENTRY:
                result_set.append(result_data)

        print('<<<edirectory_monitor_agent:sep(124)>>>')
        for i in range(len(result_set)):
            for val in result_set[i]:
                for element in val:
                    if "cn=Agent" in element:
                        print_sections(result_set[i])
        print('<<<edirectory_monitor_dclient:sep(124)>>>')
        for i in range(len(result_set)):
            for val in result_set[i]:
                for element in val:
                    if "cn=Dclient" in element:
                        print_sections(result_set[i])
        print('<<<edirectory_monitor_dhost:sep(124)>>>')
        for i in range(len(result_set)):
            for val in result_set[i]:
                for element in val:
                    if "cn=DHOST" in element:
                        print_sections(result_set[i])
        print('<<<edirectory_monitor_ldap:sep(124)>>>')
        for i in range(len(result_set)):
            for val in result_set[i]:
                for element in val:
                    if "cn=LDAP" in element:
                        print_sections(result_set[i])
        print('<<<edirectory_monitor_recordmanager:sep(124)>>>')
        for i in range(len(result_set)):
            for val in result_set[i]:
                for element in val:
                    if "cn=RecordManager" in element:
                        print_sections(result_set[i])
        print('<<<edirectory_monitor_idm:sep(124)>>>')
        for i in range(len(result_set)):
            for val in result_set[i]:
                for element in val:
                    if "cn=IDM" in element:
                        print_sections(result_set[i])

    except ldap.LDAPError as e:
        print(f"LDAP search failed: {e}")

    finally:
        l.unbind_s()

if __name__ == "__main__":
    main()

