#!/usr/bin/python3.11

# Copyright (C) 2010 Novell, Inc. All rights reserved.
#
# This work is subject to U.S. and international copyright laws and treaties.
# No part of this work may be used, practiced, performed, copied, distributed,
# revised, modified, translated, abridged, condensed, expanded, collected,
# compiled, linked, recast, transformed or adapted without the prior written
# consent of Novell, Inc. Any use or exploitation of this work without authorization
# could subject the perpetrator to criminal and civil liability.

import sys
from ldap3 import Server, Connection, BASE, LEVEL,SUBTREE, Tls, MODIFY_ADD, MODIFY_REPLACE, ServerPool, FIRST
from ldap3.core.exceptions import LDAPException
import os
import subprocess
import ssl

sys.path.append('/opt/novell/ncs/bin')
import clstrlib
import clstrlibss

# initialize LDAP options
certPath = subprocess.Popen(
    ['sed', '-n', 's/^TLS_CACERTDIR //p', '/etc/openldap/ldap.conf'],
    stdout=subprocess.PIPE, stderr=subprocess.PIPE
).communicate()[0]
certPath = bytes.decode(certPath).strip()
if certPath and os.path.isdir(certPath):
    tls_config = Tls(
        ca_certs_path=certPath,
        validate=ssl.CERT_REQUIRED,  
        version=ssl.PROTOCOL_TLS_CLIENT  
    )
else:
    tls_config = Tls(validate=ssl.CERT_NONE)  

def usage():
    sys.stderr.write( "Usage: " + os.path.basename( sys.argv[0] ) + " new_prxy_fdn ldap_admin_fdn\n" )

#############################################################################
#
# Function: main
#
# Returns: Nothing.   
#
# Comments:
#
def main(argv):

    if 2 > len( argv ):
        usage()
        rc = 22
    else:
        try:
            ss = clstrlibss.load()
            if ',' in ss.ldapUrl:
                servers = [Server(url.strip(),use_ssl=True,connect_timeout=8,tls=tls_config) for url in ss.ldapUrl.split(",")]
                server = ServerPool(servers, pool_strategy=FIRST,active=True)
            else:
                server = Server(ss.ldapUrl,use_ssl=True,connect_timeout=8,tls=tls_config)
            connection = Connection(server , argv[1], os.getenv( "OES_ADMIN_DATA", ""), receive_timeout=16,auto_bind=True,raise_exceptions=True)
            rc = clstrlib.addUserToNCSGroup( connection, ss.clusterDn, argv[0] )
            connection.unbind()
        except Exception as e:
            sys.stderr.write( "Failed to add user '" +  argv[0] + "' to NCS management group: " + str( e ) + "\n" )
            rc = 5

    sys.exit(rc)

if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

