#!/usr/bin/env python3

import os
import time
import subprocess
import syslog

THINCLIENT_CRON="/etc/cron.d/lliurex-shutdowner-thinclients"

#in minutes
SERVER_WAIT_TIME=2
CLIENT_WAIT_TIME=1

DEBUG=True

class Shutdowner:
	
	def __init__(self):
		
		self.init_var()
		self.flavours=[]
		self.adi_server="/usr/bin/natfree-adi"
		self.current_flavour=self.what_am_i()
		self.shutdown(self.current_flavour)
		
	#def __init__
	
	def dprint(self,msg):
		
		msg="[lliurex-shutdowner] %s"%msg
		
		if DEBUG:
			print(msg)
			syslog.syslog(msg)
		
	#def dprint

	def init_var(self):
		
		self.lliurex_flavour={
			"server":False,
			"client":False,
			"thin":False,
			"semi":False,
			"desktop":False
		}
		
		self.shutdown_function={
			"server":self.server_shutdown,
			"thin":self.thin_shutdown,
			"semi":self.semi_shutdown,
			"client":self.client_shutdown,
			"desktop":self.standalone_shutdown,
			"unknown":self.basic_shutdown
		}
		
	#def init_var
	
	def what_am_i(self):

		self.get_flavours()

		flavours=["server","client","thin","semi","deskop"]

		for flavour in flavours:
			if subprocess.run(["lliurex-version", "-x", flavour],capture_output=True).returncode==0:
				self.lliurex_flavour[flavour]=True

		if not any(self.lliurex_flavour.values()):
			fallBackFlavour=self.check_flavour()
			if fallBackFlavour in ["server","client","desktop"]:
				self.lliurex_flavour[fallBackFlavour]=True

		priorityOrder=["thin","server","semi","client","desktop"]
		for flavour in priorityOrder:
			if self.lliurex_flavour.get(flavour):
				return flavour
			
		return "unknown"
		
	#def what_am_i
		
	def shutdown(self,flavour):
		
		return self.shutdown_function[flavour]()
		
	#def shutdown
	
	def server_shutdown(self):
		
		self.dprint("Server shutdown")
		
		# server always handles shutdown dialogs for thin clients
		self.dprint("Handling thin client dialogs...")
		thinclients=subprocess.Popen(["ps aux| grep LTSP_CLIENT | grep DISPLAY"],shell=True,stdout=subprocess.PIPE).communicate()[0]
		thinclients=thinclients.decode("utf-8")
		thinclients=thinclients.strip("\n").split("\n")
				
		for tc in thinclients:
			if "DISPLAY=" in tc:
				tmp=tc.split(" ")
				user=tmp[0]
				for item in tmp:
					if "DISPLAY=" in item:
						display=item.split("=")[1]
						command=["su","-c",f"DISPLAY={display} /usr/sbin/shutdown-lliurex-dialog.py {CLIENT_WAIT_TIME}",user]
						self.dprint(" ".join(command))
						subprocess.Popen(command)
		
		# if THINCLIENT_CRON file does not exist. server shutsdow itself as well
		if not os.path.exists(THINCLIENT_CRON):			
			self.dprint("Calling standalone_shutdown...")
			self.standalone_shutdown(SERVER_WAIT_TIME)
	
	#def server_shutdown
	
	def thin_shutdown(self):
		
		self.dprint("Thin shutdown")
		
		# Making sure we don't shutdown server by mistake. Tbin clients are also detected as servers
		if not os.path.exists(THINCLIENT_CRON):
			
			# if we are a thin client AND THINCLIENT_CRON file does NOT exist, 
			# this is executed inside client itself
			
			time.sleep(60*CLIENT_WAIT_TIME)
			command=["n4d-client", "-r", "-m", "shutdown", "-c", "ShutdownerClient"]
			subproces.run(command)

	#def  thin_shutdown
	
	def semi_shutdown(self):
		
		self.dprint("Semi shutdown")
		self.dprint("Calling standalone_shutdown...")
		self.standalone_shutdown(CLIENT_WAIT_TIME)
		
	#def semi_shutdown
	
	def client_shutdown(self):
		
		self.dprint("Client shutdown")
		self.dprint("Calling standalone_shutdown...")
		self.standalone_shutdown(CLIENT_WAIT_TIME)
		
	#def client_shutdown
	
	def unknown_shutdown(self):
		
		self.dprint("Unknown shutdown")
		self.dprint("Calling basic_shutdown...")
		self.basic_shutdown()
		
	#def unknown_shutdown
	
	def standalone_shutdown(self,wait_time=CLIENT_WAIT_TIME):
		
		self.dprint("Standalone shutdown")

		if os.path.exists(self.adi_server):
			wait_time=SERVER_WAIT_TIME

		try:
			result = subprocess.run(
				["loginctl", "list-sessions", "--no-legend"],
				stdout=subprocess.PIPE,
				stderr=subprocess.PIPE,
				text=True
			)	
			sessions = result.stdout
		except Exception as e:
			self.dprint(f"Error running loginctl: {e}")
			sessions = []

		for line in sessions.strip().splitlines():
			parts=line.split()
			if not parts:
				continue
				
			session_id = parts[0]
			user = parts[2]
			
			try:
				info = subprocess.run(
						["loginctl", "show-session", session_id, "-p", "Display"],
						stdout=subprocess.PIPE, text=True, check=True
					)
				sessionInfo=info.stdout.strip()
			except subprocess.SubprocessError:
				continue

			if not sessionInfo.startswith("Display=") or "=" not in sessionInfo:
				continue

			display=sessionInfo.split("=",1)[1]
			cmd=["su","-c",f"DISPLAY={display} /usr/sbin/shutdown-lliurex-dialog.py {wait_time}",user]

			self.dprint(f"\t{' '.join(cmd)}")
			subprocess.Popen(cmd)
			
		self.dprint("Calling basic_shutdown...")
		self.basic_shutdown(wait_time)
		
	#def standalone_shutdown
	
	def basic_shutdown(self,wait_time=CLIENT_WAIT_TIME):
		
		self.dprint("Basic shutdown")
		command=["/sbin/shutdown", "-h", f"+{wait_time}"]
		self.dprint(f"\t{' '.join(command)}")
		subprocess.Popen(command)
		
	#def basic_shutdown

	def get_flavours(self):

		try:
			result=subprocess.check_output(['lliurex-version', '-v'],text=True)
			self.flavours=[x.strip() for x in result.split(",")]
		except (subprocess.CalledProcessError,FileNotFoundError):
			return		
	
	#def get_flavours
	
	def check_flavour(self):

		for item in self.flavours:
			if 'server' in item:
				return 'server'
			if "client" in item:
				return "client"
			if "desktop" in item:
				return "desktop"

		return "unknown"
		
	#def check_flavour
	
#class Shutdowner

if __name__=="__main__":
	
	sd=Shutdowner()

