#!/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 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:
    if os.geteuid() == 0:
      subprocess.Popen([
        "su", "-", "user", "-c",
        f"DISPLAY=:0 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/10000/bus 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", "unix:path=/run/user/10000/bus")
      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_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)

  # Make adapter discoverable and pairable when Bluetooth is ON so senders can see the phone
  subprocess.run(["bluetoothctl", "discoverable-timeout", "0"],
                 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  subprocess.run(["bluetoothctl", "discoverable", "on"],
                 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  subprocess.run(["bluetoothctl", "pairable", "on"],
                 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

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