#!/usr/bin/env python3

import sys
import xmlrpc.client
import ssl
import subprocess
import time
import os
import psutil
import threading 
import signal

DEBUG=False

class EpoptesClientManager:

	def __init__(self,timeout=None):
		
		self.epoptes_client_pid=None
		self.root_epoptes_pid=None
		self.current_certificate_timestamp=None
		self.unconfigured_timeout=15
		self.configured_timeout=60*3
		if timeout != None:
			self.unconfigured_timeout = timeout
			self.configured_timeout = timeout
			
		self.main_pid=os.getpid()
		
		context=ssl._create_unverified_context()
		self.n4d=xmlrpc.client.ServerProxy("https://localhost:9779",allow_none=True,context=context)
		
		self.dprint("Staring loop...")
		self.thread=threading.Thread(target=self.run_forever)
		self.thread.daemon=True
		self.thread.start()
		
		signal.signal(signal.SIGINT,self.exit_signal)
		
		while True:
			
			if not self.thread.is_alive():
				self.dprint("Restarting thread...")
				self.thread=threading.Thread(target=self.run_forever)
				self.thread.daemon=True
				self.thread.start()
				
			time.sleep(2)
		
	#def init
	
	def dprint(self,data):
		
		if DEBUG:
			print("[EpoptesDesktopClient] %s"%str(data))
		
	#def dprint
	
	def get_root_epoptes_pid(self):
		
		try:
			for p in psutil.process_iter():
				if "epoptes-client" in p.name() and "root" == p.username():
					return p.pid
		except:
			pass 
			
		return None
	
	def start_epoptes_client(self):
		
		if self.epoptes_client_pid == None:
			self.dprint("Starting epoptes-client...")
			p=subprocess.Popen(["epoptes-client"])
			self.epoptes_client_pid=p.pid
			self.dprint("epoptes-client pid: %s"%p.pid)
			return True
	
		self.dprint("epoptes-client instance already running. Skipping start_epoptes_client...")
	
		return False
		
	#def execute_epoptes_client
	
	def stop_epoptes_client(self):
		
		if self.epoptes_client_pid != None:
			process=psutil.Process(self.epoptes_client_pid)
			self.dprint("Killing epoptes-client child processes...")
			for child in process.children(recursive=True):
				try:
					child.terminate()
				except Exception as e:
					self.dprint(e)
					os.system("kill -9 %s"%child.pid)

			try:
				self.dprint("Killing epoptes-client [%s]"%self.epoptes_client_pid)
				process.terminate()
			except Exception as e:
				self.dprint(e)
				os.system("kill -9 %s"%self.epoptes_client_pid)
				
			self.epoptes_client_pid=None
			
			process=psutil.Process(self.main_pid)
			for child in process.children(recursive=True):
				try:
					child.terminate()
				except Exception as e:
					self.dprint(e)
					os.system("kill -9 %s"%child.pid)	
					
			return True
		
		# Should we make sure epoptes_client_pid is None ? 
		self.epoptes_client_pid = None
		self.dprint("epoptes-client pid not registered. Skipping stop_epoptes_client...")
		return False
		
	#def stop_epoptes_client
	
	def restart_epoptes_client(self):
		
		self.dprint("Restarting epoptes-client...")
		self.stop_epoptes_client()
		return self.start_epoptes_client()
		
	#def restart_epoptes_client
	
	def get_current_certificate_timestamp(self):
		
		cert_timestamp=None
		
		try:
			ret=self.n4d.get_certificate_timestamp("","EpoptesDesktopClient")
			if ret["status"]==0:
				cert_timestamp=ret["return"]
			else:
				self.dprint(ret)
		except Exception as e:
			self.dprint(e)
			
		return cert_timestamp
			
		
	#def get_current_certificate_timestamp
	
	def check_zombie(self):
		
		try:
			if self.epoptes_client_pid!=None:
				proc=psutil.Process(self.epoptes_client_pid)
				if proc.status() == psutil.STATUS_ZOMBIE:
					self.dprint("epoptes-client seems to be in zombie status.")
					return True
			
			return False
		except:
			return False
			
	#def check_zombie
	
	def run_forever(self):
		
		while True:
			
			root_epoptes_pid=self.get_root_epoptes_pid()
			self.dprint("Current root epoptes-client pid: %s"%root_epoptes_pid)
			
			timeout=self.unconfigured_timeout
			timestamp=self.get_current_certificate_timestamp()
			self.dprint("Server certificate configuration timestamp: %s"%timestamp)
			
			# This should be covered by following if
			# self.start_epoptes_client()
			
			if timestamp!=None:
				
				restart_ok = True
				
				# whether its the first time or a different timestamp
				# we need to register new timestamp and restart 
				# user-level epoptes-client
				if timestamp!=self.current_certificate_timestamp:
					self.dprint("Registering new certificate timestamp")
					self.current_certificate_timestamp=timestamp
					restart_ok = self.restart_epoptes_client()

				if restart_ok:
					timeout=self.configured_timeout
					
				if self.epoptes_client_pid == None and root_epoptes_pid != None:
					self.start_epoptes_client()
			
			if self.check_zombie():
				# Something seems to be wrong. 
				# Lets restart user-level epoptes-client
				self.stop_epoptes_client()
				break
			
			root_epoptes_pid=self.get_root_epoptes_pid()
			self.dprint("Current root epoptes-client pid: %s"%root_epoptes_pid)
			
			if root_epoptes_pid == None:
				self.dprint("Somehow root epoptes-client is dead. Killing epoptes until it revives...")
				self.stop_epoptes_client()
				# I dont see a better way to sleep before breaking thread
				time.sleep(self.unconfigured_timeout)
				break
				
			else:
				if self.root_epoptes_pid==None:
					self.dprint("First time registering root epoptes-client.")
					self.root_epoptes_pid=root_epoptes_pid
					if self.epoptes_client_pid == None:
						# if by some chance we dont have epoptes-client running, exit thread
						# and start it from a fresh started loop
						self.stop_epoptes_client()
						break

				else:
					if root_epoptes_pid != self.root_epoptes_pid:
						self.dprint("Current root epoptes-client pid is different from registered root epoptes-client pid. %s != %s "%(root_epoptes_pid,self.root_epoptes_pid))
						self.root_epoptes_pid=root_epoptes_pid
						self.stop_epoptes_client()
						break
			
			self.dprint("Sleeping %s ..."%timeout)
			time.sleep(timeout)
		
	#def run_forever
	
	def exit_signal(self,signum, frame):
		
		self.dprint("SIGINT captured")
		self.stop_epoptes_client()
		sys.exit(0)
		
		
	#def exit_signal
	
#class EpoptesClientManager

if __name__=="__main__":
	
	timeout = None
	
	if len(sys.argv)>1:
		count = 1
		for arg in sys.argv[1:]:
			if arg == "-d":
				DEBUG = True
			if arg == "-t":
				try:
					timeout=int(sys.argv[count+1])
				except:
					print("Parsing args error: -t must be followed by an integer")
					sys.exit(1)
			count+=1
			
	ecm=EpoptesClientManager(timeout)
	