#!/usr/bin/env python3.11
# ------------------------------------------------------------------------------
# Copyright [2023-2025] Open Text.
#
# The only warranties for products and services of Open Text and its
# affiliates and licensors (“Open Text”) are as may be set forth in the
# express warranty statements accompanying such products and services.
# Nothing herein should be construed as constituting an additional
# warranty. Open Text shall not be liable for technical or editorial
# errors or omissions contained herein. The information contained herein
# is subject to change without notice.
#
# Except as specifically indicated otherwise, this document contains
# confidential information and a valid license is required for possession,
# use or copying. If this work is provided to the U.S. Government,
# consistent with FAR 12.211 and 12.212, Commercial Computer Software,
# Computer Software Documentation, and Technical Data for Commercial Items
# are licensed to the U.S. Government under vendor's standard commercial
# license.
# -------------------------------------------------------------------------

import json
import os.path
import configparser
import logging
import oes_cert_mgmt_utils

CERT_PATH = "/etc/opt/novell/cis/db/certs/client-cert.pem"
OUT_JSON_PATH = "/var/opt/novell/oes-cert-mgmt/servicecerts/cis-mariadb.json"
CIS_CONF_PATH = "/etc/opt/novell/cis/config"
CIS_CONF_PATH_FOR_SCALE="/etc/opt/novell/cis-scale/config"
SECURE_DB_CONNECTION_SEARCH_STRING = "SECURE_DB_CONNECTION"
DB_CLIENT_CERT_PATH_SEARCH_STRING = "DB_CLIENT_CERT_PATH"

LOG_PATH = "/var/opt/novell/log/oes-cert-mgmt/oes-cert-mgmt.log"

logger = logging.getLogger('Logger')
logLevel = oes_cert_mgmt_utils.getloglevel()
logger.setLevel(logLevel)

def initialize_logger():
    """
    Initialize logger.
    """
    rfh = logging.handlers.RotatingFileHandler(LOG_PATH, maxBytes=1024*1024*10, backupCount=2)
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', '%m/%d/%Y %I:%M:%S')
    rfh.setFormatter(formatter)
    logger.addHandler(rfh)

def read_config(filePath, searchString):
    """
    Get the config value from the conf file
    """
    found = False
    valuestr = ""
    try:
        with open(filePath,'r') as file:
            for line in file.readlines():
                if not line.strip().startswith("#"):
                    if searchString in line:
                        elements = line.strip().split("=")
                        if len(elements) >= 2:
                            valuestr = elements[1].split('\t')[-1].split(' ')[-1].strip("\"")
                            found = True
                            break

            if found == False:
                logger.warn("cis - "+ str(searchString)+ " is not found in conf file")
                exit(200)

    except FileNotFoundError as e:
        exit(200)

    finally:
        if(file != None):
            file.close()

    return valuestr

def deploymenttype():
    if os.path.exists('/etc/opt/novell/cis/configurationStatus.json'):
        configStatusjson = open('/etc/opt/novell/cis/configurationStatus.json')
        data = json.load(configStatusjson)
        deploymenttype = data['configType']
        configStatusjson.close()
        return deploymenttype
    else:
        return ""

# Data to be written
def main():
    initialize_logger()

    #if db is ssl enabled, if yes where is the certificate
    is_secure_db = 0
    is_scale = 0
    cis_config_path = CIS_CONF_PATH
    if (deploymenttype() == ""):
        exit (201)
    elif (deploymenttype() == "scale"):
        cis_config_path = CIS_CONF_PATH_FOR_SCALE
        is_scale = 1

    if os.path.exists(cis_config_path) == False:
        exit (201)

    if read_config(cis_config_path, SECURE_DB_CONNECTION_SEARCH_STRING) == "yes":
        is_secure_db = 1

    secure_db_cert_path = read_config(cis_config_path, DB_CLIENT_CERT_PATH_SEARCH_STRING) + "client-cert.pem"
    if ((is_secure_db == 1 or is_scale == 1) and os.path.isfile(secure_db_cert_path)):
        cisagentcerts = {
            "servicename": "CIS-MariaDB",
            "certpath": secure_db_cert_path,
            "certpathtoprocess": secure_db_cert_path
        }

        # Serializing json
        json_object = json.dumps(cisagentcerts, indent=4)

        # Writing to sample.json
        with open(OUT_JSON_PATH, "w") as outfile:
            outfile.write(json_object)

        exit (204)
    else:
        #if ssl not enabled for db or certificate path don't exits
        exit (201)

#Main code starts here
if __name__ == '__main__':
    main()
