#!/usr/bin/env python3
"""AdPlayr Raspberry Pi player 0.2.3. Run as the desktop user, without sudo."""
import threading
import socket
import ipaddress
import contextlib
import datetime
import hashlib
import json
import os
from pathlib import Path
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
import time
import urllib.request
import uuid

MARKER = "# AdPlayr player startup"
URL = "https://adplayr.com/player"
VERSION = "0.2.3"
FEED = "https://adplayr.com/updates/pi/"
PUBLIC_KEY = """-----BEGIN PUBLIC KEY-----
MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEAqntPIGgCUXZHpphXF77f
hEJ/TQ9VimDzxmZolV/6uvQF1SXjJJHbcRzkKWSS/Bw3qwN+fJwSgoE25sp16z4q
2pJH6zDj5U1JNUEG0RFDUCI31QKo0m/PPfijLdV7ZLR7dC47XM+qBw9Q01e1Y+v0
YTEZ4VtJkQJTT3QfmmrfYhjzCw7su8HQbRpSNkxXwAHcYOSekAHQAB3MzNnDt/CM
tfMevJ7o5vy/2K2hWhoinOyTNJc/BjzPXYgjb9J3IDqSQ4i2YI7DmLqToFIHHAim
1hfT92ZgnnncXf1govn0WQVJaBR841PML+Z9gvCESqDOoVmKh0E+12hpe+BokkGm
pLG8MWrv+cyh5LvSW8PwAMlup108Oztah5GW991vt19BsuA4vMrCMhsyF96/e5dk
XHTXCCwZwyDh2+Sm5+teyTkEt7XjrgNdicDR3FuT4StiggyEbbS6osmoNsz/5K/P
AfvS4S7r3TkeqhV5TJn6ap3ByzZl5ObaQR7ririIvOatAgMBAAE=
-----END PUBLIC KEY-----"""


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        raise RuntimeError("Unexpected update redirect")


def download(name, limit, deadline):
    remaining = deadline - time.monotonic()
    if remaining <= 0:
        raise TimeoutError("Update check timed out")
    request = urllib.request.Request(FEED + name, headers={"Cache-Control": "no-cache"})
    with urllib.request.build_opener(NoRedirect).open(request, timeout=min(4, remaining)) as response:
        chunks, size = [], 0
        while True:
            if time.monotonic() >= deadline:
                raise TimeoutError("Update check timed out")
            chunk = response.read1(min(8192, limit + 1 - size))
            if not chunk:
                return b"".join(chunks)
            size += len(chunk)
            if size > limit:
                raise RuntimeError("Update exceeds size limit")
            chunks.append(chunk)


def verify_policy(content, signature):
    # OpenSSL is supplied by Raspberry Pi OS. Missing/broken verification skips the update.
    executable = shutil.which("openssl")
    if not executable:
        raise RuntimeError("OpenSSL is needed to verify updates")
    with tempfile.TemporaryDirectory(prefix="adplayr-signature-") as folder:
        directory = Path(folder)
        (directory / "key.pem").write_text(PUBLIC_KEY, encoding="ascii")
        (directory / "policy.json").write_bytes(content)
        (directory / "signature").write_bytes(signature)
        result = subprocess.run([executable, "dgst", "-sha256", "-verify", str(directory / "key.pem"),
                                 "-signature", str(directory / "signature"), str(directory / "policy.json")],
                                capture_output=True, timeout=3, check=False)
        if result.returncode:
            raise RuntimeError("Invalid update signature")
    return json.loads(content)


def policy(deadline):
    return verify_policy(download("policy.json", 16384, deadline), download("policy.sig", 4096, deadline))


def eligible(release, identity, now=None):
    try:
        version = release["version"]
        if not isinstance(version, str) or not re.fullmatch(r"\d{1,5}\.\d{1,5}\.\d{1,5}", version):
            return False
        if tuple(map(int, version.split("."))) <= tuple(map(int, VERSION.split("."))):
            return False
        expiry = datetime.datetime.fromisoformat(release["expiresUtc"].replace("Z", "+00:00"))
        now = now or datetime.datetime.now(datetime.timezone.utc)
        cohort = int.from_bytes(hashlib.sha256(identity.encode()).digest()[:2], "big") % 100
        percent = release["rolloutPercent"]
        return (release["enabled"] is True and release["product"] == "AdPlayr-Pi"
                and type(percent) is int and 0 < percent <= 100 and cohort < percent
                and expiry > now and isinstance(release["sha256"], str)
                and re.fullmatch(r"[a-f0-9]{64}", release["sha256"]) is not None)
    except (KeyError, ValueError, TypeError, AttributeError):
        return False


def atomic_write(path, data):
    descriptor, temporary = tempfile.mkstemp(prefix=".adplayr-", dir=path.parent)
    try:
        with os.fdopen(descriptor, "wb") as output:
            output.write(data)
            output.flush()
            os.fsync(output.fileno())
        os.replace(temporary, path)
    finally:
        Path(temporary).unlink(missing_ok=True)


