#!/usr/bin/python3

"""This program is in charge of watching what wol-monitor writes to its FIFO
bus, nominally located at /run/wol-monitor/wol-bus, then running XBMC in
response to writes to that bus."""

import socket
import subprocess
import sys
import time
import threading


ACTIVATE_KODI_CMD = (
    "xdotool search --desktop 0 --all --class --name Kodi windowactivate"
    " || "
    "kwin_wmgmt_helper Kodi"
)


def _in_(needles, haystack):
    for needle in needles:
        if needle in haystack:
            return True
    return False


def report(text: str, *args):
    if args:
        text = text % args
    print(text, file=sys.stderr)


def start_xbmc_if_not_started():
    if "--test" in sys.argv[1:]:
        report("Simulating start of Kodi")
        return

    report("Searching for Kodi window")
    if 0 != subprocess.call(
        ACTIVATE_KODI_CMD,
        shell=True,
    ):
        report("Starting Kodi")
        p = subprocess.Popen("kodi-standalone")
        collector = threading.Thread(target=lambda: p.wait())
        collector.daemon = True
        collector.start()


class WOLWatcher:
    def run(self):
        while True:
            bus = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            while True:
                try:
                    bus.connect("/run/wol-monitor/wol-bus")
                    break
                except Exception as e:
                    report(
                        "Error trying to connect to bus: %s",
                        e,
                    )
                    time.sleep(5)
            try:
                while bus.recv(1):
                    start_xbmc_if_not_started()
            except Exception as e:
                report(
                    "Error reading from bus: %s",
                    e,
                )
            bus.close()


watcher = WOLWatcher()
watcher.run()
