#!/usr/bin/env python3
"""LinuxDoors Package Manager -- unprivileged launcher. Always shows a
real masked-password GTK dialog (no silent default-password attempt --
this app deliberately keeps prompting every time), replacing the old
bare `su`-in-a-terminal "Password: " prompt with a clearer one that
says what it's for and which account it's actually checking."""
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
import os
import pty
import select

APP = "/usr/local/bin/linuxdoors-pkg-manager"
WHY_TEXT = "This is LinuxDoors Package Manager. A password is required to start this program."

CSS = b"""
window, .background {
    background-image: linear-gradient(to bottom, #1c1038, #0a0616);
    background-color: #1c1038;
}
label { color: #fbeed2; }
.subtitle { color: #b8a4d8; font-size: 13px; }
/* Password field: a light box with DARK text. Some host GTK themes force
   a white/light entry background that our dark background-color could not
   override, leaving the masked "*" characters cream-on-white and unreadable
   (user-reported). Making the field explicitly light + near-black text
   guarantees contrast no matter what the theme does. `background-image:
   none` also clears any themed gradient the plain background-color would
   otherwise show through. Both the `entry` node and its inner `entry text`
   node are set, since GTK 3.20+ draws the text on the child node. */
entry {
    background-image: none;
    background-color: #f4eeff;
    color: #1c1038;
    caret-color: #1c1038;
    border-radius: 8px;
    border: 1px solid #b7a4dd;
    padding: 6px 10px;
}
entry text {
    color: #1c1038;
    caret-color: #1c1038;
    background-color: transparent;
}
entry text selection { background-color: #e8c98a; color: #1c1038; }
entry image, entry placeholder { color: #6c5a94; }
entry:focus {
    background-image: none;
    background-color: #ffffff;
    border-color: #e8c98a;
}
button {
    border-radius: 8px;
    padding: 8px 16px;
    border: none;
    background-image: none;
}
button.suggested-action {
    background-color: #e8c98a;
    color: #1c1038;
    font-weight: bold;
}
button.suggested-action label { color: #1c1038; }
button label { color: #1c1038; }
button.flat-nav {
    background-color: #241246;
    color: #cdbdec;
    border: 1px solid #3a2570;
}
button.flat-nav label { color: #cdbdec; }
"""


def try_su(password):
    """Runs `su -c APP root` under a real pty, feeding `password` once a
    Password: prompt appears. Blocks until APP itself exits (keeping the
    pty open the whole time -- closing it early would SIGHUP the root-
    owned app). Returns True if the password was accepted."""
    pid, fd = pty.fork()
    if pid == 0:
        _x = os.environ.get("XAUTHORITY") or os.path.expanduser("~/.Xauthority")
        _d = os.environ.get("DISPLAY", ":0")
        # A desktop-icon double-click (pcmanfm-qt --desktop, LXQt) does not
        # carry XAUTHORITY, and `su -c` resets HOME to /root -- so the
        # root GUI cannot reach the X display and crashes silently. Pass
        # DISPLAY + the resolved XAUTHORITY explicitly (root can read the
        # user file).
        os.execvp("su", ["su", "-c",
                         "env DISPLAY=" + _d + " XAUTHORITY=" + _x + " " + APP,
                         "root"])
    sent = False
    auth_failed = False
    while True:
        try:
            r, _, _ = select.select([fd], [], [], 60)
        except OSError:
            break
        if fd not in r:
            continue
        try:
            data = os.read(fd, 4096)
        except OSError:
            break
        if not data:
            break
        low = data.lower()
        if not sent and b"password" in low:
            os.write(fd, (password + "\n").encode())
            sent = True
        elif sent and (b"authentication failure" in low or b"incorrect password" in low):
            auth_failed = True
            break
    os.waitpid(pid, 0)
    return sent and not auth_failed


def ask_password(retry):
    dialog = Gtk.Dialog(title="LinuxDoors Package Manager")
    screen = dialog.get_screen()
    provider = Gtk.CssProvider()
    provider.load_from_data(CSS)
    Gtk.StyleContext.add_provider_for_screen(
        screen, provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
    dialog.set_default_size(360, 170)
    dialog.set_position(Gtk.WindowPosition.CENTER)
    cancel_btn = dialog.add_button("Cancel", Gtk.ResponseType.CANCEL)
    cancel_btn.get_style_context().add_class("flat-nav")
    ok_btn = dialog.add_button("Unlock", Gtk.ResponseType.OK)
    ok_btn.get_style_context().add_class("suggested-action")
    dialog.set_default(ok_btn)

    box = dialog.get_content_area()
    box.set_spacing(10)
    box.set_border_width(18)
    why_label = Gtk.Label(label=WHY_TEXT)
    why_label.set_xalign(0)
    why_label.set_line_wrap(True)
    why_label.get_style_context().add_class("subtitle")
    box.pack_start(why_label, False, False, 0)
    if retry:
        retry_label = Gtk.Label(label="That password wasn't accepted -- try again.")
        retry_label.set_xalign(0)
        box.pack_start(retry_label, False, False, 0)
    entry_label = Gtk.Label(label="Password for root:")
    entry_label.set_xalign(0)
    box.pack_start(entry_label, False, False, 0)
    entry = Gtk.Entry()
    entry.set_visibility(False)
    entry.set_invisible_char("*")
    entry.set_activates_default(True)
    box.pack_start(entry, False, False, 0)
    dialog.show_all()
    response = dialog.run()
    password = entry.get_text()
    dialog.destroy()
    if response != Gtk.ResponseType.OK:
        return None
    return password


def main():
    retry = False
    while True:
        password = ask_password(retry)
        if password is None:
            return
        if try_su(password):
            return
        retry = True


if __name__ == "__main__":
    main()
