#!/usr/bin/python3

from __future__ import annotations

import hashlib
import json
import os
import re
import signal
import socket
import subprocess
import sys
import time
from pathlib import Path
from typing import Any

STATE_DIRECTORY = Path("/run/blob-hotspot")
STATE_FILE = STATE_DIRECTORY / "state.json"
LEASE_FILE = STATE_DIRECTORY / "leases"
DNSMASQ_PID_FILE = STATE_DIRECTORY / "dnsmasq.pid"
CONTROL_DIRECTORY = Path("/run/wpa_supplicant")
SUBNET_PREFIX = "192.168.79"
GATEWAY = f"{SUBNET_PREFIX}.1"
NFT_TABLE = "blob_hotspot"
FREQUENCIES = {"2.4": 2437, "5": 5180}
INTERFACE_PATTERN = re.compile(r"[A-Za-z0-9_.-]{1,15}")
GROUP_WAIT_SECONDS = 20


class HotspotError(Exception):
  pass


def run(command: list[str], check: bool = True) -> str:
  result = subprocess.run(command, capture_output=True, text=True, timeout=20)
  if check and result.returncode != 0:
    raise HotspotError(f"{command[0]} failed: {(result.stderr or result.stdout).strip()}")
  return result.stdout


class Control:
  def __init__(self, interface: str) -> None:
    self.target = str(CONTROL_DIRECTORY / interface)
    if not os.path.exists(self.target):
      raise HotspotError(f"wpa_supplicant has no control socket for {interface}")
    self.local = str(STATE_DIRECTORY / f"control-{os.getpid()}")
    self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
    self.socket.bind(self.local)
    self.socket.settimeout(10)

  def send(self, command: str) -> str:
    self.socket.sendto(command.encode(), self.target)
    while True:
      reply = self.socket.recv(8192).decode(errors="replace")
      if not reply.startswith("<"):
        return reply.strip()

  def ok(self, command: str) -> None:
    reply = self.send(command)
    if reply != "OK":
      raise HotspotError(f"wpa_supplicant refused {command.split()[0]}: {reply}")

  def close(self) -> None:
    self.socket.close()
    Path(self.local).unlink(missing_ok=True)


def p2p_device(wifi: str) -> str:
  for name in (f"p2p-dev-{wifi}", wifi):
    if (CONTROL_DIRECTORY / name).exists():
      return name
  raise HotspotError("This Wi-Fi card has no Wi-Fi Direct interface")


def group_interfaces(wifi: str) -> set[str]:
  return {path.name for path in Path("/sys/class/net").glob(f"p2p-{wifi}-*")}


def read_state() -> dict[str, Any]:
  try:
    return json.loads(STATE_FILE.read_text(encoding="utf-8"))
  except (OSError, ValueError):
    return {}


def write_state(state: dict[str, Any]) -> None:
  STATE_FILE.write_text(json.dumps(state), encoding="utf-8")
  os.chmod(STATE_FILE, 0o644)


def start_group(control: Control, ssid: str, password: str, frequency: int, wifi: str) -> tuple[str, int]:
  before = group_interfaces(wifi)
  network_id = control.send("ADD_NETWORK")
  if not network_id.isdigit():
    raise HotspotError(f"wpa_supplicant could not add the hotspot network: {network_id}")
  psk = hashlib.pbkdf2_hmac("sha1", password.encode(), ssid.encode(), 4096, 32).hex()
  control.ok(f"SET_NETWORK {network_id} ssid {ssid.encode().hex()}")
  control.ok(f"SET_NETWORK {network_id} psk {psk}")
  control.ok(f"SET_NETWORK {network_id} mode 3")
  control.ok(f"SET_NETWORK {network_id} disabled 2")
  control.ok(f"P2P_GROUP_ADD persistent={network_id} freq={frequency}")
  deadline = time.time() + GROUP_WAIT_SECONDS
  while time.time() < deadline:
    created = group_interfaces(wifi) - before
    if created:
      return sorted(created)[0], int(network_id)
    time.sleep(0.5)
  control.send(f"REMOVE_NETWORK {network_id}")
  raise HotspotError("The hotspot did not start. The card may not allow it on this band")


def nft_rules(group: str, upstream: str) -> str:
  return f"""
table ip {NFT_TABLE} {{
  chain postrouting {{
    type nat hook postrouting priority srcnat; policy accept;
    ip saddr {SUBNET_PREFIX}.0/24 oifname "{upstream}" masquerade
  }}
  chain forward {{
    type filter hook forward priority filter; policy accept;
    iifname "{group}" oifname "{upstream}" accept
    iifname "{upstream}" oifname "{group}" ct state established,related accept
  }}
}}
"""