@contextlib.contextmanager
def update_lock(root):
    import fcntl
    with (root / "update.lock").open("a") as lock:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            yield False
            return
        try:
            yield True
        finally:
            fcntl.flock(lock, fcntl.LOCK_UN)


@contextlib.contextmanager
def player_lock(root):
    # One Chromium profile must be owned by one player process. This also
    # prevents a second menu click from creating a competing restart loop.
    import fcntl
    with (root / "player.lock").open("a") as lock:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            yield False
            return
        try:
            yield True
        finally:
            fcntl.flock(lock, fcntl.LOCK_UN)


def apply_startup_update(root):
    installed = root / "player.py"
    if Path(__file__).resolve() != installed.resolve():
        return
    deadline = time.monotonic() + 20
    identity_path = root / "update-install-id"
    if not identity_path.exists():
        atomic_write(identity_path, uuid.uuid4().hex.encode())
    identity = identity_path.read_text().strip()
    release = policy(deadline)
    if not eligible(release, identity):
        return
    candidate = download("player-" + release["version"] + ".py", 262144, deadline)
    if hashlib.sha256(candidate).hexdigest() != release["sha256"]:
        raise RuntimeError("Update package hash mismatch")
    compile(candidate, "player.py", "exec")
    # Probe the signed candidate before replacing the installed file; no browser is opened.
    with tempfile.TemporaryDirectory(prefix=".adplayr-probe-", dir=root) as temporary:
        probe = Path(temporary) / "player.py"
        probe.write_bytes(candidate)
        result = subprocess.run([sys.executable, str(probe), "--update-self-test"], capture_output=True, timeout=3)
        if result.returncode or result.stdout.decode().strip() != release["version"]:
            raise RuntimeError("Update startup check failed")
    latest = policy(deadline)
    if not eligible(latest, identity) or latest["version"] != release["version"] or latest["sha256"] != release["sha256"]:
        return
    if time.monotonic() >= deadline:
        return
    previous = installed.read_bytes()
    atomic_write(root / "player.previous.py", previous)
    atomic_write(installed, candidate)
    try:
        os.execv(sys.executable, [sys.executable, str(installed), "start", "--skip-update"])
    except OSError:
        atomic_write(installed, previous)
        raise


def check_startup_update(root):
    try:
        with update_lock(root) as acquired:
            if acquired:
                apply_startup_update(root)
    except Exception as error:
        # Verification/network/storage failures must not prevent the existing player opening.
        print("AdPlayr update skipped: " + type(error).__name__, file=sys.stderr)


def startup_text(existing, command=None):
    result = []
    skip = False
    for line in existing.splitlines():
        if skip:
            skip = False
            continue
        if line == MARKER:
            skip = True
            continue
        result.append(line)
    if command:
        result.extend([MARKER, command])
    return "\n".join(result) + "\n"


def locations():
    home = Path.home()
    return (home / ".local/share/adplayr-pi", home / ".config/labwc/autostart",
            home / ".local/share/applications/adplayr-pi.desktop")


def browser():
    executable = shutil.which("chromium") or shutil.which("chromium-browser")
    if not executable:
        raise RuntimeError("Install Chromium using Raspberry Pi OS Add/Remove Software, then retry.")
    return executable


def desktop_quote(value):
    value = str(value)
    for char in ('\\', '"', '`', '$'):
        value = value.replace(char, '\\' + char)
    return '"' + value.replace('%', '%%') + '"'


def install():
    browser()
    if not (shutil.which("labwc") or shutil.which("labwc-pi")):
        raise RuntimeError("This setup requires Raspberry Pi OS Desktop with labwc.")
    root, autostart, desktop = locations()
    root.mkdir(parents=True, exist_ok=True, mode=0o700)
    installed = root / "player.py"
    if Path(__file__).resolve() != installed.resolve():
        atomic_write(installed, Path(__file__).read_bytes())
    autostart.parent.mkdir(parents=True, exist_ok=True)
    if autostart.exists():
        existing = autostart.read_text()
        backup = autostart.with_name("autostart.before-adplayr")
        if not backup.exists():
            shutil.copyfile(autostart, backup)
    else:
        system = Path("/etc/xdg/labwc/autostart")
        existing = system.read_text() if system.exists() else ""
    command = shlex.join([sys.executable, str(installed), "start"]) + " &"
    autostart.write_text(startup_text(existing, command))
    desktop.parent.mkdir(parents=True, exist_ok=True)
    desktop.write_text("[Desktop Entry]\nType=Application\nName=AdPlayr Player\n"
                       "Comment=Open your advert screen\nTerminal=false\nCategories=AudioVideo;\nExec="
                       + desktop_quote(sys.executable) + " " + desktop_quote(installed) + " start\n")
    print("Installed. Open AdPlayr Player from the applications menu, or sign out and back in.")
    print("Enable Desktop Auto Login and disable Screen Blanking in Raspberry Pi settings.")
    print("Close the player with Alt+F4. Existing signage programs are not changed.")


