#!/usr/bin/env python3.11
# ------------------------------------------------------------------------------
# Copyright [2023-2024] 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

CERT_PATH = ""
OUT_JSON_PATH = "/var/opt/novell/oes-cert-mgmt/servicecerts/cis-cloudgateway.json"
CIS_CONF_PATH = "/etc/opt/novell/cis/config"
CIS_CONF_PATH_FOR_SCALE="/etc/opt/novell/cis-scale/config"
CERTS_PATH_SEARCH_STRING = "CERTS_PATH"
CLOUD_CA_BUNDLE_NAME_SEARCH_STRING = "CLOUD_CA_BUNDLE_NAME"



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:
                print ("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 ""

def main():

    cis_config_path = CIS_CONF_PATH
    if (deploymenttype() == ""):
        exit(201)
    elif (deploymenttype() == "scale"):
        cis_config_path = CIS_CONF_PATH_FOR_SCALE

    if ((os.path.exists(cis_config_path) == False) or  (os.path.exists(cis_config_path) and read_config(cis_config_path, CLOUD_CA_BUNDLE_NAME_SEARCH_STRING) == "")):
        exit (201)

    cloud_ca_bundle_path = read_config(cis_config_path, CERTS_PATH_SEARCH_STRING) + "/rootCAs/" + read_config(cis_config_path, CLOUD_CA_BUNDLE_NAME_SEARCH_STRING)

    # Data to be written
    #if os.path.isfile(CERT_PATH):
    if os.path.exists(cloud_ca_bundle_path):
        cisagentcerts = {
            "servicename": "CIS-Cloudgateway",
            "certpath": cloud_ca_bundle_path,
            "certpathtoprocess": cloud_ca_bundle_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:
        exit (201)

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