#!/usr/bin/python3
# blob:summary=Share your internet as a Wi-Fi hotspot with your own name and password
# blob:args=[status|on|off|toggle|mode keep|replace|save <ssid> <band> (password on stdin)|password]
# blob:group=network

from __future__ import annotations

import json
import os
import subprocess
import sys
import uuid
from pathlib import Path
from typing import Any

import dbus

CONNECTION_ID = "blob-hotspot"
NM = "org.freedesktop.NetworkManager"
NM_PATH = "/org/freedesktop/NetworkManager"
SETTINGS_PATH = "/org/freedesktop/NetworkManager/Settings"
DEVICE_TYPE_WIFI = 2
ACTIVE_STATES = {1: "starting", 2: "on", 3: "stopping", 4: "off"}
BANDS = {"2.4": "bg", "5": "a", "auto": ""}
HELPER = "/usr/local/lib/blob/blob-hotspot-share"
SHARED_STATE = Path("/run/blob-hotspot/state.json")
SHARED_LEASES = Path("/run/blob-hotspot/leases")
SETTINGS_FILE = Path(os.environ.get("XDG_STATE_HOME", str(Path.home() / ".local" / "state"))) / "blob" / "hotspot.json"


def hotspot_mode() -> str:
  try:
    mode = json.loads(SETTINGS_FILE.read_text(encoding="utf-8")).get("mode", "keep")
  except (OSError, ValueError, AttributeError):
    mode = "keep"
  return mode if mode in ("keep", "replace") else "keep"


def set_mode(mode: str) -> int:
  if mode not in ("keep", "replace"):
    print("Mode must be keep or replace", file=sys.stderr)
    return 2
  SETTINGS_FILE.parent.mkdir(parents=True, exist_ok=True)
  SETTINGS_FILE.write_text(json.dumps({"mode": mode}) + "\n", encoding="utf-8")
  return 0


def shared_state() -> dict[str, Any]:
  try:
    state = json.loads(SHARED_STATE.read_text(encoding="utf-8"))
  except (OSError, ValueError):
    return {}
  return state if state.get("group") and Path(f"/sys/class/net/{state['group']}").exists() else {}


def bus_object(bus: dbus.SystemBus, path: str, interface: str) -> dbus.Interface:
  return dbus.Interface(bus.get_object(NM, path), interface)


def properties(bus: dbus.SystemBus, path: str, interface: str) -> dict[str, Any]:
  return bus_object(bus, path, "org.freedesktop.DBus.Properties").GetAll(interface)


def wifi_device(bus: dbus.SystemBus) -> tuple[str, str] | None:
  manager = bus_object(bus, NM_PATH, NM)
  for path in manager.GetDevices():
    device = properties(bus, path, NM + ".Device")
    if int(device["DeviceType"]) == DEVICE_TYPE_WIFI:
      return str(path), str(device["Interface"])
  return None


def find_connection(bus: dbus.SystemBus) -> str | None:
  settings = bus_object(bus, SETTINGS_PATH, NM + ".Settings")
  for path in settings.ListConnections():
    values = bus_object(bus, path, NM + ".Settings.Connection").GetSettings()
    if str(values.get("connection", {}).get("id", "")) == CONNECTION_ID:
      return str(path)
  return None


def active_connection(bus: dbus.SystemBus, connection_path: str | None) -> tuple[str, int] | None:
  if connection_path is None:
    return None
  for path in properties(bus, NM_PATH, NM)["ActiveConnections"]:
    try:
      active = properties(bus, path, NM + ".Connection.Active")
    except dbus.DBusException:
      continue
    if str(active["Connection"]) == connection_path:
      return str(path), int(active["State"])
  return None


def saved_secret(bus: dbus.SystemBus, connection_path: str) -> str:
  try:
    secrets = bus_object(bus, connection_path, NM + ".Settings.Connection").GetSecrets("802-11-wireless-security")
  except dbus.DBusException:
    return ""
  return str(secrets.get("802-11-wireless-security", {}).get("psk", ""))


