#!/usr/bin/env python3
import ipaddress
import json
import os
import pathlib
import re
import signal
import subprocess
import sys
import time

STATE_DIR = pathlib.Path("/run/lemoa-network-scanner")
STATE_FILE = STATE_DIR / "state.json"
MAX_PINS = 64
MAC_PATTERN = re.compile(r"[0-9a-f]{2}(?::[0-9a-f]{2}){5}")
MONITOR_NAME = re.compile(r"lscmon[0-9]")
# Passive channel tuning bounds. A monitor interface only listens; changing its
# channel never transmits. Duration is capped so a tuning run cannot outlive a
# bounded capture, and the base channel is always restored when it ends.
CHANNEL_FREQUENCY = re.compile(r"^\s*\*\s*(\d+)\s*MHz\s*\[(\d+)\]([^\n]*)$", re.M)
DWELL_MIN_MS = 100
DWELL_MAX_MS = 10000
TUNE_MAX_SECONDS = 300
CHANNEL_LIST_LIMIT = 64


def fail(message):
    print(message, file=sys.stderr)
    raise SystemExit(2)


def command(args):
    result = subprocess.run(args, text=True, capture_output=True, timeout=10)
    if result.returncode:
        fail(result.stderr.strip() or f"Command failed: {' '.join(args)}")
    return result


def valid_interface(name):
    return (
        name != "lo"
        and name.replace("-", "").replace("_", "").isalnum()
        and (pathlib.Path("/sys/class/net") / name).exists()
    )


def valid_network(range_text):
    try:
        network = ipaddress.ip_network(range_text, strict=False)
    except ValueError as exc:
        fail(str(exc))
    if network.version != 4 or network.prefixlen < 16 or network.prefixlen > 30:
        fail("IPv4 range must be between /16 and /30")
    return network


def load_state():
    if not STATE_FILE.exists():
        return {}
    try:
        state = json.loads(STATE_FILE.read_text())
    except ValueError:
        return {}
    return state if isinstance(state, dict) else {}


def save_state(state):
    if not state.get("cidr") and not state.get("pins") and not state.get("monitors"):
        STATE_FILE.unlink(missing_ok=True)
        return
    STATE_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
    temporary = STATE_DIR / ".state.json.tmp"
    temporary.unlink(missing_ok=True)
    descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
    with os.fdopen(descriptor, "w") as output:
        output.write(json.dumps(state))
    os.replace(temporary, STATE_FILE)


def restore_network_state(state):
    """Remove this application's temporary address and neighbour entries."""
    for pin in state.get("pins", []):
        if valid_interface(pin.get("device", "")):
            subprocess.run(["ip", "neigh", "del", pin["address"], "dev", pin["device"]], text=True, capture_output=True, timeout=10)
            print(f"Released {pin['address']} on {pin['device']}")
    device = state.get("device")
    cidr = state.get("cidr")
    if device and cidr and valid_interface(device):
        subprocess.run(["ip", "address", "del", cidr, "dev", device], text=True, capture_output=True, timeout=10)
        print(f"Removed {cidr} from {device}")
    state.pop("pins", None)
    state.pop("device", None)
    state.pop("cidr", None)


def interface_is_monitor(name, phy):
    if not valid_interface(name) or not re.fullmatch(r"phy\d+", phy or ""):
        return False
    try:
        result = subprocess.run(["iw", "dev", name, "info"], text=True, capture_output=True, timeout=10)
    except (OSError, subprocess.TimeoutExpired):
        return False
    return bool(result.returncode == 0
                and re.search(r"^\s*type\s+monitor\s*$", result.stdout, re.M)
                and re.search(rf"^\s*wiphy\s+{int(phy[3:])}\s*$", result.stdout, re.M))


def stop_tracked_monitor(item):
    name, phy = item.get("interface", ""), item.get("phy", "")
    if not MONITOR_NAME.fullmatch(name) or not re.fullmatch(r"phy\d+", phy):
        return False
    if not (pathlib.Path("/sys/class/net") / name).exists():
        return True
    if not interface_is_monitor(name, phy):
        return False
    subprocess.run(["ip", "link", "set", "dev", name, "down"], text=True, capture_output=True, timeout=10)
    try:
        result = subprocess.run(["iw", "dev", name, "del"], text=True, capture_output=True, timeout=10)
    except (OSError, subprocess.TimeoutExpired):
        return False
    if result.returncode and (pathlib.Path("/sys/class/net") / name).exists():
        return False
    print(f"Removed monitor interface {name}")
    return True


