#!/usr/bin/python
#
# Version 0.1
#
# This Localcheck is still a work in progress - do not use it for production !!

import sys
import ldap
import json
import re

def print_list(the_list):
    for each_item in the_list:
        if isinstance(each_item, list):
            print_list(each_item)
        else:
            jsonArray = json.loads(json.dumps(each_item))
            # start creating resultArray elements
            resultArray = ['0 \"eDirectory ']
            detailArray = []
            # add result efrom sublist key, but strip leading and trasiling spaces
            resultArray.append(' '.join(jsonArray[0].split(',')[::-1]).replace('cn=Monitor', '').replace('cn=', '').strip() + "\" ")

            for k,v in jsonArray[1].items():
                # objectclass is not intersting for monitoring, so omitting it
                if k == "objectclass":
                    continue
                else:
                    # put the resulting keys in an array, and reverse the order
                    keyresult = jsonArray[0].split(',')[::-1]
                    # strip whitespaces and other unwanted information
                    keytxtresult = (' '.join(keyresult).replace('cn=Monitor', '').replace('cn=', '').strip())
                    # join the values into a string
                    valueresult = ' '.join(str(e) for e in v)
                    # sanitize the timestamps if they are present
                    valueresult = re.sub('(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})([Z])', r'\3-\2-\1 \4:\5:\6', valueresult)
                    # usecases of formatting data differently
                    if "BackGroundProc" in keytxtresult or "Agent Status" in keytxtresult:
                        resultArray.append("- ")
                        resultArray.append(k + ":" + valueresult)
                        resultArray.append(' ')
                    else:
                        # append items to resultArray, but skip non-interesting items
                        if "CheckPointThreadForceStartTime" in k or "CheckPointThreadStartTime" in k:
                            continue
                        else:
                            resultArray.append(k + "=" + valueresult)
                            resultArray.append('|')
                            detailArray.append(k + ":" + valueresult)
            #remove last item from array
            resultArray.pop()
            # print the resulting array as a string removing unwanted text
            resultStr = ''.join(str(e) for e in resultArray).replace(" Bytes", "").replace(" KB", "") + " " + ' '.join(str(e) for e in detailArray)
            if "BackGroundProc" in resultStr:
                continue
            else:
                print(resultStr)


l = ldap.initialize('ldaps://localhost:636')
binddn = "my_bind_user"
pw = "my_bind_user_password"
basedn = "cn=Monitor"
searchFilter = "(objectClass=*)"
searchAttribute = ["*"]
#this will scope the entire subtree under Monitor
searchScope = ldap.SCOPE_SUBTREE
#Bind to the server
try:
    l.protocol_version = ldap.VERSION3
    l.simple_bind_s(binddn, pw)
except ldap.INVALID_CREDENTIALS:
  print "Your username or password is incorrect."
  sys.exit(0)
except ldap.LDAPError, e:
  if type(e.message) == dict and e.message.has_key('desc'):
      print e.message['desc']
  else:
      print e
  sys.exit(0)
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
        else:
            if result_type == ldap.RES_SEARCH_ENTRY:
                result_set.append(result_data)
#    print(type(result_set))

    for i in range(len(result_set)):
        print_list(result_set[i])

except ldap.LDAPError, e:
    print e
l.unbind_s()