#!/usr/bin/env python3

"""What this machine offers to other machines, and switches for it.

Every row reports what is actually true, including "the software for this is not
installed". GNOME's Sharing panel shows switches for services that are absent,
which is how a switch ends up doing nothing at all.

Enabling remote login is a system-wide change and goes through pkexec, which
prompts with the polkit agent this desktop already runs. Remote desktop is a
user service and needs no privilege.

    panama-sharing snapshot
    panama-sharing set-remote-login true|false
    panama-sharing set-remote-desktop true|false
    panama-sharing set-hostname NAME
"""

from __future__ import annotations

import json
import re
import shutil
import subprocess
import sys
from pathlib import Path

HOSTNAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9-]{0,62}$")


class BoundaryError(RuntimeError):
    """A user-visible validation or permission failure."""


def run(command: list[str], timeout: float = 25.0) -> subprocess.CompletedProcess:
    try:
        return subprocess.run(command, capture_output=True, text=True,
                              timeout=timeout, check=False)
    except (OSError, subprocess.TimeoutExpired) as error:
        raise BoundaryError(f"{command[0]} did not answer.") from error


def unit_state(unit: str, user: bool = False) -> dict:
    scope = ["--user"] if user else []
    active = run(["systemctl", *scope, "is-active", unit]).stdout.strip()
    enabled = run(["systemctl", *scope, "is-enabled", unit]).stdout.strip()
    return {
        "installed": enabled not in ("", "not-found"),
        "active": active == "active",
        "enabled": enabled == "enabled",
    }


def ssh_setting(name: str) -> str:
    """What sshd's own configuration says, or "" when it says nothing.

    `sshd -T` would be authoritative but needs root. Reading the files means
    reporting "not configured" rather than guessing a default -- which matters,
    because claiming "keys only" on a machine that actually accepts passwords
    would be a security claim this cannot back up.
    """
    paths = [Path("/etc/ssh/sshd_config")]
    paths.extend(sorted(Path("/etc/ssh/sshd_config.d").glob("*.conf"))
                 if Path("/etc/ssh/sshd_config.d").is_dir() else [])
    pattern = re.compile(rf"^\s*{name}\s+(\S+)", re.IGNORECASE)
    for path in paths:
        try:
            for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
                found = pattern.match(line)
                if found:
                    return found.group(1)
        except OSError:
            continue
    return ""


def remote_desktop() -> dict:
    state = unit_state("gnome-remote-desktop.service", user=True)
    state["available"] = bool(shutil.which("grdctl"))
    state["rdpEnabled"] = False
    state["port"] = ""
    state["hasCredentials"] = False
    state["viewOnly"] = False
    if not state["available"]:
        return state

    status = run(["grdctl", "status"]).stdout
    section = status.split("RDP:", 1)
    if len(section) > 1:
        block = section[1].split("VNC:", 1)[0]
        state["rdpEnabled"] = re.search(r"Status:\s*enabled", block) is not None
        port = re.search(r"Port:\s*(\d+)", block)
        state["port"] = port.group(1) if port else ""
        # grdctl prints "(hidden)" when a credential is stored and nothing when
        # it is not, so this reads presence without ever reading the value.
        state["hasCredentials"] = "(hidden)" in block
        state["viewOnly"] = re.search(r"View-only:\s*yes", block) is not None
    return state


def active_logins() -> list[dict[str, str]]:
    """Who is signed in from another machine right now.

    Read from `who`, which names the user, when they arrived, and where from.
    Only sessions with an origin are reported: a local seat has none, and
    listing the person sitting at the keyboard as a remote login would be
    alarming and wrong.
    """
    result = run(["who"])
    if result.returncode != 0:
        return []

    sessions: list[dict[str, str]] = []
    for line in result.stdout.splitlines():
        match = re.match(r"^(\S+)\s+(\S+)\s+(.+?)\s+\((.+)\)\s*$", line)
        if not match:
            continue
        user, line_name, when, origin = match.groups()
        # X displays appear in the same parenthesised field as a hostname.
        if origin.startswith(":") or origin in ("localhost", ""):
            continue
        sessions.append({
            "user": user,
            "line": line_name,
            "since": when.strip(),
            "from": origin,
        })
    return sessions


def media_sharing() -> dict:
    """Rygel, which serves media to devices on the network over DLNA.

    Reported as a running state rather than just "installed", because installed
    and off is the normal case and is not the same thing as sharing. Turning it
    on publishes media directories to every device on the network, which is why
    the page says so next to the switch.
    """
    if not shutil.which("rygel"):
        return {"installed": False, "active": False, "enabled": False, "package": "rygel"}
    state = unit_state("rygel.service", user=True)
    state["installed"] = True
    state["package"] = "rygel"
    return state


def set_media_sharing(enabled: bool) -> None:
    if not shutil.which("rygel"):
        raise BoundaryError("Rygel is not installed.")
    verb = "enable" if enabled else "disable"
    result = run(["systemctl", "--user", verb, "--now", "rygel.service"])
    if result.returncode != 0:
        detail = (result.stderr or "").strip().splitlines()
        raise BoundaryError(detail[-1] if detail else "Media sharing could not be changed.")


