#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-only
# Bananarchy Bluetooth OBEX Object Push (OPP) Server & Client

import os
import sys
import time
import fcntl
import select
import struct
import socket
import signal
import subprocess
import threading

OPP_UUID = "00001105-0000-1000-8000-00805f9b34fb"
RX_STATUS_FILE = "/tmp/bananarchy_bt_rx.status"
TX_STATUS_FILE = "/tmp/bananarchy_bt_tx.status"
PID_FILE = "/tmp/bananarchy_bt_obex.pid"
DURESS_FLAG = "/tmp/bananarchy_duress_mode"


def is_duress_mode():
  return os.path.exists(DURESS_FLAG)


def get_downloads_dir():
  if is_duress_mode():
    base = "/tmp/duress_home"
  else:
    base = "/home/user"
  dl = os.path.join(base, "Downloads")
  os.makedirs(dl, exist_ok=True)
  try:
    os.chown(dl, 10000, 10000)
  except OSError:
    pass
  return dl


def write_status(path, text):
  try:
    tmp = path + ".tmp"
    with open(tmp, "w", encoding="utf-8") as f:
      f.write(text.strip() + "\n")
    os.chmod(tmp, 0o644)
    os.replace(tmp, path)
  except OSError:
    pass


def notify_networks_ui():
  fifo = "/tmp/dwm_plugin_networks.fifo"
  if os.path.exists(fifo):
    try:
      fd = os.open(fifo, os.O_WRONLY | os.O_NONBLOCK)
      os.write(fd, b"REFRESH_BT\n")
      os.close(fd)
    except OSError:
      pass


