#!/usr/bin/env python3

import os
import time
import subprocess
import syslog


#in minutes
SERVER_WAIT_TIME=2
CLIENT_WAIT_TIME=1

DEBUG=True

class Shutdowner:
	
	def __init__(self):
		
		self.init_var()
		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
		}
	
		self.shutdown_function={
			"server":self.server_shutdown,
			"unknown":self.unknown_shutdown
		}
		
	#def init_var
	
	def what_am_i(self):
		
		if subprocess.run(["lliurex-version", "-x", "server"],capture_output=True).returncode==0:
			self.lliurex_flavour["server"]=True
			return "server"

		if subprocess.run(["lliurex-version", "-x", "desktop"],capture_output=True).returncode==0:
			if os.path.exists(self.adi_server):
				return "server"
				
		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.standalone_shutdown(SERVER_WAIT_TIME)
		
	#def server_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
	
#class Shutdowner

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