def restore():
    if os.geteuid() != 0:
        fail("Administrator privileges are required")
    state = load_state()
    if not state:
        print("No temporary network changes are active")
        return
    restore_network_state(state)
    save_state(state)


def start_monitor(phy):
    if os.geteuid() != 0:
        fail("Administrator privileges are required")
    if not re.fullmatch(r"phy\d+", phy or ""):
        fail("Invalid wireless radio")
    info = command(["iw", "phy", phy, "info"]).stdout
    modes = re.search(r"Supported interface modes:(.*?)(?:\n\s*Band|\n\s*valid interface combinations|\Z)", info, re.S)
    if not modes or not re.search(r"^\s*\*\s+monitor\s*$", modes.group(1), re.M):
        fail("This wireless radio does not report monitor-mode support")
    state = load_state()
    tracked = [item for item in state.get("monitors", []) if isinstance(item, dict)
               and MONITOR_NAME.fullmatch(item.get("interface", ""))
               and (pathlib.Path("/sys/class/net") / item["interface"]).exists()]
    state["monitors"] = tracked
    save_state(state)
    tracked_names = {item.get("interface") for item in tracked if isinstance(item, dict)}
    name = next((f"lscmon{index}" for index in range(10)
                 if f"lscmon{index}" not in tracked_names and not (pathlib.Path("/sys/class/net") / f"lscmon{index}").exists()), None)
    if not name:
        fail("All scanner monitor interface names are in use; stop one first")
    command(["iw", "phy", phy, "interface", "add", name, "type", "monitor"])
    try:
        command(["ip", "link", "set", "dev", name, "up"])
        state["monitors"] = tracked + [{"phy": phy, "interface": name}]
        save_state(state)
    except BaseException:
        subprocess.run(["iw", "dev", name, "del"], text=True, capture_output=True, timeout=10)
        raise
    print(name)


def stop_monitor(name):
    if os.geteuid() != 0:
        fail("Administrator privileges are required")
    if not MONITOR_NAME.fullmatch(name or ""):
        fail("Only monitor interfaces created by this application can be stopped here")
    state = load_state()
    matches = [item for item in state.get("monitors", []) if isinstance(item, dict) and item.get("interface") == name]
    if len(matches) != 1:
        fail("This application does not own that monitor interface")
    if not stop_tracked_monitor(matches[0]):
        fail("The interface could not be safely removed; it may have changed since it was created")
    state["monitors"] = [item for item in state.get("monitors", []) if item.get("interface") != name]
    save_state(state)


def allowed_channels(phy):
    """Channel numbers the driver reports as usable now, per the regulatory domain.

    Disabled channels are excluded. A 'no IR' channel can still be listened to
    passively, so it stays allowed; this helper never initiates on any channel.
    """
    info = command(["iw", "phy", phy, "info"]).stdout
    allowed = {}
    for match in CHANNEL_FREQUENCY.finditer(info):
        frequency, channel, flags = int(match.group(1)), int(match.group(2)), match.group(3)
        if "disabled" in flags:
            continue
        allowed.setdefault(channel, frequency)
    return allowed


def monitor_current_channel(name):
    try:
        info = subprocess.run(["iw", "dev", name, "info"], text=True, capture_output=True, timeout=10).stdout
    except (OSError, subprocess.TimeoutExpired):
        return None
    match = re.search(r"^\s*channel\s+(\d+)", info, re.M)
    return int(match.group(1)) if match else None


def parse_channel_list(text):
    channels = []
    for part in (text or "").split(","):
        part = part.strip()
        if not part.isdigit():
            fail("Channels must be given as comma-separated channel numbers")
        channels.append(int(part))
    if not 1 <= len(channels) <= CHANNEL_LIST_LIMIT:
        fail(f"Choose between 1 and {CHANNEL_LIST_LIMIT} channels")
    return channels


