#!/bin/bash set -euo pipefail WIFI_IFACE="wlan0" PRIMARY_CONN="netplan-wlan0-eskimue.de" SECONDARY_CONN="4pi" FALLBACK_AP_CONN="CUNO-AP" CHECK_INTERVAL=20 get_active_connection() { nmcli -t -f GENERAL.CONNECTION device show "$WIFI_IFACE" 2>/dev/null | head -n 1 | cut -d: -f2- } activate_connection() { local connection_name="$1" nmcli --wait 15 connection up "$connection_name" ifname "$WIFI_IFACE" >/dev/null 2>&1 } ensure_best_connection() { local active_connection active_connection="$(get_active_connection)" if [[ "$active_connection" == "$PRIMARY_CONN" ]]; then return fi if activate_connection "$PRIMARY_CONN"; then return fi active_connection="$(get_active_connection)" if [[ "$active_connection" == "$SECONDARY_CONN" ]]; then return fi if activate_connection "$SECONDARY_CONN"; then return fi active_connection="$(get_active_connection)" if [[ "$active_connection" != "$FALLBACK_AP_CONN" ]]; then activate_connection "$FALLBACK_AP_CONN" || true fi } while true; do ensure_best_connection sleep "$CHECK_INTERVAL" done