#!/usr/bin/env python3
"""Detect USB serial LoRa-side devices for GAR-BOT."""

from __future__ import annotations

import glob
import os
import subprocess


def run(command: list[str]) -> str:
    try:
        return subprocess.check_output(command, text=True, stderr=subprocess.STDOUT)
    except Exception as exc:
        return f"{type(exc).__name__}: {exc}"


def main() -> int:
    print("USB serial links:")
    for path in sorted(glob.glob("/dev/serial/by-id/*")):
        target = os.path.realpath(path)
        print(f"  {path} -> {target}")
    for path in sorted(glob.glob("/dev/ttyUSB*") + glob.glob("/dev/ttyACM*")):
        print(f"  {path}")

    print("\nlsusb:")
    print(run(["lsusb"]))

    print("\nRecent USB kernel log:")
    print("\n".join(run(["dmesg", "-T"]).splitlines()[-80:]))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
