#!/usr/bin/python3
"""Run the selected stock Debian SDDM session after first-login agreement."""
import os
import subprocess
import sys
from pathlib import Path

from agreement_model import has_agreed, is_live_boot
from initial_access import required as needs_password_handoff


def start_session(kind, arguments):
    scripts = {"x11": "/etc/sddm/Xsession", "wayland": "/etc/sddm/wayland-session"}
    if kind not in scripts or not arguments:
        return 2
    if not is_live_boot():
        directory = Path(__file__).parent
        prompts = [] if has_agreed() else ["agreement_ui.py"]
        if needs_password_handoff():
            prompts.append("initial_access.py")
        for name in prompts:
            command = [str(directory / name)]
            environment = os.environ.copy()
            if kind == "wayland":
                environment.pop("DISPLAY", None)
                environment.pop("WAYLAND_DISPLAY", None)
                environment["GDK_BACKEND"] = "wayland"
                command = ["/usr/bin/cage", "--", *command]
            else:
                environment["GDK_BACKEND"] = "x11"
            result = subprocess.run(command, env=environment, check=False)
            if result.returncode not in (0, 1):
                print(f"First-login prompt exited with status {result.returncode}", file=sys.stderr)
                return 2
            if result.returncode != 0 or not has_agreed():
                # SDDM reserves status 1 for a failed password. A deliberate
                # sign-out ends the session normally and restores the greeter.
                return 0
            if name == "initial_access.py" and needs_password_handoff():
                return 0
    script = scripts[kind]
    os.execv(script, [script, *arguments])


if __name__ == "__main__":
    try:
        sys.exit(start_session(sys.argv[1], sys.argv[2:]))
    except (OSError, IndexError) as error:
        print(f"Agreement login: {error}", file=sys.stderr)
        sys.exit(2)
