#!/bin/sh
# Clawdie operator USB live Wi-Fi bring-up.
# Many FreeBSD wireless drivers create an underlying device (e.g. iwm0)
# at attach time but leave it unusable until a wlan0 clone is created
# from it. This service detects the first wlan-capable device after the
# kernel has probed PCI/USB hardware, loads common driver kmods as a
# defensive fallback in case devd autoload missed them, and creates
# wlan0 so NetworkMgr and dhclient can see a usable interface on first
# boot without any operator action.
#
# Runs before netif so the freshly created wlan0 is brought up cleanly.

# PROVIDE: clawdie_live_wifi
# REQUIRE: FILESYSTEMS devfs
# BEFORE: netif
# KEYWORD: nojail

. /etc/rc.subr

name="clawdie_live_wifi"
rcvar="${name}_enable"
start_cmd="${name}_start"
stop_cmd=":"

clawdie_live_wifi_start() {
    # Belt-and-suspenders: most autoload on PCI/USB attach, but covering
    # the common chips by hand is cheap and avoids early-boot probe races.
    _drivers="if_iwm if_iwlwifi if_rtwn_usb if_urtwn if_run if_otus if_mt76"
    _drivers="${_drivers} iwm iwlwifi rtwn_usb urtwn run otus mt76"
    for _drv in ${_drivers}; do
        kldload "$_drv" 2>/dev/null || true
    done

    _dev=$(sysctl -n net.wlan.devices 2>/dev/null | awk '{print $1}')
    if [ -z "${_dev:-}" ]; then
        echo "${name}: no wlan-capable device detected"
        return 0
    fi

    if ifconfig -l | tr ' ' '\n' | grep -q '^wlan'; then
        return 0
    fi

    if ifconfig wlan0 create wlandev "${_dev}" 2>/dev/null; then
        echo "${name}: created wlan0 on ${_dev}"
    else
        echo "${name}: failed to create wlan0 on ${_dev}" >&2
        return 1
    fi
}

load_rc_config "$name"
: "${clawdie_live_wifi_enable:=YES}"
run_rc_command "$1"