def network_key(root):
    path = root / "network-key"
    if path.exists():
        value = path.read_text().strip()
        if re.fullmatch(r"[a-f0-9]{64}", value):
            return value
    value = uuid.uuid4().hex + uuid.uuid4().hex
    path.write_text(value)
    path.chmod(0o600)
    return value


def local_network():
    for family, target in [(socket.AF_INET, "8.8.8.8"), (socket.AF_INET6, "2001:4860:4860::8888")]:
        try:
            with socket.socket(family, socket.SOCK_DGRAM) as sock:
                sock.connect((target, 53))
                address = str(ipaddress.ip_address(sock.getsockname()[0].split("%")[0]))
            connection = "other"
            result = subprocess.run(["ip", "-j", "address"], capture_output=True, text=True, timeout=3)
            for interface in json.loads(result.stdout or "[]"):
                if any(a.get("local") == address for a in interface.get("addr_info", [])):
                    name = interface.get("ifname", "")
                    if re.fullmatch(r"[a-zA-Z0-9_.-]+", name):
                        if (Path("/sys/class/net") / name / "wireless").exists():
                            connection = "wifi"
                        elif name.startswith(("eth", "en")):
                            connection = "ethernet"
                    break
            return {"ip": address, "connection": connection}
        except (OSError, ValueError, subprocess.SubprocessError):
            continue
    return {"ip": None, "connection": None}


def report_network(key, stopped):
    while not stopped.is_set():
        try:
            request = urllib.request.Request("https://adplayr.com/api/player/network/report",
                data=json.dumps(local_network()).encode(), method="POST",
                headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"})
            with urllib.request.build_opener(NoRedirect()).open(request, timeout=10) as response:
                response.read(1024)
        except Exception:
            pass  # Diagnostics never interrupt playback.
        stopped.wait(60)


def player_arguments(profile, key):
    return [browser(), "--user-data-dir=" + str(profile), "--kiosk", "--no-first-run",
            "--no-default-browser-check", "--disable-session-crashed-bubble",
            "--autoplay-policy=no-user-gesture-required",
            URL + "?desktop=1&player_platform=raspberry-pi&native_version=" + VERSION + "#network_key=" + key]


def launch_player(profile, key, stopped):
    # A normal Chromium exit (including Alt+F4) stops the player. A non-zero
    # exit is treated as a crash and restarted with a capped delay so a broken
    # browser does not spin the device or flood its logs.
    delay = 2
    while not stopped.is_set():
        status = subprocess.call(player_arguments(profile, key))
        if status == 0 or stopped.is_set():
            return status
        print("AdPlayr browser stopped unexpectedly; retrying in " + str(delay) + " seconds.", file=sys.stderr)
        stopped.wait(delay)
        delay = min(delay * 2, 60)
    return 0


def start(skip_update=False):
    root, _, _ = locations()
    root.mkdir(parents=True, exist_ok=True, mode=0o700)
    if not skip_update:
        check_startup_update(root)
    with player_lock(root) as acquired:
        if not acquired:
            print("AdPlayr Player is already running.")
            return
        profile = root / "browser-profile"
        profile.mkdir(parents=True, exist_ok=True, mode=0o700)
        key = network_key(root)
        stopped = threading.Event()
        threading.Thread(target=report_network, args=(key, stopped), daemon=True).start()
        # Retain Chromium's sandbox, pairing cookies and offline media across restarts.
        try:
            raise SystemExit(launch_player(profile, key, stopped))
        finally:
            stopped.set()


def uninstall():
    _, autostart, desktop = locations()
    if autostart.exists():
        autostart.write_text(startup_text(autostart.read_text()))
    desktop.unlink(missing_ok=True)
    print("Automatic startup and menu shortcut removed. Close the player with Alt+F4.")
    print("Pairing and cached media kept. Disconnect the screen in AdPlayr when retiring it.")


def main():
    if sys.argv[1:] == ["--update-self-test"]:
        # Called only after signature/hash verification, before installing a release.
        if "BEGIN PUBLIC KEY" not in PUBLIC_KEY:
            raise RuntimeError("Missing update key")
        print(VERSION)
        return
    if sys.platform != "linux" or os.geteuid() == 0:
        raise RuntimeError("Run this on the Pi as your normal desktop user, without sudo.")
    if sys.argv[1:] == ["start", "--skip-update"]:
        start(skip_update=True)
        return
    action = sys.argv[1] if len(sys.argv) == 2 else "install" if len(sys.argv) == 1 else ""
    if action not in ("install", "start", "uninstall"):
        raise RuntimeError("Usage: python3 AdPlayr-Pi-Setup.py [install|start|uninstall]")
    {"install": install, "start": start, "uninstall": uninstall}[action]()


if __name__ == "__main__":
    try:
        main()
    except (RuntimeError, OSError) as error:
        print(str(error), file=sys.stderr)
        sys.exit(1)
