#!/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 run_gamepad_uinput_bridge(is_running):
  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

  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 now - last_scan >= 2.0:
      last_scan = now
      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)
            if has_gamepad:
              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

    if not gamepads:
      time.sleep(1.5)
      continue

    fd_map = {info["fd"]: (path, info) for path, info in list(gamepads.items())}
    try:
      rlist, _, _ = select.select(list(fd_map.keys()), [], [], 1.0)
    except Exception:
      time.sleep(0.5)
      continue

    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

  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 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

  def stop_handler(_signum, _frame):
    nonlocal running
    running = False

  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,), daemon=True)
  gp_thread.start()

  profile_path = "/org/bananarchy/obex_opp"
  conn = None
  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"),
      "Role": ("s", "server"),
      "Channel": ("q", 9),
      "RequireAuthentication": ("b", False),
      "RequireAuthorization": ("b", False),
      "AutoConnect": ("b", True),
    }
    reg_msg = new_method_call(pm, "RegisterProfile", "osa{sv}",
                              (profile_path, OPP_UUID, opts))
    conn.send_and_get_reply(reg_msg, timeout=5.0)
  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:
        try:
          msg = conn.receive(timeout=1.0)
        except TimeoutError:
          msg = None
        if msg is not None and 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)
      else:
        time.sleep(1.0)

      if rfcomm_listener is not None:
        try:
          csock, _addr = rfcomm_listener.accept()
          t = threading.Thread(target=handle_obex_rx_session,
                               args=(csock,), daemon=True)
          t.start()
        except BlockingIOError:
          pass
    except Exception:
      time.sleep(0.5)

  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 stop_daemon():
  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, signal.SIGTERM)
    except Exception:
      pass
    try:
      os.unlink(PID_FILE)
    except OSError:
      pass
  subprocess.run(["pkill", "-f", "bananarchy-bt-obex daemon"],
                 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def main():
  cmd = sys.argv[1] if len(sys.argv) > 1 else "status"
  if cmd == "daemon":
    run_daemon()
  elif cmd == "start":
    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 0
      except Exception:
        pass
    subprocess.Popen([sys.executable, __file__, "daemon"],
                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                     start_new_session=True)
    return 0
  elif cmd == "stop":
    stop_daemon()
    return 0
  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())
