#!/usr/bin/env python3

import os
import time
import subprocess
import syslog
import shlex


SERVER_WAIT_TIME=2
CLIENT_WAIT_TIME=1

DEBUG=True

class Shutdowner:
	
	def __init__(self):
		
		self.init_var()
		self.adiServer="/usr/bin/natfree-adi"
		self.version_reference=["adi","desktop"]
		self.current_flavour=self.what_am_i()
		self.shutdown(self.current_flavour)
		
	#def __init__
	
	def dprint(self,msg):
		
		msg=f"[lliurex-shutdowner] {msg}"
		
		if DEBUG:
			print(msg)
			syslog.syslog(msg)
		
	#def dprint

	def init_var(self):

		self.shutdown_function={
			"adi":self.server_shutdown,
			"unknown":self.basic_shutdown
		}
		
	#def init_var
	
	def what_am_i(self):
		
		if os.path.exists(self.adiServer):
			return "adi"

		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")
		
		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")
		waylandCommand = '"wayland;xcb"'
		
		try:
			result = subprocess.run(
				["loginctl", "list-sessions", "--no-legend"],
				stdout=subprocess.PIPE,
				stderr=subprocess.PIPE,
				text=True
			)
			
			sessions = result.stdout.strip().split("\n")
		except Exception as e:
			self.dprint(f"Error running loginctl: {e}")
			sessions = []
			
		for session_line in sessions:
			if not session_line.strip():
				continue
				
			parts = session_line.split()
			if len(parts) < 3:
				continue
				
			session_id = parts[0]
			user = parts[2]
			
			if user in ["root", "lightdm", "gdm", "sddm"]:
				continue
				
			session_type = subprocess.run(
				["loginctl", "show-session", session_id, "-p", "Type", "--value"],
				stdout=subprocess.PIPE, text=True
			).stdout.strip()
			
			display = subprocess.run(
				["loginctl", "show-session", session_id, "-p", "Display", "--value"],
				stdout=subprocess.PIPE, text=True
			).stdout.strip()
			
			if session_type == "wayland":
				env_var=f"QT_QPA_PLATFORM={waylandCommand}"
			else:
				if not display:
					display = ":0"
				env_var=f"DISPLAY={display}"

			inner_command=f"{env_var} /usr/sbin/shutdown-lliurex-dialog.py {wait_time}"
			command = ["su","-c",inner_command,user]

			self.dprint(f"\t{' '.join(command)}")
			subprocess.Popen(command)
			
		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()

