#!/bin/bash
# Every-login network connectivity check. Split out of the old bos-welcome
# script, which conflated this with one-time onboarding (now breadhelp's
# job) — this half must keep running unconditionally on every login, before
# any GUI toolkit is worth spinning up, and must never be gated by a marker.
set -u

# Never run in the live/installer session — only on an installed system.
[[ "$(id -un)" == "liveuser" ]] && exit 0

# A fresh install usually boots with no connection (Wi-Fi isn't configured
# during install), and the first `bos-update`/pacman run then fails with
# confusing DNS/"could not resolve host" errors. If NetworkManager reports
# we're not fully online, open nmtui so the user can join a network before
# anything else. Best-effort: missing nmcli/nmtui/kitty, or the user quitting
# nmtui, must never block the rest of login.
command -v nmcli &>/dev/null || exit 0

conn="$(nmcli networking connectivity check 2>/dev/null)"
# NetworkManager may still be associating right at compositor start — give it
# a few short retries before concluding we're actually offline, so a machine
# with working Wi-Fi doesn't get a spurious nmtui popup.
tries=0
while [[ "$conn" != "full" && "$tries" -lt 3 ]]; do
    sleep 1
    conn="$(nmcli networking connectivity check 2>/dev/null)"
    tries=$((tries + 1))
done

if [[ "$conn" != "full" ]]; then
    notify-send -u normal "BOS" "No internet yet — opening network setup so updates work." 2>/dev/null || true
    if command -v nmtui &>/dev/null; then
        kitty --class bos-netsetup --title "Connect to a network" -- nmtui connect 2>/dev/null || true
    fi
fi