def notify_user(title, body):
  try:
    bus_addr = "unix:path=/run/user/10000/bus"
    if os.path.exists("/run/user/10000/dbus.bus"):
      try:
        with open("/run/user/10000/dbus.bus", "r", encoding="utf-8") as bf:
          line = bf.readline().strip()
          if line:
            bus_addr = line
      except OSError:
        pass
    if os.geteuid() == 0:
      subprocess.Popen([
        "su", "-", "user", "-c",
        f"DISPLAY=:0 DBUS_SESSION_BUS_ADDRESS={subprocess.list2cmdline([bus_addr])} notify-send {subprocess.list2cmdline([title, body])}"
      ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    else:
      env = os.environ.copy()
      env.setdefault("DISPLAY", ":0")
      env.setdefault("DBUS_SESSION_BUS_ADDRESS", bus_addr)
      subprocess.Popen(["notify-send", title, body],
                       env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  except Exception:
    pass


def format_size(num_bytes):
  if num_bytes >= 1024 * 1024:
    return f"{num_bytes / (1024.0 * 1024.0):.1f} MB"
  if num_bytes >= 1024:
    return f"{num_bytes / 1024.0:.1f} KB"
  return f"{num_bytes} B"


def safe_filename(raw_name):
  name = os.path.basename(raw_name.replace("\\", "/")).strip()
  clean = "".join(c if (c.isalnum() or c in "._- ()[]") else "_" for c in name)
  if not clean or clean in (".", ".."):
    clean = f"bt_file_{int(time.time())}.bin"
  return clean


def unique_dest_path(directory, filename):
  cand = os.path.join(directory, filename)
  if not os.path.exists(cand):
    return cand
  stem, ext = os.path.splitext(filename)
  idx = 1
  while True:
    cand = os.path.join(directory, f"{stem}_{idx}{ext}")
    if not os.path.exists(cand):
      return cand
    idx += 1


def recv_exact(sock, n):
  buf = bytearray()
  while len(buf) < n:
    chunk = sock.recv(n - len(buf))
    if not chunk:
      return None
    buf.extend(chunk)
  return bytes(buf)


def recv_obex_packet(sock):
  hdr = recv_exact(sock, 3)
  if not hdr:
    return None, None
  opcode = hdr[0]
  pkt_len = struct.unpack(">H", hdr[1:3])[0]
  if pkt_len < 3:
    return opcode, b""
  payload = recv_exact(sock, pkt_len - 3)
  if payload is None:
    return None, None
  return opcode, payload


def handle_obex_rx_session(sock):
  sock.settimeout(30.0)
  out_file = None
  out_path = None
  file_name = ""
  total_len = 0
  rx_bytes = 0
  last_ui_notify = 0.0

  try:
    while True:
      opcode, payload = recv_obex_packet(sock)
      if opcode is None:
        break

      op_base = opcode & 0x7F
      is_final = (opcode & 0x80) != 0

      if opcode == 0x80:  # CONNECT
        # OBEX CONNECT response: 0xA0 (OK), len 7, ver 0x10, flags 0, max_pkt 0x8000
        resp = struct.pack(">BHBBH", 0xA0, 7, 0x10, 0x00, 0x8000)
        sock.sendall(resp)

      elif opcode == 0x81:  # DISCONNECT
        sock.sendall(struct.pack(">BH", 0xA0, 3))
        break

      elif opcode in (0xFF, 0x7F):  # ABORT
        if out_file:
          out_file.close()
          out_file = None
        if out_path and os.path.exists(out_path):
          try:
            os.unlink(out_path)
          except OSError:
            pass
        write_status(RX_STATUS_FILE, "IDLE\tReady (~/Downloads)")
        notify_networks_ui()
        sock.sendall(struct.pack(">BH", 0xA0, 3))
        break

      elif op_base == 0x02:  # PUT / PUT-Final
        pos = 0
        plen = len(payload)
        body_chunks = []

        while pos < plen:
          hi = payload[pos]
          pos += 1
          h_encoding = hi & 0xC0

          if h_encoding in (0x00, 0x40):  # 2-byte length prefixed
            if pos + 2 > plen:
              break
            hlen = struct.unpack(">H", payload[pos:pos + 2])[0]
            if hlen < 3 or pos + hlen - 1 > plen:
              break
            hdata = payload[pos + 2:pos + hlen - 1]
            pos += hlen - 1

            if hi == 0x01:  # Name (UTF-16BE)
              try:
                decoded = hdata.decode("utf-16-be", errors="replace").rstrip("\x00")
              except Exception:
                decoded = "received_file"
              file_name = safe_filename(decoded)
            elif hi in (0x48, 0x49):  # Body / End-of-Body
              body_chunks.append(hdata)

          elif h_encoding == 0x80:  # 1-byte value
            pos += 1

          elif h_encoding == 0xC0:  # 4-byte value
            if pos + 4 > plen:
              break
            val = struct.unpack(">I", payload[pos:pos + 4])[0]
            pos += 4
            if hi == 0xC3:  # Length
              total_len = val

        if body_chunks and out_file is None:
          if not file_name:
            file_name = f"bt_rx_{int(time.time())}.bin"
          dl_dir = get_downloads_dir()
          out_path = unique_dest_path(dl_dir, file_name)
          out_file = open(out_path, "wb")
          try:
            os.chown(out_path, 10000, 10000)
          except OSError:
            pass

        for chunk in body_chunks:
          if out_file:
            out_file.write(chunk)
            rx_bytes += len(chunk)

        now = time.time()
        if not is_final:
          if now - last_ui_notify >= 0.4:
            pct = int((rx_bytes * 100) // total_len) if total_len > 0 else 0
            write_status(
              RX_STATUS_FILE,
              f"RECEIVING\t{file_name or '...'}\t{rx_bytes}\t{total_len}\t{pct}%"
            )
            notify_networks_ui()
            last_ui_notify = now
          sock.sendall(struct.pack(">BH", 0x90, 3))  # Continue
        else:
          if out_file:
            out_file.flush()
            out_file.close()
            out_file = None
            try:
              os.chown(out_path, 10000, 10000)
              os.chmod(out_path, 0o644)
            except OSError:
              pass
            saved_base = os.path.basename(out_path)
            sz_str = format_size(rx_bytes)
            write_status(
              RX_STATUS_FILE,
              f"RECEIVED\t{saved_base}\t{sz_str}\t{out_path}"
            )
            notify_networks_ui()
            notify_user("Bluetooth File Received",
                        f"{saved_base} ({sz_str}) saved to Downloads")
          sock.sendall(struct.pack(">BH", 0xA0, 3))  # Success
          out_path = None
          file_name = ""
          total_len = 0
          rx_bytes = 0

      elif op_base == 0x05:  # SETPATH
        sock.sendall(struct.pack(">BH", 0xA0, 3))

      else:
        sock.sendall(struct.pack(">BH", 0xD1, 3))  # Not Implemented
  except Exception:
    if out_file:
      try:
        out_file.close()
      except Exception:
        pass
  finally:
    try:
      sock.close()
    except Exception:
      pass


def open_input_inotify_fd():
  try:
    import ctypes
    libc = ctypes.CDLL(None, use_errno=True)
    libc.inotify_init.argtypes = []
    libc.inotify_init.restype = ctypes.c_int
    libc.inotify_add_watch.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_uint32]
    libc.inotify_add_watch.restype = ctypes.c_int
    fd = libc.inotify_init()
    if fd < 0:
      return -1
    os.set_inheritable(fd, False)
    os.set_blocking(fd, False)
    # IN_ATTRIB (0x04) | IN_MOVED_TO (0x80) | IN_CREATE (0x100) | IN_DELETE (0x200)
    if libc.inotify_add_watch(fd, b"/dev/input", 0x00000384) < 0:
      os.close(fd)
      return -1
    return fd
  except Exception:
    return -1


def run_gamepad_uinput_bridge(is_running, wake_r=-1):
  ev_fmt = "llHHi"
  ev_size = struct.calcsize(ev_fmt)
  ui_set_evbit = 0x40045564
  ui_set_keybit = 0x40045565
  ui_dev_create = 0x5501
  ui_dev_destroy = 0x5502
  eviocgbit_key = (2 << 30) | (96 << 16) | (0x45 << 8) | (0x20 + 0x01)

  # Map Linux gamepad button codes to Bananarchy keypad/navigation keys:
  # South(A)=Enter(OK), East(B)=8(GB B), West(X)=5(Fire/Turbo B), North(Y)=6(Turbo A)
  # Start=2(GB Start), Select=3(GB Select), L1=F1(LSK), R1=F2(RSK), L2=*, R2=0, Mode=Esc
  btn_map = {
    0x130: 28,   # BTN_SOUTH (A) -> KEY_ENTER
    0x131: 9,    # BTN_EAST (B) -> KEY_8
    0x132: 8,    # BTN_C -> KEY_7
    0x133: 6,    # BTN_WEST (X) -> KEY_5
    0x134: 7,    # BTN_NORTH (Y) -> KEY_6
    0x135: 10,   # BTN_Z -> KEY_9
    0x136: 59,   # BTN_TL (L1) -> KEY_F1 (Left Softkey)
    0x137: 60,   # BTN_TR (R1) -> KEY_F2 (Right Softkey)
    0x138: 55,   # BTN_TL2 (L2) -> KEY_KPASTERISK (*)
    0x139: 11,   # BTN_TR2 (R2) -> KEY_0
    0x13a: 4,    # BTN_SELECT -> KEY_3
    0x13b: 3,    # BTN_START -> KEY_2
    0x13c: 1,    # BTN_MODE -> KEY_ESC
    0x120: 28,   # BTN_TRIGGER -> KEY_ENTER
    0x121: 9,    # BTN_THUMB -> KEY_8
    0x220: 103,  # BTN_DPAD_UP -> KEY_UP
    0x221: 108,  # BTN_DPAD_DOWN -> KEY_DOWN
    0x222: 105,  # BTN_DPAD_LEFT -> KEY_LEFT
    0x223: 106,  # BTN_DPAD_RIGHT -> KEY_RIGHT
  }
  all_keys = sorted(set(btn_map.values()) | {103, 108, 105, 106})

  uinput_fd = None
  gamepads = {}  # path -> {"fd": int, "hat_x": 0, "hat_y": 0, "lx": 0, "ly": 0, "ax": {}}
  last_scan = 0.0
  last_input_mtime = 0
  inotify_fd = open_input_inotify_fd()
  need_scan = True

  def ensure_uinput():
    nonlocal uinput_fd
    if uinput_fd is not None:
      return True
    try:
      subprocess.run(["modprobe", "-q", "uinput"],
                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
      fd = os.open("/dev/uinput", os.O_WRONLY | os.O_NONBLOCK)
      fcntl.ioctl(fd, ui_set_evbit, 0x00)  # EV_SYN
      fcntl.ioctl(fd, ui_set_evbit, 0x01)  # EV_KEY
      for k in all_keys:
        fcntl.ioctl(fd, ui_set_keybit, k)
      name = b"Bananarchy BT Gamepad Bridge"
      udev = struct.pack("80sHHHHi", name, 0x06, 0x1209, 0x8110, 1, 0) + (b"\x00" * (64 * 4 * 4))
      os.write(fd, udev)
      fcntl.ioctl(fd, ui_dev_create)
      uinput_fd = fd
      return True
    except Exception:
      return False

  def emit_key(code, val):
    if uinput_fd is None and not ensure_uinput():
      return
    try:
      os.write(uinput_fd, struct.pack(ev_fmt, 0, 0, 0x01, code, val))
      os.write(uinput_fd, struct.pack(ev_fmt, 0, 0, 0x00, 0, 0))
    except OSError:
      pass

  def get_axis_dir(fd, axis, val, cache):
    if axis not in cache:
      try:
        ioc = (2 << 30) | (24 << 16) | (0x45 << 8) | (0x40 + axis)
        buf = fcntl.ioctl(fd, ioc, b"\x00" * 24)
        _v, min_v, max_v, _fz, _fl, _rs = struct.unpack("6i", buf)
        if max_v > min_v:
          cache[axis] = (min_v, max_v)
        else:
          cache[axis] = (-32768, 32767)
      except Exception:
        cache[axis] = (-32768, 32767)
    min_v, max_v = cache[axis]
    mid = (min_v + max_v) / 2.0
    span = (max_v - min_v) / 2.0
    if span <= 0:
      return 0
    norm = (val - mid) / span
    if norm < -0.40:
      return -1
    if norm > 0.40:
      return 1
    return 0

  while is_running():
    now = time.monotonic()
    if need_scan or (inotify_fd < 0 and now - last_scan >= 2.0):
      need_scan = False
      last_scan = now
      try:
        st_in = os.stat("/dev/input")
        if last_input_mtime != 0 and st_in.st_mtime_ns != last_input_mtime:
          subprocess.Popen(
            ["sh", "-c", "DISPLAY=:0 xsetroot -name \"$(cat /tmp/sxmo_status_bar 2>/dev/null || printf 'Bananarchy')\" >/dev/null 2>&1 || sxmo_hook_statusbar.sh >/dev/null 2>&1"],
            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
          )
        last_input_mtime = st_in.st_mtime_ns
      except OSError:
        pass
      try:
        for entry in os.listdir("/dev/input"):
          if not entry.startswith("event"):
            continue
          dev_path = f"/dev/input/{entry}"
          if dev_path in gamepads:
            continue
          sys_name_path = f"/sys/class/input/{entry}/device/name"
          try:
            with open(sys_name_path, "r", encoding="utf-8") as nf:
              dname = nf.read().strip()
            if "Bananarchy BT Gamepad Bridge" in dname:
              continue
          except OSError:
            pass
          try:
            fd = os.open(dev_path, os.O_RDONLY | os.O_NONBLOCK)
            buf = bytearray(96)
            fcntl.ioctl(fd, eviocgbit_key, buf, True)
            has_gamepad = bool((buf[0x130 // 8] >> (0x130 % 8)) & 1) or bool((buf[0x120 // 8] >> (0x120 % 8)) & 1)
            has_qwerty = bool((buf[16 // 8] >> (16 % 8)) & 1) and bool((buf[30 // 8] >> (30 % 8)) & 1)
            if has_gamepad and not has_qwerty:
              ensure_uinput()
              gamepads[dev_path] = {
                "fd": fd, "hat_x": 0, "hat_y": 0, "lx": 0, "ly": 0, "ax": {}
              }
            else:
              os.close(fd)
          except Exception:
            pass
      except OSError:
        pass

    fd_map = {info["fd"]: (path, info) for path, info in list(gamepads.items())}
    wait_fds = list(fd_map.keys())
    if inotify_fd >= 0:
      wait_fds.append(inotify_fd)
    if wake_r >= 0:
      wait_fds.append(wake_r)
    if not wait_fds:
      time.sleep(1.5)
      continue
    sel_timeout = None if (inotify_fd >= 0 and wake_r >= 0) else 2.0
    try:
      rlist, _, _ = select.select(wait_fds, [], [], sel_timeout)
    except Exception:
      if is_running():
        time.sleep(0.5)
      continue

    if not is_running():
      break

    if inotify_fd >= 0 and inotify_fd in rlist:
      while True:
        try:
          if not os.read(inotify_fd, 512):
            break
        except BlockingIOError:
          break
        except OSError:
          break
      need_scan = True

    for rfd in rlist:
      path, info = fd_map.get(rfd, (None, None))
      if not path:
        continue
      try:
        data = os.read(rfd, ev_size * 16)
        if not data:
          raise OSError("EOF")
      except OSError:
        try:
          os.close(rfd)
        except OSError:
          pass
        gamepads.pop(path, None)
        continue

      offset = 0
      while offset + ev_size <= len(data):
        _sec, _usec, ev_type, ev_code, ev_val = struct.unpack_from(ev_fmt, data, offset)
        offset += ev_size
        if ev_type == 0x01 and ev_code in btn_map:
          if ev_val in (0, 1, 2):
            emit_key(btn_map[ev_code], ev_val)
        elif ev_type == 0x03:
          if ev_code == 0x10:  # ABS_HAT0X
            new_dir = -1 if ev_val < 0 else (1 if ev_val > 0 else 0)
            old_dir = info["hat_x"]
            if new_dir != old_dir:
              if old_dir == -1:
                emit_key(105, 0)
              elif old_dir == 1:
                emit_key(106, 0)
              if new_dir == -1:
                emit_key(105, 1)
              elif new_dir == 1:
                emit_key(106, 1)
              info["hat_x"] = new_dir
          elif ev_code == 0x11:  # ABS_HAT0Y
            new_dir = -1 if ev_val < 0 else (1 if ev_val > 0 else 0)
            old_dir = info["hat_y"]
            if new_dir != old_dir:
              if old_dir == -1:
                emit_key(103, 0)
              elif old_dir == 1:
                emit_key(108, 0)
              if new_dir == -1:
                emit_key(103, 1)
              elif new_dir == 1:
                emit_key(108, 1)
              info["hat_y"] = new_dir
          elif ev_code == 0x00:  # ABS_X (Left Stick X)
            new_dir = get_axis_dir(rfd, 0x00, ev_val, info["ax"])
            old_dir = info["lx"]
            if new_dir != old_dir:
              if old_dir == -1:
                emit_key(105, 0)
              elif old_dir == 1:
                emit_key(106, 0)
              if new_dir == -1:
                emit_key(105, 1)
              elif new_dir == 1:
                emit_key(106, 1)
              info["lx"] = new_dir
          elif ev_code == 0x01:  # ABS_Y (Left Stick Y)
            new_dir = get_axis_dir(rfd, 0x01, ev_val, info["ax"])
            old_dir = info["ly"]
            if new_dir != old_dir:
              if old_dir == -1:
                emit_key(103, 0)
              elif old_dir == 1:
                emit_key(108, 0)
              if new_dir == -1:
                emit_key(103, 1)
              elif new_dir == 1:
                emit_key(108, 1)
              info["ly"] = new_dir

  if inotify_fd >= 0:
    try:
      os.close(inotify_fd)
    except OSError:
      pass
  for info in gamepads.values():
    try:
      os.close(info["fd"])
    except OSError:
      pass
  if uinput_fd is not None:
    try:
      fcntl.ioctl(uinput_fd, ui_dev_destroy)
    except Exception:
      pass
    try:
      os.close(uinput_fd)
    except OSError:
      pass


def trust_device_path(conn, dev_path):
  if not isinstance(dev_path, str) or not dev_path.startswith("/org/bluez/"):
    return
  try:
    from jeepney import DBusAddress, new_method_call
    prop_addr = DBusAddress(dev_path, bus_name="org.bluez",
                            interface="org.freedesktop.DBus.Properties")
    conn.send(new_method_call(prop_addr, "Set", "ssv",
                              ("org.bluez.Device1", "Trusted", ("b", True))))
  except Exception:
    pass


def set_hog_preferred_bearer(conn, dev_path, props=None):
  """Force the LE bearer for HID-over-GATT devices before Pair/Connect."""
  if not isinstance(dev_path, str) or not dev_path.startswith("/org/bluez/"):
    return
  uuids = []
  if isinstance(props, dict):
    uuids = [str(v).lower() for v in (props.get("UUIDs") or [])]
  if not any(u.startswith("00001812-") for u in uuids):
    return
  try:
    from jeepney import DBusAddress, new_method_call
    prop_addr = DBusAddress(dev_path, bus_name="org.bluez",
                            interface="org.freedesktop.DBus.Properties")
    conn.send(new_method_call(prop_addr, "Set", "ssv",
                              ("org.bluez.Device1", "PreferredBearer",
                               ("s", "le"))))
  except Exception:
    pass


def handle_agent_method_call(conn, msg, agent_path):
  from jeepney import new_method_return, MessageType
  if msg is None or msg.header.message_type != MessageType.method_call:
    return False
  path = msg.header.fields.get(1)
  member = msg.header.fields.get(3)
  if path != agent_path:
    return False
  dev_path = msg.body[0] if (msg.body and len(msg.body) > 0) else None
  if member in ("RequestConfirmation", "RequestAuthorization", "AuthorizeService"):
    conn.send(new_method_return(msg))
    trust_device_path(conn, dev_path)
    notify_networks_ui()
    return True
  if member == "RequestPinCode":
    conn.send(new_method_return(msg, "s", ("0000",)))
    trust_device_path(conn, dev_path)
    notify_networks_ui()
    return True
  if member == "RequestPasskey":
    conn.send(new_method_return(msg, "u", (0,)))
    trust_device_path(conn, dev_path)
    notify_networks_ui()
    return True
  if member in ("DisplayPinCode", "DisplayPasskey"):
    conn.send(new_method_return(msg))
    trust_device_path(conn, dev_path)
    notify_networks_ui()
    return True
  if member in ("Cancel", "Release"):
    conn.send(new_method_return(msg))
    return True
  conn.send(new_method_return(msg))
  return True


def dbus_call_with_agent(conn, call_msg, agent_path, timeout=5.0):
  from jeepney import HeaderFields, MessageType
  serial = next(conn.outgoing_serial)
  conn.send(call_msg, serial=serial)
  deadline = time.time() + timeout
  while time.time() < deadline:
    rem = max(0.05, deadline - time.time())
    try:
      msg = conn.receive(timeout=rem)
    except TimeoutError:
      return None
    if msg is None:
      continue
    if handle_agent_method_call(conn, msg, agent_path):
      continue
    if msg.header.message_type in (MessageType.method_return, MessageType.error):
      if msg.header.fields.get(HeaderFields.reply_serial, -1) == serial:
        return msg
  return None


def register_bluez_services(conn, profile_path, agent_path):
  from jeepney import DBusAddress, new_method_call
  try:
    aprop = DBusAddress("/org/bluez/hci0", bus_name="org.bluez",
                        interface="org.freedesktop.DBus.Properties")
    dbus_call_with_agent(
      conn,
      new_method_call(aprop, "Set", "ssv",
                      ("org.bluez.Adapter1", "PairableTimeout", ("u", 0))),
      agent_path,
      timeout=2.0
    )
    dbus_call_with_agent(
      conn,
      new_method_call(aprop, "Set", "ssv",
                      ("org.bluez.Adapter1", "Pairable", ("b", True))),
      agent_path,
      timeout=2.0
    )
  except Exception:
    pass
  try:
    am = DBusAddress("/org/bluez", bus_name="org.bluez",
                     interface="org.bluez.AgentManager1")
    dbus_call_with_agent(
      conn,
      new_method_call(am, "RegisterAgent", "os",
                      (agent_path, "NoInputNoOutput")),
      agent_path,
      timeout=3.0
    )
    dbus_call_with_agent(
      conn,
      new_method_call(am, "RequestDefaultAgent", "o", (agent_path,)),
      agent_path,
      timeout=3.0
    )
  except Exception:
    pass
  try:
    pm = DBusAddress("/org/bluez", bus_name="org.bluez",
                     interface="org.bluez.ProfileManager1")
    opts = {
      "Name": ("s", "OBEX Object Push"),
      "Role": ("s", "server"),
      "Channel": ("q", 9),
      "RequireAuthentication": ("b", False),
      "RequireAuthorization": ("b", False),
      "AutoConnect": ("b", True),
    }
    dbus_call_with_agent(
      conn,
      new_method_call(pm, "RegisterProfile", "osa{sv}",
                      (profile_path, OPP_UUID, opts)),
      agent_path,
      timeout=3.0
    )
  except Exception:
    pass


def run_daemon():
  from jeepney import DBusAddress, new_method_call, new_method_return, MessageType
  from jeepney.io.blocking import open_dbus_connection

  with open(PID_FILE, "w", encoding="utf-8") as pf:
    pf.write(f"{os.getpid()}\n")

  write_status(RX_STATUS_FILE, "IDLE\tReady (~/Downloads)")
  notify_networks_ui()

  running = True
  wake_r, wake_w = os.pipe()
  os.set_inheritable(wake_r, False)
  os.set_inheritable(wake_w, False)
  os.set_blocking(wake_r, False)
  os.set_blocking(wake_w, False)

  def stop_handler(_signum, _frame):
    nonlocal running
    running = False
    try:
      os.write(wake_w, b"\x01")
    except OSError:
      pass

  signal.signal(signal.SIGTERM, stop_handler)
  signal.signal(signal.SIGINT, stop_handler)

  bt_name = ""
  try:
    if os.path.exists("/home/user/.config/sxmo/bt_name"):
      with open("/home/user/.config/sxmo/bt_name", "r", encoding="utf-8") as nf:
        bt_name = nf.readline().strip()
  except OSError:
    pass
  if not bt_name:
    try:
      bt_name = socket.gethostname().strip()
    except Exception:
      bt_name = "Bananarchy"
  if bt_name:
    subprocess.run(["timeout", "2", "bluetoothctl", "system-alias", bt_name],
                   stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

  bt_disc = "1"
  try:
    if os.path.exists("/home/user/.config/sxmo/bt_discoverable"):
      with open("/home/user/.config/sxmo/bt_discoverable", "r", encoding="utf-8") as df:
        bt_disc = df.readline().strip() or "1"
  except OSError:
    pass
  disc_on = bt_disc.lower() not in ("0", "off", "no", "false")

  subprocess.run(["timeout", "2", "bluetoothctl", "discoverable-timeout", "0"],
                 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  subprocess.run(["timeout", "2", "bluetoothctl", "discoverable", "on" if disc_on else "off"],
                 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  subprocess.run(["timeout", "2", "bluetoothctl", "pairable", "on"],
                 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

  gp_thread = threading.Thread(target=run_gamepad_uinput_bridge,
                               args=(lambda: running, wake_r), daemon=True)
  gp_thread.start()

  profile_path = "/org/bananarchy/obex_opp"
  agent_path = "/org/bananarchy/bt_agent"
  conn = None
  try:
    conn = open_dbus_connection(bus="SYSTEM", enable_fds=True)
    dbus_bus = DBusAddress("/org/freedesktop/DBus",
                           bus_name="org.freedesktop.DBus",
                           interface="org.freedesktop.DBus")
    conn.send(new_method_call(
      dbus_bus, "AddMatch", "s",
      ("type='signal',sender='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.bluez'",)
    ))
    conn.send(new_method_call(
      dbus_bus, "AddMatch", "s",
      ("type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='org.bluez.Device1'",)
    ))
    register_bluez_services(conn, profile_path, agent_path)
  except Exception:
    pass

  # Also bind a direct RFCOMM listener fallback on channel 9 if BlueZ didn't bind it
  rfcomm_listener = None
  try:
    s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
    s.bind(("00:00:00:00:00:00", 9))
    s.listen(2)
    s.setblocking(False)
    rfcomm_listener = s
  except OSError:
    if rfcomm_listener:
      rfcomm_listener.close()
      rfcomm_listener = None

  while running:
    try:
      if conn is not None:
        while running:
          try:
            msg = conn.receive(timeout=0.0)
          except TimeoutError:
            msg = None
          except (EOFError, OSError):
            try:
              conn.close()
            except Exception:
              pass
            conn = None
            break
          if msg is None:
            break
          if handle_agent_method_call(conn, msg, agent_path):
            pass
          elif msg.header.message_type == MessageType.method_call:
            member = msg.header.fields.get(3)  # Member name
            path = msg.header.fields.get(1)    # Object path
            if path == profile_path and member == "NewConnection":
              # Args: (o device, h fd, a{sv} fd_properties)
              dev_path, fd_obj, _props = msg.body
              reply = new_method_return(msg)
              conn.send(reply)
              raw_fd = os.dup(fd_obj.fileno())
              fd_obj.close()
              client_sock = socket.socket(fileno=raw_fd)
              t = threading.Thread(target=handle_obex_rx_session,
                                   args=(client_sock,), daemon=True)
              t.start()
            elif path == profile_path and member in ("RequestDisconnection", "Release"):
              reply = new_method_return(msg)
              conn.send(reply)
          elif msg.header.message_type == MessageType.signal:
            member = msg.header.fields.get(3)
            if member == "NameOwnerChanged" and msg.body and len(msg.body) >= 3:
              name, _old_owner, new_owner = msg.body[0], msg.body[1], msg.body[2]
              if name == "org.bluez" and new_owner:
                register_bluez_services(conn, profile_path, agent_path)
            elif member == "PropertiesChanged" and msg.body and len(msg.body) >= 2:
              iface, changed = msg.body[0], msg.body[1]
              if iface == "org.bluez.Device1" and isinstance(changed, dict):
                if any(k in changed for k in ("Connected", "Paired", "Bonded")):
                  notify_networks_ui()

      if rfcomm_listener is not None:
        while running:
          try:
            csock, _addr = rfcomm_listener.accept()
            t = threading.Thread(target=handle_obex_rx_session,
                                 args=(csock,), daemon=True)
            t.start()
          except BlockingIOError:
            break

      if not running:
        break

      wait_fds = [wake_r]
      if conn is not None and getattr(conn, "sock", None) is not None:
        wait_fds.append(conn.sock)
      if rfcomm_listener is not None:
        wait_fds.append(rfcomm_listener)
      select.select(wait_fds, [], [], None if len(wait_fds) > 1 else 5.0)
    except Exception:
      if running:
        time.sleep(0.5)

  for fd in (wake_r, wake_w):
    try:
      os.close(fd)
    except OSError:
      pass
  try:
    if os.path.exists(PID_FILE):
      os.unlink(PID_FILE)
  except OSError:
    pass


def connect_opp_socket(mac):
  from jeepney import DBusAddress, new_method_call, new_method_return, MessageType
  from jeepney.io.blocking import open_dbus_connection

  mac = mac.strip().upper()
  dev_path = "/org/bluez/hci0/dev_" + mac.replace(":", "_")
  client_profile_path = f"/org/bananarchy/obex_client_{os.getpid()}"

  # Method 1: Use BlueZ ProfileManager1 client profile + Device1.ConnectProfile
  try:
    conn = open_dbus_connection(bus="SYSTEM", enable_fds=True)
    pm = DBusAddress("/org/bluez", bus_name="org.bluez",
                     interface="org.bluez.ProfileManager1")
    opts = {
      "Name": ("s", "OBEX Object Push Client"),
      "Role": ("s", "client"),
    }
    conn.send_and_get_reply(
      new_method_call(pm, "RegisterProfile", "osa{sv}",
                      (client_profile_path, OPP_UUID, opts)),
      timeout=4.0
    )
    dev_addr = DBusAddress(dev_path, bus_name="org.bluez",
                           interface="org.bluez.Device1")
    conn.send(new_method_call(dev_addr, "ConnectProfile", "s", (OPP_UUID,)))

    deadline = time.time() + 10.0
    while time.time() < deadline:
      rem = max(0.1, deadline - time.time())
      try:
        msg = conn.receive(timeout=rem)
      except TimeoutError:
        break
      if msg.header.message_type == MessageType.method_call:
        if msg.header.fields.get(1) == client_profile_path and \
           msg.header.fields.get(3) == "NewConnection":
          _dpath, fd_obj, _props = msg.body
          conn.send(new_method_return(msg))
          raw_fd = os.dup(fd_obj.fileno())
          fd_obj.close()
          return socket.socket(fileno=raw_fd), conn, client_profile_path
      elif msg.header.message_type == MessageType.error:
        break
    try:
      conn.send_and_get_reply(
        new_method_call(pm, "UnregisterProfile", "o", (client_profile_path,)),
        timeout=2.0
      )
      conn.close()
    except Exception:
      pass
  except Exception:
    pass

  # Method 2: Direct RFCOMM channel scan for common OPP channels
  for ch in (12, 9, 4, 10, 5, 6, 1, 2, 3, 7, 8, 11):
    s = None
    try:
      s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
      s.settimeout(2.5)
      s.connect((mac, ch))
      return s, None, None
    except OSError:
      if s:
        try:
          s.close()
        except Exception:
          pass

  return None, None, None


def send_file_obex(mac, filepath):
  if not os.path.isfile(filepath):
    write_status(TX_STATUS_FILE, "ERROR\tFile not found")
    return 1

  filename = os.path.basename(filepath)
  filesize = os.path.getsize(filepath)
  write_status(TX_STATUS_FILE, f"CONNECTING\t{filename}\t{mac}")

  sock, dbus_conn, prof_path = connect_opp_socket(mac)
  if sock is None:
    write_status(TX_STATUS_FILE, f"ERROR\tCould not connect to {mac}")
    notify_user("Bluetooth Send Failed", f"Could not connect to {mac}")
    return 1

  try:
    sock.settimeout(20.0)
    # 1. OBEX CONNECT
    conn_pkt = struct.pack(">BHBBH", 0x80, 7, 0x10, 0x00, 0x8000)
    sock.sendall(conn_pkt)
    resp_op, resp_body = recv_obex_packet(sock)
    if resp_op != 0xA0 or resp_body is None or len(resp_body) < 4:
      write_status(TX_STATUS_FILE, "ERROR\tOBEX Connect rejected")
      notify_user("Bluetooth Send Failed", "Remote rejected OBEX connection")
      return 1

    remote_max_pkt = struct.unpack(">H", resp_body[2:4])[0]
    max_pkt = min(max(255, remote_max_pkt), 8192)

    # 2. Build Name header (0x01) + Length header (0xC3)
    name_utf16 = filename.encode("utf-16-be") + b"\x00\x00"
    name_hdr = struct.pack(">BH", 0x01, 3 + len(name_utf16)) + name_utf16
    len_hdr = struct.pack(">BI", 0xC3, filesize)
    first_headers = name_hdr + len_hdr

    sent_bytes = 0
    with open(filepath, "rb") as f:
      first = True
      while True:
        hdr_prefix = first_headers if first else b""
        first = False
        max_chunk = max_pkt - 3 - len(hdr_prefix) - 3
        if max_chunk < 64:
          max_chunk = 64
        chunk = f.read(max_chunk)
        eof = (len(chunk) == 0) or (sent_bytes + len(chunk) >= filesize)

        body_hi = 0x49 if eof else 0x48
        body_hdr = struct.pack(">BH", body_hi, 3 + len(chunk)) + chunk
        pkt_payload = hdr_prefix + body_hdr
        pkt_op = 0x82 if eof else 0x02
        pkt = struct.pack(">BH", pkt_op, 3 + len(pkt_payload)) + pkt_payload
        sock.sendall(pkt)

        sent_bytes += len(chunk)
        pct = int((sent_bytes * 100) // filesize) if filesize > 0 else 100
        write_status(TX_STATUS_FILE, f"SENDING\t{filename}\t{pct}%")

        r_op, _r_body = recv_obex_packet(sock)
        if eof:
          if r_op == 0xA0:
            write_status(TX_STATUS_FILE, f"SENT\t{filename}\t{format_size(filesize)}")
            notify_user("Bluetooth File Sent", f"Sent {filename} ({format_size(filesize)})")
            break
          else:
            write_status(TX_STATUS_FILE, f"ERROR\tTransfer rejected (0x{r_op or 0:02X})")
            notify_user("Bluetooth Send Failed", f"Transfer rejected by {mac}")
            return 1
        else:
          if r_op != 0x90:
            write_status(TX_STATUS_FILE, f"ERROR\tTransfer aborted (0x{r_op or 0:02X})")
            notify_user("Bluetooth Send Failed", f"Transfer interrupted ({pct}%)")
            return 1

    # 3. OBEX DISCONNECT
    try:
      sock.sendall(struct.pack(">BH", 0x81, 3))
      recv_obex_packet(sock)
    except Exception:
      pass
    return 0
  except Exception as e:
    write_status(TX_STATUS_FILE, f"ERROR\t{e}")
    notify_user("Bluetooth Send Failed", str(e))
    return 1
  finally:
    try:
      sock.close()
    except Exception:
      pass
    if dbus_conn and prof_path:
      try:
        from jeepney import DBusAddress, new_method_call
        pm = DBusAddress("/org/bluez", bus_name="org.bluez",
                         interface="org.bluez.ProfileManager1")
        dbus_conn.send_and_get_reply(
          new_method_call(pm, "UnregisterProfile", "o", (prof_path,)),
          timeout=2.0
        )
        dbus_conn.close()
      except Exception:
        pass


def ensure_daemon_running():
  if os.path.exists(PID_FILE):
    try:
      with open(PID_FILE, "r", encoding="utf-8") as f:
        pid = int(f.read().strip())
      os.kill(pid, 0)
      return
    except Exception:
      pass
  try:
    subprocess.Popen([sys.executable, __file__, "daemon"],
                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                     start_new_session=True)
    time.sleep(0.25)
  except Exception:
    pass


def prepare_bt_controller():
  """Power the adapter and enable LE before DBus Pair/Connect calls."""
  try:
    subprocess.run(["timeout", "3", "bluetoothctl", "power", "on"],
                   stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                   timeout=4)
  except Exception:
    pass
  helper = "/usr/bin/bananarchy-bt-le-enable.sh"
  try:
    if os.geteuid() == 0:
      subprocess.run([helper], stdout=subprocess.DEVNULL,
                     stderr=subprocess.DEVNULL, timeout=4)
    else:
      subprocess.run(["doas", "-n", helper], stdout=subprocess.DEVNULL,
                     stderr=subprocess.DEVNULL, timeout=4)
  except Exception:
    pass


def clear_stale_linkkey(mac):
  mac = mac.strip().upper()
  if not mac:
    return False
  if os.geteuid() != 0:
    res = subprocess.run(
      ["doas", "-n", "/usr/bin/bananarchy-bt-obex", "clear-linkkey", mac],
      stdout=subprocess.DEVNULL,
      stderr=subprocess.DEVNULL
    )
    return res.returncode == 0

  bt_root = "/var/lib/bluetooth"
  changed = False
  if os.path.isdir(bt_root):
    for adapter in os.listdir(bt_root):
      info_path = os.path.join(bt_root, adapter, mac, "info")
      if not os.path.isfile(info_path):
        continue
      try:
        with open(info_path, "r", encoding="utf-8", errors="replace") as f:
          lines = f.readlines()
        out_lines = []
        skip_sec = False
        for ln in lines:
          s = ln.strip()
          if s.startswith("[") and s.endswith("]"):
            skip_sec = s.lower() in ("[linkkey]", "[longtermkey]", "[peripherallongtermkey]", "[slaveLongtermkey]")
          if not skip_sec:
            out_lines.append(ln)
        if len(out_lines) != len(lines):
          with open(info_path, "w", encoding="utf-8") as f:
            f.writelines(out_lines)
          changed = True
      except Exception:
        pass
  if changed:
    subprocess.run(["rc-service", "bluetooth", "restart"],
                   stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    time.sleep(0.8)
    subprocess.run(["bluetoothctl", "power", "on"],
                   stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    time.sleep(0.4)
  return changed


def connect_or_pair_bt_device(mac, dev_name="", do_pair=False):
  from jeepney import DBusAddress, new_method_call, MessageType
  from jeepney.io.blocking import open_dbus_connection

  ensure_daemon_running()
  prepare_bt_controller()
  mac = mac.strip().upper()
  if not mac:
    return 1

  dev_path = "/org/bluez/hci0/dev_" + mac.replace(":", "_")
  orig_path = dev_path
  cli_agent_path = f"/org/bananarchy/bt_cli_agent_{os.getpid()}"
  adapter_addr = DBusAddress("/org/bluez/hci0", bus_name="org.bluez",
                             interface="org.bluez.Adapter1")
  am_addr = DBusAddress("/org/bluez", bus_name="org.bluez",
                        interface="org.bluez.AgentManager1")
  om_addr = DBusAddress("/", bus_name="org.bluez",
                        interface="org.freedesktop.DBus.ObjectManager")

  conn = None
  nonlocal_conn = [None]
  try:
    conn = open_dbus_connection(bus="SYSTEM")
    nonlocal_conn[0] = conn
    aprop_addr = DBusAddress("/org/bluez/hci0", bus_name="org.bluez",
                             interface="org.freedesktop.DBus.Properties")
    dbus_call_with_agent(
      conn,
      new_method_call(aprop_addr, "Set", "ssv",
                      ("org.bluez.Adapter1", "Pairable", ("b", True))),
      cli_agent_path,
      timeout=2.0
    )
    dbus_call_with_agent(
      conn,
      new_method_call(am_addr, "RegisterAgent", "os",
                      (cli_agent_path, "NoInputNoOutput")),
      cli_agent_path,
      timeout=2.5
    )
    dbus_call_with_agent(
      conn,
      new_method_call(am_addr, "RequestDefaultAgent", "o", (cli_agent_path,)),
      cli_agent_path,
      timeout=2.5
    )

    def pump_agent(duration):
      end_t = time.time() + duration
      while time.time() < end_t:
        rem = max(0.05, min(0.25, end_t - time.time()))
        try:
          m = nonlocal_conn[0].receive(timeout=rem)
          if m is not None:
            handle_agent_method_call(nonlocal_conn[0], m, cli_agent_path)
        except TimeoutError:
          pass

    def get_dev_props(dpath):
      prop_addr = DBusAddress(dpath, bus_name="org.bluez",
                              interface="org.freedesktop.DBus.Properties")
      rep = dbus_call_with_agent(
        nonlocal_conn[0],
        new_method_call(prop_addr, "GetAll", "s", ("org.bluez.Device1",)),
        cli_agent_path,
        timeout=2.5
      )
      if rep is None or rep.header.message_type != MessageType.method_return or not rep.body:
        return None
      raw = rep.body[0]
      if not isinstance(raw, dict):
        return None
      out = {}
      for k, v in raw.items():
        out[k] = v[1] if (isinstance(v, (tuple, list)) and len(v) == 2) else v
      return out

    def find_matching_device(target_name, prefer_path=None):
      if not target_name:
        return None
      t_low = target_name.strip().lower()
      rep = dbus_call_with_agent(
        nonlocal_conn[0],
        new_method_call(om_addr, "GetManagedObjects"),
        cli_agent_path,
        timeout=3.0
      )
      if rep is None or rep.header.message_type != MessageType.method_return or not rep.body:
        return None
      objs = rep.body[0]
      if not isinstance(objs, dict):
        return None
      candidates = []
      for opath, ifaces in objs.items():
        if not isinstance(opath, str) or not opath.startswith("/org/bluez/hci0/dev_"):
          continue
        dprops_raw = ifaces.get("org.bluez.Device1") if isinstance(ifaces, dict) else None
        if not isinstance(dprops_raw, dict):
          continue
        dprops = {
          k: (v[1] if isinstance(v, (tuple, list)) and len(v) == 2 else v)
          for k, v in dprops_raw.items()
        }
        nm = str(dprops.get("Name") or dprops.get("Alias") or "").strip().lower()
        if nm == t_low:
          score = 0
          if dprops.get("Connected"):
            score += 100
          if "RSSI" in dprops and dprops.get("RSSI") is not None:
            score += 50
          if opath == prefer_path:
            score += 10
          candidates.append((score, opath))
      if not candidates:
        return None
      candidates.sort(key=lambda x: x[0], reverse=True)
      return candidates[0][1]

    def wait_for_bond_if_connected(dpath, max_wait=3.5):
      deadline = time.time() + max_wait
      while time.time() < deadline:
        pump_agent(0.25)
        p = get_dev_props(dpath)
        if not p or not p.get("Connected"):
          break
        if p.get("Paired") or p.get("Bonded"):
          return p
      return get_dev_props(dpath)

    def cancel_pending_connect(dpath):
      dev_addr = DBusAddress(dpath, bus_name="org.bluez",
                             interface="org.bluez.Device1")
      dbus_call_with_agent(
        nonlocal_conn[0], new_method_call(dev_addr, "Disconnect"), cli_agent_path, timeout=2.0
      )

    def attempt_connect_path(dpath, want_pair):
      p = get_dev_props(dpath)
      set_hog_preferred_bearer(nonlocal_conn[0], dpath, p)
      trust_device_path(nonlocal_conn[0], dpath)
      if p is None:
        return False
      if p.get("Connected"):
        p = wait_for_bond_if_connected(dpath, 3.5) or p
        if p.get("Connected") and (not want_pair or p.get("Paired") or p.get("Bonded")):
          return True

      dev_addr = DBusAddress(dpath, bus_name="org.bluez",
                             interface="org.bluez.Device1")
      if want_pair and not (p.get("Paired") or p.get("Bonded")):
        rep = dbus_call_with_agent(
          nonlocal_conn[0], new_method_call(dev_addr, "Pair"), cli_agent_path, timeout=8.0
        )
        if rep is None:
          cancel_pending_connect(dpath)
        p = get_dev_props(dpath) or {}

      if not p.get("Connected"):
        rep = dbus_call_with_agent(
          nonlocal_conn[0], new_method_call(dev_addr, "Connect"), cli_agent_path, timeout=8.0
        )
        if rep is None:
          cancel_pending_connect(dpath)
        elif rep.header.message_type == MessageType.error:
          err_str = " ".join(str(x) for x in (rep.body or ())).lower()
          if "key-missing" in err_str or "authentication" in err_str:
            dev_mac = dpath.split("dev_")[-1].replace("_", ":")
            if clear_stale_linkkey(dev_mac):
              try:
                nonlocal_conn[0].close()
              except Exception:
                pass
              conn_new = open_dbus_connection(bus="SYSTEM")
              nonlocal_conn[0] = conn_new
              dbus_call_with_agent(
                conn_new,
                new_method_call(aprop_addr, "Set", "ssv",
                                ("org.bluez.Adapter1", "Pairable", ("b", True))),
                cli_agent_path,
                timeout=2.0
              )
              dbus_call_with_agent(
                conn_new,
                new_method_call(am_addr, "RegisterAgent", "os",
                                (cli_agent_path, "NoInputNoOutput")),
                cli_agent_path,
                timeout=2.5
              )
              dbus_call_with_agent(
                conn_new,
                new_method_call(am_addr, "RequestDefaultAgent", "o", (cli_agent_path,)),
                cli_agent_path,
                timeout=2.5
              )
              trust_device_path(conn_new, dpath)
              dbus_call_with_agent(
                conn_new, new_method_call(dev_addr, "Pair"), cli_agent_path, timeout=8.0
              )
              dbus_call_with_agent(
                conn_new, new_method_call(dev_addr, "Connect"), cli_agent_path, timeout=8.0
              )
        p = get_dev_props(dpath) or {}

      if p.get("Connected") and not (p.get("Paired") or p.get("Bonded")):
        p = wait_for_bond_if_connected(dpath, 4.0) or p

      if p.get("Connected"):
        return True
      if want_pair and (p.get("Paired") or p.get("Bonded")):
        return True
      return False

    def scan_for_device(prefer_path, max_scan=15.0):
      dbus_call_with_agent(
        nonlocal_conn[0], new_method_call(adapter_addr, "StartDiscovery"), cli_agent_path, timeout=2.5
      )
      scan_start = time.time()
      scan_deadline = scan_start + max_scan
      discovered_path = prefer_path
      while time.time() < scan_deadline:
        pump_agent(0.35)
        p = get_dev_props(prefer_path)
        if p and (p.get("Connected") or (p.get("RSSI") is not None and (time.time() - scan_start) >= 0.8)):
          discovered_path = prefer_path
          break
        if dev_name:
          alt = find_matching_device(dev_name, prefer_path=prefer_path)
          if alt:
            ap = get_dev_props(alt)
            if ap and (ap.get("Connected") or ap.get("RSSI") is not None):
              discovered_path = alt
              trust_device_path(nonlocal_conn[0], discovered_path)
              if ap.get("Connected") or (time.time() - scan_start) >= 0.8:
                break
      dbus_call_with_agent(
        nonlocal_conn[0], new_method_call(adapter_addr, "StopDiscovery"), cli_agent_path, timeout=2.0
      )
      pump_agent(0.15)
      return discovered_path

    props = get_dev_props(dev_path)
    orig_unbonded = (props is None) or (not props.get("Paired") and not props.get("Bonded"))
    if not do_pair and orig_unbonded and (props is not None or dev_name):
      do_pair = True
    if props and not dev_name:
      dev_name = str(props.get("Name") or props.get("Alias") or "").strip()
    if props is None and dev_name:
      alt = find_matching_device(dev_name)
      if alt:
        dev_path = alt
        props = get_dev_props(dev_path)

    trust_device_path(nonlocal_conn[0], dev_path)

    # Try connecting directly first when BlueZ already knows the device (avoids
    # blocking 15s in StartDiscovery for paired BR/EDR headsets in Page Scan).
    if props is None:
      dev_path = scan_for_device(dev_path, max_scan=8.0)

    ok = attempt_connect_path(dev_path, do_pair)

    if not ok:
      discovered_path = scan_for_device(dev_path, max_scan=8.0)
      ok = attempt_connect_path(discovered_path, do_pair)
      if ok and discovered_path != orig_path and orig_unbonded:
        dbus_call_with_agent(
          nonlocal_conn[0],
          new_method_call(adapter_addr, "RemoveDevice", "o", (orig_path,)),
          cli_agent_path,
          timeout=2.0
        )

    notify_networks_ui()
    return 0 if ok else 1
  except Exception:
    return 1
  finally:
    c_final = nonlocal_conn[0]
    if c_final is not None:
      try:
        dbus_call_with_agent(
          c_final,
          new_method_call(am_addr, "UnregisterAgent", "o", (cli_agent_path,)),
          cli_agent_path,
          timeout=1.5
        )
      except Exception:
        pass
      try:
        c_final.close()
      except Exception:
        pass


def stop_daemon():
  pids = set()
  if os.path.exists(PID_FILE):
    try:
      with open(PID_FILE, "r", encoding="utf-8") as f:
        pid = int(f.read().strip())
      pids.add(pid)
      os.kill(pid, signal.SIGTERM)
    except Exception:
      pass
    try:
      os.unlink(PID_FILE)
    except OSError:
      pass
  # The target rootfs is BusyBox-based and does not ship an external process
  # killer, so find stale daemon command lines through /proc instead.
  try:
    for entry in os.listdir("/proc"):
      if not entry.isdigit() or int(entry) == os.getpid():
        continue
      try:
        with open("/proc/" + entry + "/cmdline", "rb") as cf:
          cmd = cf.read().replace(b"\x00", b" ").decode("utf-8", "replace")
      except OSError:
        continue
      if "bananarchy-bt-obex" in cmd and " daemon" in cmd:
        pids.add(int(entry))
  except OSError:
    pass
  for pid in pids:
    try:
      os.kill(pid, signal.SIGTERM)
    except OSError:
      pass


def main():
  cmd = sys.argv[1] if len(sys.argv) > 1 else "status"
  if cmd == "daemon":
    run_daemon()
  elif cmd == "start":
    ensure_daemon_running()
    return 0
  elif cmd == "stop":
    stop_daemon()
    return 0
  elif cmd == "connect":
    if len(sys.argv) < 3:
      print("Usage: bananarchy-bt-obex connect <MAC> [name]", file=sys.stderr)
      return 1
    nm = sys.argv[3] if len(sys.argv) >= 4 else ""
    return connect_or_pair_bt_device(sys.argv[2], nm, do_pair=False)
  elif cmd == "pair":
    if len(sys.argv) < 3:
      print("Usage: bananarchy-bt-obex pair <MAC> [name]", file=sys.stderr)
      return 1
    nm = sys.argv[3] if len(sys.argv) >= 4 else ""
    return connect_or_pair_bt_device(sys.argv[2], nm, do_pair=True)
  elif cmd == "clear-linkkey":
    if len(sys.argv) < 3:
      return 1
    return 0 if clear_stale_linkkey(sys.argv[2]) else 1
  elif cmd == "send":
    if len(sys.argv) < 4:
      print("Usage: bananarchy-bt-obex send <MAC> <filepath>", file=sys.stderr)
      return 1
    return send_file_obex(sys.argv[2], sys.argv[3])
  elif cmd == "status":
    if os.path.exists(RX_STATUS_FILE):
      with open(RX_STATUS_FILE, "r", encoding="utf-8") as f:
        print(f.read().strip())
    else:
      print("IDLE\tReady (~/Downloads)")
    return 0
  return 0


if __name__ == "__main__":
  sys.exit(main())