def tune_monitor(name, dwell_text, duration_text, channels_text):
    """Tune a scanner-created monitor interface to a fixed channel, or hop a set of
    channels passively, for a bounded time; restore the prior channel on exit.

    Only this application's own monitor interfaces are touched. The managed
    interface, NetworkManager and wpa_supplicant are never changed or stopped.
    No frames are transmitted: the interface only listens on each channel.
    """
    if os.geteuid() != 0:
        fail("Administrator privileges are required")
    if not MONITOR_NAME.fullmatch(name or ""):
        fail("Only monitor interfaces created by this application can be tuned")
    state = load_state()
    matches = [item for item in state.get("monitors", []) if isinstance(item, dict) and item.get("interface") == name]
    if len(matches) != 1:
        fail("This application does not own that monitor interface")
    phy = matches[0].get("phy", "")
    if not re.fullmatch(r"phy\d+", phy) or not interface_is_monitor(name, phy):
        fail("The monitor interface could not be verified; it may have changed since it was created")
    if not (dwell_text.isdigit() and duration_text.isdigit()):
        fail("Dwell and duration must be whole numbers")
    dwell_ms, duration_s = int(dwell_text), int(duration_text)
    if not DWELL_MIN_MS <= dwell_ms <= DWELL_MAX_MS:
        fail(f"Dwell must be between {DWELL_MIN_MS} and {DWELL_MAX_MS} ms")
    if not 1 <= duration_s <= TUNE_MAX_SECONDS:
        fail(f"Duration must be between 1 and {TUNE_MAX_SECONDS} seconds")
    channels = parse_channel_list(channels_text)
    allowed = allowed_channels(phy)
    for channel in channels:
        if channel not in allowed:
            fail(f"Channel {channel} is not available on this radio in the current regulatory domain")
    base = monitor_current_channel(name)
    stop = {"requested": False}

    def request_stop(_signum, _frame):
        stop["requested"] = True

    signal.signal(signal.SIGTERM, request_stop)
    signal.signal(signal.SIGINT, request_stop)
    deadline = time.monotonic() + duration_s

    def wait(until):
        while not stop["requested"] and time.monotonic() < until:
            time.sleep(min(0.1, max(0.0, until - time.monotonic())))

    try:
        index = 0
        while not stop["requested"] and time.monotonic() < deadline:
            channel = channels[index % len(channels)]
            result = subprocess.run(["iw", "dev", name, "set", "channel", str(channel)], text=True, capture_output=True, timeout=10)
            print(f"channel {channel}" if result.returncode == 0 else f"skip {channel}", flush=True)
            index += 1
            wait(min(deadline, time.monotonic() + dwell_ms / 1000))
            if len(channels) == 1:
                wait(deadline)  # Fixed channel: hold without re-tuning until the capture ends.
    finally:
        if base is not None:
            subprocess.run(["iw", "dev", name, "set", "channel", str(base)], text=True, capture_output=True, timeout=10)
            print(f"restored channel {base}", flush=True)


def interface_addresses(device):
    result = command(["ip", "-j", "-4", "address", "show", "dev", device])
    try:
        data = json.loads(result.stdout or "[]")
    except ValueError:
        fail("Could not read the interface addresses")
    return [ipaddress.ip_interface(f"{entry['local']}/{entry['prefixlen']}") for item in data for entry in item.get("addr_info", [])
            if entry.get("family") == "inet" and entry.get("local")]


def valid_pin_address(device, address_text):
    """A private IPv4 address on a network the interface is directly connected to."""
    try:
        address = ipaddress.IPv4Address(address_text)
    except ValueError:
        fail("Invalid IPv4 address")
    if not address.is_private or address.is_loopback or address.is_link_local or address.is_multicast or address.is_unspecified:
        fail("Only private IPv4 addresses on the local network can be pinned")
    own = interface_addresses(device)
    if address in {interface.ip for interface in own}:
        fail("This computer's own address cannot be pinned")
    for interface in own:
        network = interface.network
        if address in network and address not in {network.network_address, network.broadcast_address}:
            return str(address)
    fail("The address is not on a network directly connected to this interface")


