#!/usr/bin/env python3
"""Start the Patiobar remote and its matching Melodica pianobar."""
import os
from pathlib import Path
import secrets
import shutil
import subprocess
import tempfile
import time

root = Path(__file__).resolve().parent
original = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "pianobar"
engine = root / "engine/pianobar"
if not engine.is_file():
    raise SystemExit("Unpack the Melodica bundle to run Patiobar with its player.")
with tempfile.TemporaryDirectory(prefix="patiobar-") as temp:
    session = Path(temp)
    settings = session / "pianobar"
    settings.mkdir(mode=0o700)
    fifo = session / "control"
    os.mkfifo(fifo, 0o600)
    source = (original / "config").read_text() if (original / "config").is_file() else ""
    config = settings / "config"
    config.write_text(source + "\nfifo = " + str(fifo) + "\nevent_command = " + str(root / "event.py") + "\n")
    config.chmod(0o600)
    if (original / "state").is_file():
        shutil.copyfile(original / "state", settings / "state")
    env = dict(os.environ, PATIOBAR_SESSION=temp, PATIOBAR_KEY=secrets.token_urlsafe(24))
    # Keep the listener's existing scrobbling or notification command.
    for line in source.splitlines():
        key, sep, value = line.partition("=")
        if sep and key.strip() == "event_command" and value.strip():
            hook = Path(value.strip()).expanduser()
            if hook != root / "event.py":
                env["PATIOBAR_PREVIOUS_HOOK"] = str(hook)
    server = subprocess.Popen(["node", str(root / "index.js")], env=env)
    try:
        for _ in range(200):
            if (session / "ready").is_file():
                break
            if server.poll() is not None:
                raise SystemExit("Patiobar could not open its listening port.")
            time.sleep(.025)
        else:
            raise SystemExit("Patiobar did not start.")
        result = subprocess.run([str(engine)], env=dict(env, XDG_CONFIG_HOME=temp))
        raise SystemExit(result.returncode)
    finally:
        server.terminate()
        server.wait()