def snapshot() -> dict:
    static_name = run(["hostnamectl", "--static"]).stdout.strip()
    pretty_name = run(["hostnamectl", "--pretty"]).stdout.strip()

    login = unit_state("sshd.service")
    login["port"] = ssh_setting("Port") or "22"
    login["passwordAuthentication"] = ssh_setting("PasswordAuthentication")
    login["rootLogin"] = ssh_setting("PermitRootLogin")
    login["sessions"] = active_logins()

    return {
        "hostname": static_name,
        "prettyHostname": pretty_name,
        "remoteLogin": login,
        "remoteDesktop": remote_desktop(),
        # Reported as absent rather than offered as a switch that would do
        # nothing. Installing software is not this page's job.
        "fileSharing": {"installed": bool(shutil.which("smbd")), "package": "samba"},
        "mediaSharing": media_sharing(),
        "error": "",
    }


def set_remote_login(enabled: bool) -> None:
    if not unit_state("sshd.service")["installed"]:
        raise BoundaryError("OpenSSH server is not installed.")
    action = ["enable", "--now"] if enabled else ["disable", "--now"]
    result = run(["pkexec", "systemctl", *action, "sshd.service"], timeout=120)
    if result.returncode != 0:
        raise BoundaryError(_refusal(result, "Remote login could not be changed."))


def set_remote_desktop(enabled: bool) -> None:
    state = remote_desktop()
    if not state["available"]:
        raise BoundaryError("Remote desktop support is not installed.")
    if enabled and not state["hasCredentials"]:
        raise BoundaryError("Set a remote desktop username and password first.")

    toggle = run(["grdctl", "rdp", "enable" if enabled else "disable"])
    if toggle.returncode != 0:
        raise BoundaryError(_refusal(toggle, "Remote desktop could not be changed."))

    action = ["enable", "--now"] if enabled else ["disable", "--now"]
    result = run(["systemctl", "--user", *action, "gnome-remote-desktop.service"], timeout=60)
    if result.returncode != 0:
        raise BoundaryError(_refusal(result, "The remote desktop service could not be changed."))


def set_rdp_port(port: str) -> None:
    if not port.isdigit() or not (1 <= int(port) <= 65535):
        raise BoundaryError("That is not a port number.")
    result = run(["grdctl", "rdp", "set-port", port])
    if result.returncode != 0:
        raise BoundaryError(_refusal(result, "The port could not be changed."))


def set_rdp_view_only(view_only: bool) -> None:
    result = run(["grdctl", "rdp",
                  "enable-view-only" if view_only else "disable-view-only"])
    if result.returncode != 0:
        raise BoundaryError(_refusal(result, "That could not be changed."))


def clear_rdp_credentials() -> None:
    result = run(["grdctl", "rdp", "clear-credentials"])
    if result.returncode != 0:
        raise BoundaryError(_refusal(result, "The credentials could not be cleared."))


def set_hostname(name: str) -> None:
    if not HOSTNAME.fullmatch(name or ""):
        raise BoundaryError("A name may use letters, digits and hyphens.")
    result = run(["hostnamectl", "set-hostname", name], timeout=60)
    if result.returncode != 0:
        raise BoundaryError(_refusal(result, "The name could not be changed."))


def _refusal(result: subprocess.CompletedProcess, fallback: str) -> str:
    text = (result.stderr or "").strip().splitlines()
    if text and ("not authorized" in text[-1].lower() or "dismissed" in text[-1].lower()):
        return "That change was not authorized."
    return text[-1][:200] if text else fallback


def main(arguments: list[str]) -> int:
    try:
        if arguments == ["snapshot"]:
            print(json.dumps(snapshot(), separators=(",", ":")))
            return 0
        if len(arguments) == 2 and arguments[0] == "set-media-sharing":
            set_media_sharing(arguments[1] == "true")
        elif len(arguments) == 2 and arguments[0] == "set-remote-login":
            set_remote_login(arguments[1] == "true")
        elif len(arguments) == 2 and arguments[0] == "set-remote-desktop":
            set_remote_desktop(arguments[1] == "true")
        elif len(arguments) == 2 and arguments[0] == "set-hostname":
            set_hostname(arguments[1])
        elif len(arguments) == 2 and arguments[0] == "set-rdp-port":
            set_rdp_port(arguments[1])
        elif len(arguments) == 2 and arguments[0] == "set-rdp-view-only":
            set_rdp_view_only(arguments[1] == "true")
        elif arguments == ["clear-rdp-credentials"]:
            clear_rdp_credentials()
        else:
            raise BoundaryError(
                "Usage: panama-sharing snapshot | set-remote-login true|false | "
                "set-remote-desktop true|false | set-hostname NAME | "
                "set-rdp-port PORT | set-rdp-view-only true|false | "
                "clear-rdp-credentials")
    except BoundaryError as error:
        state = snapshot()
        state["error"] = str(error)
        print(json.dumps(state, separators=(",", ":")))
        return 0

    print(json.dumps(snapshot(), separators=(",", ":")))
    return 0


if __name__ == "__main__":
    raise SystemExit(main(sys.argv[1:]))
