#!/usr/bin/env python3

from pydbus import SystemBus
import os
import sys


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

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

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


if __name__ == "__main__":
    if len(sys.argv) <= 1:
        sys.exit("alterator-application-legacy: <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-application-legacy: {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)

    procede = os.system("/usr/lib/alterator-application-legacy/alterator-application-legacy_dialog") if pid > 0 else 0

    if pid > 0 and procede == 0:
        os.system("pkexec kill {0}".format(pid))

    runAcc()
