#!/usr/bin/python3.11
# ------------------------------------------------------------------------------
# Copyright 2023 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 os
import sys
import argparse
import logging
from pathlib import Path
import shutil
import configparser
import oes_cert_mgmt_utils


#Arguments
#1 - operation with below valid values
#CERTCHANGE = 1
#RECONFIG = 2
#MOVETOEDIR = 4
#EDIRCERTCHANGE = 3
#2 - certificate
#3 - cacertificate
#4 - privatekey
#5 - restart
# For operations 3 and 4, no arguments required
# operation 3 - Service should reconfigure to use eDirectory Server certificate either servercert.pem Or serverECCert.pem
# operation 4 - Indication that eDirectory server certificate has changed. Service should take required measures
# operation 1 and 2 - Reconfigure with new certificate, privatekey and cacertificate

#Sample usage
#1. oes-cert-mgmt-telemetry-server-reconfig --operation 3 (Change in eDirectory server certificate)
#3. oes-cert-mgmt-telemetry-server-reconfig --operation 1 --certificate /tmp/newcert.pem --cacertificate /tmp/newncacert.pem --privatekey /tmp/newcertprivatekey.pem


#def setupcliargs():
args = []
EDIRECCERT = "/etc/ssl/servercerts/servercert.pem"
CERTCHANGE = 1
RECONFIG = 2
MOVETOEDIR = 4
EDIRCERTCHANGE = 3
certificate = ""
cacertificate = ""
privatekey = ""
SSLKEY_FILE_PATH= "/etc/ssl/servercerts/serverkey.pem"
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 parsecli():
    global args
    parser = argparse.ArgumentParser()
    parser.add_argument('--operation', type=int)
    parser.add_argument('--certificate', type=str)
    parser.add_argument('--cacertificate', type=str)
    parser.add_argument('--privatekey', type=str)
    parser.add_argument('--restart', type=str)
    args = parser.parse_args()

def validatecliargs():
    #Operation is mandatory
    if args.operation:
        operation = args.operation
        if (operation != CERTCHANGE  and operation != RECONFIG and operation != EDIRCERTCHANGE and operation != MOVETOEDIR):
            logger.info("telemetry-server: Invalid Operation passed")
            exit(200)
    else:
        logger.info("telemetry-server: Operation argument is missing")
        exit(200)

    #For reconfiguration, new certificate should be passed
    if args.certificate:
        certificate = args.certificate
    if args.cacertificate:
        cacertificate = args.cacertificate
    if args.privatekey:
        privatekey = args.privatekey

    if (args.operation == CERTCHANGE or args.operation == RECONFIG):
        if len(sys.argv) < 4:
            logger.info("One or more arguments are missing for reconfiguration")
            exit(200)

        if (len(args.certificate) == 0  or len(cacertificate) == 0 or len(privatekey) == 0):
            logger.info("One or more certificate details of new certificate are missing")
            exit(200)

def handleedircertchange():
    logger.info("telemetry-server: Handling change in eDirectory server certificate")

    if (certificatePath == EDIRECCERT):
        logger.info("telemetry-server: the service is using EDIRECCERT")

def restarttelemetryserverservices():
    try:
        logger.info("telemetry-server: Restarting telemetry-server service")
        os.popen("systemctl restart oes-telemetry.service")
        logger.debug("telemetry-server: telemetry-server restarted successfully...")
    except :
        logger.error("telemetry-server: failed to start telemetry-server")

def main():
    initialize_logger()
    logger.info("telemetry-server: reconfig for telemetry-server")

    #Only root can execute
    if(os.geteuid() != 0):
        logger.info("telemetry-server: Only root can reconfigure the services")
        exit(200)

    #Parse and validate CLI args
    parsecli()
    validatecliargs()
    global certificatePath
    certificatePath = EDIRECCERT

    if (args.operation == CERTCHANGE or args.operation == RECONFIG):
        logger.error("telemetry-server: This operation is not valid for telemetry-server")
        exit(205)
    elif (args.operation == MOVETOEDIR):
        logger.error("telemetry-server: MOVETOEDIR is not valid for telemetry-server")
        exit(205)
    elif(args.operation == EDIRCERTCHANGE):
        handleedircertchange()
    else:
        logger.error("telemetry-server: entered invalid operation")
        exit(200)
    if(args.restart):
        if (args.restart).lower():
            if(args.restart == "yes"):
               restarttelemetryserverservices()
            else:
              exit(0)

    exit(0)

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