#!/usr/bin/env python3.11


# (c) Copyright 2021 Micro Focus or one of its affiliates
#
# The only warranties for products and services of Micro Focus and its affiliates and licensors
# (Micro Focus) 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. Micro Focus shall not be liable for technical or editorial errors or omissions contained
# herein. The information contained herein is subject to change without notice.


import os
import json
import sys
import subprocess
from collections import OrderedDict
from time import strptime, mktime

def printJSON(dictionary):
	jsonData = json.dumps(dictionary, indent = 4)
	print(jsonData)

def datetimeConverter(datetime_string):
        target_timestamp = strptime(datetime_string, '%a %Y-%m-%d %H:%M:%S %Z')
        mktime_epoch = mktime(target_timestamp)
        return(int(mktime_epoch)) # convert to integer to remove decimal

def isServiceActive(serviceName):
        cmd = "systemctl is-active " + serviceName
        process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
        process.wait()
        return process.returncode

def isServiceConfigured(serviceName):
        cmd = "systemctl show -p UnitFileState " + serviceName
        stream = os.popen(cmd)
        output = stream.read().strip().split("=")
        if(str(output[1]).strip() == ""):
                return 1
        else:
                return 0

def genHealth(serviceName, displayName):
        data = OrderedDict()
        data["serviceName"] = displayName
        data["status"] = ""
        data["runningSince"] = ""
        data["AdditionalInfo"] = ""

        # systemctl is-active will return with 0 if service is active so condition becomes false here

        if(isServiceActive(serviceName)):
                data["status"] = "UnHealthy"
                data["runningSince"] = 0
                data["AdditionalInfo"] = [serviceName, "Common_Inactive", "Common_ResolveDaemon"]
        else:
                cmd = "systemctl show -p ActiveEnterTimestamp " + serviceName
                stream = os.popen(cmd)
                output = stream.read()
                run = output.strip().split("=")
                data["status"] = "Healthy"
                data["runningSince"] = datetimeConverter(run[1])
        return data

serviceName = "novell-httpstkd.service"
displayName = "OES Remote Manager (NRM)"
if(isServiceConfigured(serviceName)):
        exit(0)
else: 
        healthData = genHealth(serviceName, displayName)
        printJSON(healthData)