def default_route_device() -> str:
  try:
    routes = json.loads(subprocess.run(["ip", "-j", "-4", "route", "show", "default"], capture_output=True, text=True, timeout=5).stdout or "[]")
  except (OSError, subprocess.TimeoutExpired, ValueError):
    return ""
  return str(routes[0].get("dev", "")) if routes else ""


def clients(interface: str, leases: Path | None = None) -> list[dict[str, str]]:
  leases = leases or Path(f"/var/lib/NetworkManager/dnsmasq-{interface}.leases")
  found = []
  try:
    lines = leases.read_text(encoding="utf-8").splitlines()
  except OSError:
    lines = []
  for line in lines:
    parts = line.split()
    if len(parts) >= 4:
      found.append({"mac": parts[1], "address": parts[2], "name": "" if parts[3] == "*" else parts[3]})
  return found


def status() -> dict[str, Any]:
  bus = dbus.SystemBus()
  device = wifi_device(bus)
  connection_path = find_connection(bus)
  values: dict[str, Any] = {}
  if connection_path:
    values = bus_object(bus, connection_path, NM + ".Settings.Connection").GetSettings()
  wireless = values.get("802-11-wireless", {})
  band = str(wireless.get("band", ""))
  active = active_connection(bus, connection_path)
  state = ACTIVE_STATES.get(active[1], "off") if active else "off"
  interface = device[1] if device else ""
  upstream = default_route_device()
  mode = hotspot_mode()
  shared = shared_state()
  result = {
    "available": device is not None,
    "interface": interface,
    "configured": connection_path is not None,
    "ssid": bytes(wireless.get("ssid", b"")).decode("utf-8", errors="replace"),
    "band": {"bg": "2.4", "a": "5"}.get(band, "auto"),
    "mode": mode,
    "helperInstalled": os.access(HELPER, os.X_OK),
    "state": state,
    "upstream": upstream if upstream != interface else "",
    "wifiIsUpstream": upstream == interface and state != "on" and mode == "replace",
    "clients": clients(interface) if state == "on" else [],
    "qrInterface": interface,
  }
  if shared:
    result.update(
      state="on",
      mode="keep",
      ssid=shared.get("ssid", result["ssid"]),
      upstream=shared.get("upstream", ""),
      clients=clients("", SHARED_LEASES),
      qrInterface=shared.get("group", ""),
      frequency=shared.get("frequency", 0),
    )
  return result


def save(ssid: str, band: str, password: str) -> int:
  if not 1 <= len(ssid.encode("utf-8")) <= 32:
    print("The name must be 1 to 32 characters", file=sys.stderr)
    return 2
  if band not in BANDS:
    print("Band must be 2.4, 5 or auto", file=sys.stderr)
    return 2
  bus = dbus.SystemBus()
  device = wifi_device(bus)
  if device is None:
    print("No Wi-Fi card found", file=sys.stderr)
    return 1
  connection_path = find_connection(bus)
  if not password and connection_path:
    password = saved_secret(bus, connection_path)
  if not 8 <= len(password) <= 63:
    print("The password must be 8 to 63 characters", file=sys.stderr)
    return 2
  wireless = dbus.Dictionary({"ssid": dbus.ByteArray(ssid.encode("utf-8")), "mode": "ap"}, signature="sv")
  if BANDS[band]:
    wireless["band"] = BANDS[band]
  settings = dbus.Dictionary({
    "connection": dbus.Dictionary({
      "id": CONNECTION_ID,
      "uuid": str(uuid.uuid4()),
      "type": "802-11-wireless",
      "interface-name": device[1],
      "autoconnect": False,
    }, signature="sv"),
    "802-11-wireless": wireless,
    "802-11-wireless-security": dbus.Dictionary({
      "key-mgmt": "wpa-psk",
      "psk": password,
      "proto": dbus.Array(["rsn"], signature="s"),
      "pairwise": dbus.Array(["ccmp"], signature="s"),
      "group": dbus.Array(["ccmp"], signature="s"),
    }, signature="sv"),
    "ipv4": dbus.Dictionary({"method": "shared"}, signature="sv"),
    "ipv6": dbus.Dictionary({"method": "ignore"}, signature="sv"),
  }, signature="sa{sv}")
  try:
    if connection_path:
      connection = bus_object(bus, connection_path, NM + ".Settings.Connection")
      settings["connection"]["uuid"] = str(connection.GetSettings()["connection"]["uuid"])
      connection.Update(settings)
    else:
      bus_object(bus, SETTINGS_PATH, NM + ".Settings").AddConnection(settings)
  except dbus.DBusException as error:
    print(f"NetworkManager refused the hotspot settings: {error.get_dbus_message()}", file=sys.stderr)
    return 1
  if shared_state():
    return switch_shared(False) or switch_shared(True)
  active = active_connection(bus, connection_path)
  if active and active[1] == 2:
    return switch(True)
  return 0