def ufw_enabled() -> bool:
  try:
    return "ENABLED=yes" in Path("/etc/ufw/ufw.conf").read_text(encoding="utf-8").replace(" ", "")
  except OSError:
    return False


def start(request: dict[str, Any]) -> None:
  ssid = str(request.get("ssid", ""))
  password = str(request.get("password", ""))
  wifi = str(request.get("wifi", ""))
  upstream = str(request.get("upstream", ""))
  frequency = FREQUENCIES.get(str(request.get("band", "2.4")), FREQUENCIES["2.4"])
  if not 1 <= len(ssid.encode()) <= 32:
    raise HotspotError("The name must be 1 to 32 characters")
  if not 8 <= len(password) <= 63:
    raise HotspotError("The password must be 8 to 63 characters")
  if not INTERFACE_PATTERN.fullmatch(wifi) or not INTERFACE_PATTERN.fullmatch(upstream):
    raise HotspotError("No internet connection to share")
  if read_state():
    stop()
  STATE_DIRECTORY.mkdir(mode=0o755, exist_ok=True)
  control = Control(p2p_device(wifi))
  state: dict[str, Any] = {"wifi": wifi, "upstream": upstream, "ssid": ssid, "frequency": frequency, "startedAt": int(time.time())}
  try:
    group, network_id = start_group(control, ssid, password, frequency, wifi)
    state.update(group=group, networkId=network_id, controlInterface=p2p_device(wifi))
    write_state(state)
    run(["nmcli", "device", "set", group, "managed", "no"], check=False)
    run(["ip", "address", "replace", f"{GATEWAY}/24", "dev", group])
    run(["ip", "link", "set", group, "up"])
    state["previousForward"] = Path("/proc/sys/net/ipv4/ip_forward").read_text().strip()
    Path("/proc/sys/net/ipv4/ip_forward").write_text("1")
    write_state(state)
    subprocess.run(["nft", "-f", "-"], input=nft_rules(group, upstream), text=True, check=True, capture_output=True)
    if ufw_enabled():
      run(["ufw", "route", "allow", "in", "on", group, "out", "on", upstream, "comment", "blob-hotspot"], check=False)
      state["ufw"] = True
    LEASE_FILE.unlink(missing_ok=True)
    run([
      "dnsmasq", "--conf-file=/dev/null", f"--interface={group}", "--bind-interfaces", "--except-interface=lo",
      f"--listen-address={GATEWAY}", f"--dhcp-range={SUBNET_PREFIX}.10,{SUBNET_PREFIX}.200,12h",
      f"--dhcp-option=option:router,{GATEWAY}", f"--dhcp-option=option:dns-server,{GATEWAY}",
      f"--dhcp-leasefile={LEASE_FILE}", f"--pid-file={DNSMASQ_PID_FILE}",
    ])
    write_state(state)
  except (HotspotError, subprocess.CalledProcessError, OSError) as error:
    control.close()
    stop()
    raise HotspotError(str(error)) from error
  control.close()


def stop() -> None:
  state = read_state()
  try:
    pid = int(DNSMASQ_PID_FILE.read_text().strip())
    os.kill(pid, signal.SIGTERM)
  except (OSError, ValueError):
    pass
  DNSMASQ_PID_FILE.unlink(missing_ok=True)
  subprocess.run(["nft", "delete", "table", "ip", NFT_TABLE], capture_output=True)
  group = state.get("group", "")
  if state.get("ufw") and group:
    subprocess.run(["ufw", "route", "delete", "allow", "in", "on", group, "out", "on", state.get("upstream", "")], capture_output=True)
  if state.get("previousForward") in ("0", "1"):
    Path("/proc/sys/net/ipv4/ip_forward").write_text(state["previousForward"])
  control_interface = state.get("controlInterface", "")
  if control_interface and INTERFACE_PATTERN.fullmatch(control_interface):
    STATE_DIRECTORY.mkdir(mode=0o755, exist_ok=True)
    try:
      control = Control(control_interface)
      if group:
        control.send(f"P2P_GROUP_REMOVE {group}")
      if isinstance(state.get("networkId"), int):
        control.send(f"REMOVE_NETWORK {state['networkId']}")
      control.close()
    except (HotspotError, OSError):
      pass
  STATE_FILE.unlink(missing_ok=True)
  LEASE_FILE.unlink(missing_ok=True)


def main(arguments: list[str]) -> int:
  action = arguments[0] if arguments else ""
  try:
    if action == "start":
      start(json.loads(sys.stdin.readline() or "{}"))
    elif action == "stop":
      stop()
    else:
      print("Usage: blob-hotspot-share start|stop (start reads its settings as JSON on stdin)", file=sys.stderr)
      return 2
  except (HotspotError, ValueError) as error:
    print(str(error), file=sys.stderr)
    return 1
  return 0


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