#!/usr/bin/env python3

from pydbus import SystemBus
import os
import sys

def runAcc():
	try:
		path = sys.argv[1]
		bus = SystemBus()

		manager = bus.get("ru.basealt.alterator", "/ru/basealt/alterator")["ru.basealt.alterator.manager"]
		obj = bus.get("ru.basealt.alterator", path)["ru.basealt.alterator.legacy1"]

		manager.SetEnvValue("DISPLAY", os.getenv("DISPLAY"))
		manager.SetEnvValue("XAUTHORITY", os.getenv("XAUTHORITY"))
		res = obj.Run()
		if res[-1] == 0:
			print(f"alterator-object-run: application run successfully: {res[:-1]}")
			exit(0)
		else:
			print(f"alterator-object-run: application error: {res[:-1]}", file=sys.stderr)
			exit(1)
	except Exception as e:
		print(f"alterator-object-run: unexpected error: {e}", file=sys.stderr)
		sys.exit(1)

if __name__ == "__main__":
	if len(sys.argv) <= 1:
		sys.exit("alterator-object-run: <dbus_object_path>")

	pid = -1

	try:
		pidFilePath = "/tmp/alterator/alterator-browser-x11-0.pid"
		if not os.path.isfile(pidFilePath):
			runAcc()
			exit(0)
		with open(pidFilePath, "r") as pidFile:
			potentialPid = int(pidFile.readline())
		procPath = "/proc/{0}/cmdline".format(potentialPid)
		if os.path.isfile(procPath):
			with open(procPath, "r") as cmdLineFile:
				if "alterator-browser-" in cmdLineFile.readline():
					pid = potentialPid
	except ValueError as _:
		print("alterator-bject-run: value in '/tmp/alterator/alterator-browser-x11-0.pid' must be a number", file=sys.stderr)
		sys.exit(1)
	except IOError as e:
		print(f"alterator-object-run: {e}", file=sys.stderr)
		sys.exit(1)
	except Exception as e:
		print(f"alterator-bject-run: unexpected error: {e}", file=sys.stderr)
		sys.exit(1)	

	if pid > 0 and os.system("zenity --question --text=\"The running instance of ACC will be terminated. Do you want to procede?\"") == 0:
		os.system("pkexec kill {0}".format(pid))

	runAcc()