def run_helper(action: str, request: dict[str, Any] | None = None) -> int:
  if not os.access(HELPER, os.X_OK):
    print("The hotspot helper is not installed yet. Run the installer, or see docs/shell.md", file=sys.stderr)
    return 1
  result = subprocess.run(["pkexec", HELPER, action], input=(json.dumps(request) + "\n") if request else "", capture_output=True, text=True)
  if result.returncode != 0:
    print((result.stderr or "The hotspot helper failed").strip(), file=sys.stderr)
  return result.returncode


def switch_shared(turn_on: bool) -> int:
  if not turn_on:
    return run_helper("stop")
  bus = dbus.SystemBus()
  connection_path = find_connection(bus)
  device = wifi_device(bus)
  if connection_path is None or device is None:
    print("Set a name and password first", file=sys.stderr)
    return 1
  values = bus_object(bus, connection_path, NM + ".Settings.Connection").GetSettings()
  wireless = values.get("802-11-wireless", {})
  upstream = default_route_device()
  if not upstream:
    print("You are not connected to the internet, so there is nothing to share", file=sys.stderr)
    return 1
  return run_helper("start", {
    "ssid": bytes(wireless.get("ssid", b"")).decode("utf-8", errors="replace"),
    "password": saved_secret(bus, connection_path),
    "band": "5" if str(wireless.get("band", "")) == "a" else "2.4",
    "wifi": device[1],
    "upstream": upstream,
  })


def switch(turn_on: bool) -> int:
  if shared_state():
    return switch_shared(False) if not turn_on else 0
  if turn_on and hotspot_mode() == "keep":
    return switch_shared(True)
  bus = dbus.SystemBus()
  connection_path = find_connection(bus)
  manager = bus_object(bus, NM_PATH, NM)
  try:
    if turn_on:
      device = wifi_device(bus)
      if connection_path is None or device is None:
        print("Set a name and password first", file=sys.stderr)
        return 1
      manager.ActivateConnection(connection_path, device[0], "/")
    else:
      active = active_connection(bus, connection_path)
      if active:
        manager.DeactivateConnection(active[0])
  except dbus.DBusException as error:
    print(f"NetworkManager could not {'start' if turn_on else 'stop'} the hotspot: {error.get_dbus_message()}", file=sys.stderr)
    return 1
  return 0


def main(arguments: list[str]) -> int:
  action = arguments[0] if arguments else "status"
  try:
    if action == "status":
      print(json.dumps(status()))
      return 0
    if action in ("on", "off"):
      return switch(action == "on")
    if action == "toggle":
      return switch(status()["state"] == "off")
    if action == "mode" and len(arguments) == 2:
      return set_mode(arguments[1])
    if action == "save" and len(arguments) == 3:
      password = sys.stdin.readline().rstrip("\n") if not sys.stdin.isatty() else ""
      return save(arguments[1], arguments[2], password)
    if action == "password":
      bus = dbus.SystemBus()
      connection_path = find_connection(bus)
      print(saved_secret(bus, connection_path) if connection_path else "")
      return 0
  except dbus.DBusException as error:
    print(f"Could not talk to NetworkManager: {error.get_dbus_message()}", file=sys.stderr)
    return 1
  print("blob-hotspot does not understand: " + " ".join(arguments), file=sys.stderr)
  return 2


if __name__ == "__main__":
  sys.exit(main(sys.argv[1:]))
