#!/usr/bin/python3.11

#
# © 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 logging
import syslog
import json
import os
import time
import calendar
import subprocess
from os import path
from datetime import date
from datetime import datetime
from collections import OrderedDict

configFile = '/etc/opt/novell/telemetry/config/telemetry.json'
telemetryOutputDir = "/var/opt/novell/telemetry/data/"
opt_in = False
serviceName = "novell-cifs"
fileExtension = ".json"
novcifsOutputStr = ""
novcifsClOutputStr = ""

def invokenovcifs():
	global novcifsOutputStr
	global novcifsClOutputStr
	retVal,novcifsOutput= subprocess.getstatusoutput('novcifs -o')
	if (retVal == 0):
		novcifsOutputStr = novcifsOutput.splitlines()
	else:
		syslog.syslog("Error in getting novcifs -o output")
		exit(1)
	retVal,novcifsClOutput= subprocess.getstatusoutput('novcifs -Cl')
	if (retVal == 0):
		novcifsClOutputStr = novcifsClOutput.splitlines()
	else:
		syslog.syslog("Error in getting novcifs -Cl output")
		exit(1)

def readConfigFile():
	global opt_in
	try:
		config = open(configFile, 'r')
		lines = config.readlines()
		for line in lines:
			if "opt-in" in line:
				if "yes" in line:
					opt_in = True
		config.close()

	except:
		syslog.syslog("Not able to open config file" + configFile)

def removePreviousFile():
	try:
		for cifsTelemetryFile in os.listdir(telemetryOutputDir):
			if (cifsTelemetryFile.startswith(serviceName)) and (cifsTelemetryFile.endswith(fileExtension)):
				os.remove(os.path.join(telemetryOutputDir, cifsTelemetryFile))
	except:
		syslog.syslog("Not able to clean up previous CIFS telemetry json file or No previous CIFS telemetry json file found")


def checkEnabled(line):
	if "Disabled" in line:
		return False
	else:
		return True

def checkString(searchString):
	global novcifsOutputStr
	retVal = False
	for line in novcifsOutputStr:
		if searchString in line:
			retVal = checkEnabled(line)
	return retVal

def getSMBDialect():
	global novcifsOutputStr
	smbDialect = ""	
	for line in novcifsOutputStr:
		if "Dialect" in line:
			smbDialect = line.split('-')[1].strip().strip("\"").split(" ")[0]
	return smbDialect		

def getIsSMBSigningEnabled():
	isEnabled = checkString("SMB signature")
	return (str(isEnabled))

def getIsLeaseEnabled():
	isEnabled = checkString("Leasing")
	return (str(isEnabled))

def getIsDFSSupport():
	isEnabled = checkString("DFS support")
	return (str(isEnabled))

def getCPLEnabled():
	isEnabled = checkString("Cross Protocol Locking")
	return (str(isEnabled))

def getIsEncryptEnabled():
	isEnabled = checkString("Encrypt data")
	return (str(isEnabled))

def getShareListCount():
	count = 0
	retVal,shareList = subprocess.getstatusoutput("novcifs -sl")
	if (retVal == 0):
		shareListStr = shareList.splitlines()
		for line in shareListStr:
			if( len(line) > 1):
				if "_ADMIN" in line:
					continue
				elif "IPC$" in line:
					continue
				elif "----------------------" in line:
					continue
				elif "List of share points" in line:
					continue
				else:
					count = count + 1
	else:
		syslog.syslog("Error in getting novcifs -sl output")
		exit(1)
	return count

def getConnectionCount():
	countStr = 0
	checkChar = '\n'
	global novcifsClOutputStr
	lookStr = "Total number of active CIFS client connections:"
	for line in novcifsClOutputStr:
		if lookStr in line:
			countStr = line.partition(lookStr)[2]
			if checkChar in countStr:
				return countStr.rstrip(checkChar)
			else:
				return countStr
	return countStr

def geteDirUserCount():
	eDirUserCount = 0
	global novcifsClOutputStr
	for line in novcifsClOutputStr:
		if "eDirectory" in line:
			eDirUserCount = eDirUserCount + 1
	return eDirUserCount


def getAdUserCount():
	adUserCount = 0
	global novcifsClOutputStr
	for line in novcifsClOutputStr:
		if "Active Directory" in line:
			adUserCount = adUserCount + 1
	return adUserCount

def createJsonObject():
	epochTime = round(time.time())
	jsonFile = serviceName +"_" + str(epochTime) + fileExtension
	telematryOutputFile = telemetryOutputDir + jsonFile
	cifsJsonOutput = OrderedDict([
			("OESService", serviceName),
			("timestamp", epochTime),
			("Encrypt data", getIsEncryptEnabled()),
			("Cross Protocol Locking", getCPLEnabled()),
			("DFS support", getIsDFSSupport()),
			("Leasing", getIsLeaseEnabled()),
			("SMB signature", getIsSMBSigningEnabled()),
			("Connection count", str(getConnectionCount())),
			("edirectory connection", str(geteDirUserCount())),
			("AD connection", str(getAdUserCount())),
			("share count", str(getShareListCount())),
			("Dialect", str(getSMBDialect())),
			])
		
	retVal = path.exists(telemetryOutputDir)
	if not retVal:
		syslog.syslog("Directory %s does not exists for storing Telemetry Json file" % telemetryOutputDir)
		exit(1)
	try:

		outputFileHandler = open(telematryOutputFile, "w")
		json.dump(cifsJsonOutput, outputFileHandler,indent=0)
		outputFileHandler.close()
	except:
		syslog.syslog("Not able to create Json File for telemetry service")

currentDateTime = datetime.now()
strDateTime = currentDateTime.strftime("%d-%m-%YT%H:%M:%S")
syslog.syslog("Telemetry for novell-cifs is started at " + str(strDateTime))

readConfigFile()
if opt_in is True:
	removePreviousFile()
	invokenovcifs()
	createJsonObject()