def valid_mac(mac_text):
    mac = mac_text.strip().lower()
    if not MAC_PATTERN.fullmatch(mac) or int(mac[:2], 16) & 1 or mac == "00:00:00:00:00:00":
        fail("Invalid unicast MAC address")
    return mac


def pin(device, address_text, mac_text):
    """Send traffic for one device straight to its own MAC (a permanent neighbour entry).

    Used when a router answers ARP for addresses it does not own (proxy ARP).
    The entry is recorded and removed again by restore or unpin.
    """
    if os.geteuid() != 0:
        fail("Administrator privileges are required")
    if not valid_interface(device):
        fail("Invalid network interface")
    address = valid_pin_address(device, address_text)
    mac = valid_mac(mac_text)
    state = load_state()
    pins = [item for item in state.get("pins", []) if not (item.get("device") == device and item.get("address") == address)]
    if len(pins) >= MAX_PINS:
        fail(f"At most {MAX_PINS} devices can be pinned; restore the interface first")
    command(["ip", "neigh", "replace", address, "lladdr", mac, "dev", device, "nud", "permanent"])
    pins.append({"device": device, "address": address, "mac": mac})
    state["pins"] = pins
    save_state(state)
    print(f"Pinned {address} to {mac} on {device}")


def unpin(device, address_text):
    """Remove one entry that pin created; other neighbour entries are never touched."""
    if os.geteuid() != 0:
        fail("Administrator privileges are required")
    state = load_state()
    pins = state.get("pins", [])
    match = [item for item in pins if item.get("device") == device and item.get("address") == address_text]
    if not match:
        fail("That address was not pinned by this application")
    if valid_interface(device):
        subprocess.run(["ip", "neigh", "del", address_text, "dev", device], text=True, capture_output=True, timeout=10)
    state["pins"] = [item for item in pins if item not in match]
    save_state(state)
    print(f"Released {address_text} on {device}")


def apply(device, range_text, address_text):
    if os.geteuid() != 0:
        fail("Administrator privileges are required")
    if not valid_interface(device):
        fail("Invalid network interface")
    network = valid_network(range_text)
    address = ipaddress.ip_address(address_text)
    if address not in network or address in {network.network_address, network.broadcast_address}:
        fail("Temporary address is not usable in the selected range")
    state = load_state()
    restore_network_state(state)
    save_state(state)
    cidr = f"{address}/{network.prefixlen}"
    command(["ip", "link", "set", "dev", device, "up"])
    # IPv4 labels share Linux's 15-character interface-name limit. Appending
    # ':lemoa-scan' breaks predictable USB names such as enx3cab72d591a0 and
    # produces the misleading "Attribute failed policy validation" error.
    # The state file already retains the exact device and CIDR for cleanup.
    command(["ip", "address", "add", cidr, "dev", device])
    state = load_state()
    state.update({"device": device, "cidr": cidr})
    save_state(state)
    print(f"Added temporary address {cidr} to {device}")


def main():
    if len(sys.argv) < 2:
        fail("Usage: helper apply INTERFACE CIDR ADDRESS | pin INTERFACE ADDRESS MAC | unpin INTERFACE ADDRESS | "
             "monitor-start PHY | monitor-stop INTERFACE | monitor-tune INTERFACE DWELL_MS DURATION_S CHANNELS | restore")
    if sys.argv[1] == "restore" and len(sys.argv) == 2:
        restore()
    elif sys.argv[1] == "monitor-start" and len(sys.argv) == 3:
        start_monitor(sys.argv[2])
    elif sys.argv[1] == "monitor-stop" and len(sys.argv) == 3:
        stop_monitor(sys.argv[2])
    elif sys.argv[1] == "monitor-tune" and len(sys.argv) == 6:
        tune_monitor(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5])
    elif sys.argv[1] == "apply" and len(sys.argv) == 5:
        apply(sys.argv[2], sys.argv[3], sys.argv[4])
    elif sys.argv[1] == "pin" and len(sys.argv) == 5:
        pin(sys.argv[2], sys.argv[3], sys.argv[4])
    elif sys.argv[1] == "unpin" and len(sys.argv) == 4:
        unpin(sys.argv[2], sys.argv[3])
    else:
        fail("Invalid arguments")


if __name__ == "__main__":
    main()
