Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # ============================================================================
- # NIXOS INTELLIGENT WIFI AUTO-SWITCHING MODULE
- # ============================================================================
- #
- # 📊 VISUAL FLOWCHART: See wifi-auto-flowchart.md for complete system diagram
- #
- # This module creates a complete WiFi management system that:
- #
- # 1. MONITORS WiFi connections every 30 seconds via systemd service
- # 2. DETECTS when managed networks (with agenix secrets) become available
- # 3. NOTIFIES user via desktop notifications when switches are recommended
- # 4. SWITCHES networks immediately when user approves via CLI commands
- # 5. REMEMBERS user decisions to avoid repeated prompts
- #
- # COMPONENTS:
- # - wifi-auto-monitor.service: Background daemon monitoring WiFi status
- # - wifi-notification-handler: User session service showing notifications
- # - wifi-switch-approve: CLI command for immediate network switching
- # - wifi-switch-decline: CLI command to decline network switches
- #
- # HOW TO USE:
- # 1. Store WiFi passwords: nix develop .#secrets -> encrypt-wifi <name> <password>
- # 2. Enable module: networking.wifi-auto.enable = true;
- # 3. Rebuild: sudo nixos-rebuild switch --flake .
- # 4. When notification appears: run 'wifi-switch-approve' or 'wifi-switch-decline'
- #
- # EXAMPLE WORKFLOW:
- # - Currently on AndroidAP (unmanaged hotspot)
- # - VM2530351 network becomes available (managed with agenix secret)
- # - Notification appears: "Switch to VM2530351?"
- # - User runs: wifi-switch-approve
- # - System immediately switches to VM2530351
- # ============================================================================
- { config, lib, pkgs, ... }:
- with lib;
- let
- # ============================================================================
- # STEP 1: DISCOVER WIFI SECRETS
- # ============================================================================
- # Find all WiFi secrets in the agenix configuration
- # Looks for any secret names starting with "wifi-"
- # Example: "wifi-MyVPN", "wifi-CoffeeShop" -> both found automatically
- #
- # MACHINE-SPECIFIC: The USB WiFi dongle (meshchat-usb-dongle.nix) manages its
- # own NetworkManager connection with special routing (never-default, route-metric=700).
- # We must exclude it here, otherwise wifi-auto generates a second "auto-" connection
- # for the same SSID WITHOUT those routing protections, and NetworkManager may pick
- # that one instead — stealing the default route from wlp61s0 and killing internet.
- excludedSecrets = [
- "wifi-Meshchat-192-168-4-1" # managed by modules/parts/meshchat-usb-dongle.nix
- ];
- wifiSecrets = filterAttrs (name: _: hasPrefix "wifi-" name && !(builtins.elem name excludedSecrets)) config.age.secrets;
- # Convert agenix secret names to actual WiFi network names
- # Strips the "wifi-" prefix to get the real network SSID
- # Example: "wifi-VM2530351" -> "VM2530351"
- secretToNetworkName = secretName:
- removePrefix "wifi-" secretName;
- # ============================================================================
- # STEP 2: VIP NETWORK DETECTION
- # ============================================================================
- # Check if a network is a VIP network (should not be auto-switched from)
- # VIP networks include:
- # - Networks with "vpn" or "VPN" in the name
- # - Networks manually preferred in GNOME (detected at runtime)
- isVipNetwork = networkName:
- (builtins.match ".*[Vv][Pp][Nn].*" networkName) != null;
- # ============================================================================
- # STEP 3: GENERATE NETWORKMANAGER CONNECTION FILES
- # ============================================================================
- # Create NetworkManager connection files for each discovered WiFi secret
- # These .nmconnection files tell NetworkManager which networks it can connect to
- # and where to find their passwords
- generateWifiConnections = mapAttrsToList (secretName: secret:
- let
- # Extract the actual network name (SSID)
- networkName = secretToNetworkName secretName;
- # Create a unique connection identifier
- connectionName = "auto-${networkName}";
- # Determine if this is a VIP network
- isVip = isVipNetwork networkName;
- in {
- # File location: /etc/NetworkManager/system-connections/auto-NetworkName.nmconnection
- name = "NetworkManager/system-connections/${connectionName}.nmconnection";
- # File properties and content
- value = {
- mode = "0600"; # Secure permissions - only root can read/write
- user = "root"; # NetworkManager requires root ownership
- group = "root";
- # NetworkManager connection file in INI format
- # This is the standard format NetworkManager expects
- text = ''
- [connection]
- id=${connectionName}
- type=wifi
- interface-name=wlp61s0
- autoconnect=true
- autoconnect-priority=${if isVip then "100" else "0"}
- [wifi]
- mode=infrastructure
- ssid=${networkName}
- [wifi-security]
- key-mgmt=wpa-psk
- [ipv4]
- method=auto
- [ipv6]
- addr-gen-mode=default
- method=auto
- [proxy]
- '';
- };
- }
- ) wifiSecrets;
- in {
- # ============================================================================
- # MODULE OPTIONS
- # ============================================================================
- options.networking.wifi-auto = {
- enable = mkEnableOption "automatic WiFi connection using agenix secrets";
- # Monitoring intervals for the intelligent network selection
- fastScanInterval = mkOption {
- type = types.int;
- default = 30;
- description = "Seconds between fast scans for new networks and connection restoration";
- };
- stabilityScanInterval = mkOption {
- type = types.int;
- default = 300; # 5 minutes
- description = "Seconds between stability tests and potential network switching";
- };
- # Quality thresholds for network selection
- stabilityThreshold = mkOption {
- type = types.float;
- default = 0.95; # 95% success rate
- description = "Minimum stability score (0.0-1.0) required for normal network switching";
- };
- emergencyThreshold = mkOption {
- type = types.float;
- default = 0.50; # 50% success rate
- description = "Emergency threshold below which VIP networks can be auto-switched";
- };
- minSpeedMbps = mkOption {
- type = types.int;
- default = 1;
- description = "Minimum speed in Mbps below which a connection is considered emergency-level bad";
- };
- };
- # ============================================================================
- # MODULE CONFIGURATION
- # ============================================================================
- config = mkIf config.networking.wifi-auto.enable {
- # Ensure NetworkManager is enabled
- networking.networkmanager.enable = true;
- # Install required packages for network testing and monitoring
- environment.systemPackages = with pkgs; [
- speedtest-cli # Ookla speed testing
- iperf3 # Network bandwidth testing
- iw # WiFi signal strength and scanning
- networkmanager # nmcli for connection management
- libnotify # Desktop notifications
- zenity # GNOME dialog boxes for user authorization
- bc # Calculator for stability score math
- ];
- # NetworkManager connections are now created dynamically via nmcli service
- # WiFi connections are now managed manually via fix-wifi-connections.sh script
- # This avoids systemd dependency issues during system rebuild
- # ============================================================================
- # INTELLIGENT WIFI MONITORING SERVICE WITH ZENITY POPUPS
- # ============================================================================
- # Main WiFi monitoring service with interactive user authorization
- systemd.services.wifi-auto-monitor = {
- description = "Intelligent WiFi Auto-Connection Monitor with User Authorization";
- documentation = [ "Custom NixOS WiFi management with stability-based selection" ];
- wantedBy = [ "multi-user.target" ];
- after = [ "NetworkManager.service" "network.target" "graphical-session.target" ];
- wants = [ "NetworkManager.service" ];
- # Service configuration for robust operation
- serviceConfig = {
- Type = "simple";
- Restart = "always";
- RestartSec = "10";
- User = "root"; # Required for NetworkManager control
- Group = "root";
- # Security hardening (Tier A/B applied via basicHardening module)
- NoNewPrivileges = true;
- ProtectSystem = "strict";
- ProtectHome = true;
- ReadWritePaths = [
- "/etc/NetworkManager/system-connections"
- "/var/lib/wifi-auto-monitor"
- "/tmp"
- ];
- # Allow access to display for zenity popups (X11 and Wayland compatible)
- Environment = [
- "DISPLAY=:0"
- "WAYLAND_DISPLAY=wayland-0"
- "XDG_RUNTIME_DIR=/run/user/1000"
- "XDG_SESSION_TYPE=wayland"
- "XDG_CURRENT_DESKTOP=GNOME"
- "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus,guid=ae228eab7c9054b61adddc9768aba0e3"
- ];
- # ======================================================================
- # MAIN WIFI AUTO-SWITCHING SERVICE SCRIPT
- # ======================================================================
- # This is the core daemon that:
- # 1. Monitors current WiFi connection every 30 seconds
- # 2. Detects when managed networks (with agenix secrets) become available
- # 3. Creates authorization requests for user approval via notifications
- # 4. Switches networks when approved via CLI commands
- # 5. Remembers user decisions to avoid repeated prompts
- # ======================================================================
- ExecStart = pkgs.writeShellScript "wifi-auto-monitor" ''
- #!/bin/bash
- # ========================================================================
- # WIFI AUTO-MONITOR SERVICE WITH USER AUTHORIZATION
- # ========================================================================
- #
- # How it works:
- # - Runs every 30 seconds to check network status
- # - When on unmanaged network (like AndroidAP), offers to switch to managed (VM2530351)
- # - Creates request files in /tmp/ that CLI commands can respond to
- # - User approves with: wifi-switch-approve (switches immediately)
- # - User declines with: wifi-switch-decline
- # - Notifications appear via desktop notification system
- set -euo pipefail
- # Add required tools to PATH
- export PATH="${pkgs.networkmanager}/bin:${pkgs.zenity}/bin:${pkgs.speedtest-cli}/bin:${pkgs.iperf3}/bin:${pkgs.iw}/bin:${pkgs.bc}/bin:${pkgs.coreutils}/bin:${pkgs.util-linux}/bin:${pkgs.wget}/bin:${pkgs.gawk}/bin:${pkgs.gnugrep}/bin:${pkgs.gnused}/bin:$PATH"
- # Configuration from NixOS module options
- FAST_INTERVAL=${toString config.networking.wifi-auto.fastScanInterval}
- STABILITY_INTERVAL=${toString config.networking.wifi-auto.stabilityScanInterval}
- STABILITY_THRESHOLD=${toString config.networking.wifi-auto.stabilityThreshold}
- EMERGENCY_THRESHOLD=${toString config.networking.wifi-auto.emergencyThreshold}
- MIN_SPEED_MBPS=${toString config.networking.wifi-auto.minSpeedMbps}
- # State directory for persistent data
- STATE_DIR="/var/lib/wifi-auto-monitor"
- mkdir -p "$STATE_DIR"
- # State files for decision memory
- USER_DECISIONS_FILE="$STATE_DIR/user_decisions.txt"
- NETWORK_HISTORY_FILE="$STATE_DIR/network_history.txt"
- # Logging function with timestamps
- log() {
- echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" >&2
- }
- # ======================================================================
- # STARTUP CLEANUP: Remove stale auto-* connection files
- # ======================================================================
- # The monitor script creates real files in /etc/NetworkManager/system-connections/
- # which persist across rebuilds and ignore declarative config changes.
- # On startup, remove them so the "restore missing connections" block below
- # recreates them with the current settings (e.g. interface-name=wlp61s0).
- log "Cleaning up stale auto-* connection files"
- shopt -s nullglob
- for f in /etc/NetworkManager/system-connections/auto-*.nmconnection; do
- rm -f "$f" && log "Removed stale: $f"
- done
- shopt -u nullglob
- nmcli connection reload 2>/dev/null || true
- log "Connection reload complete"
- # ======================================================================
- # INTERACTIVE USER AUTHORIZATION WITH ZENITY
- # ======================================================================
- # Ask user for authorization using file-based communication with user session
- ask_user_authorization() {
- local from_network="$1"
- local to_network="$2"
- local reason="$3"
- # Check if we've recently shown a notification for this network pair
- # Snooze duration matches the scan interval to prevent duplicate popups
- local snooze_duration=$((FAST_INTERVAL + 60)) # scan interval + 1 minute buffer
- local snooze_file="/tmp/wifi-notification-snooze-$from_network-to-$to_network"
- local current_time=$(date +%s)
- if [ -f "$snooze_file" ]; then
- local last_notification_time=$(cat "$snooze_file" 2>/dev/null || echo 0)
- local time_diff=$((current_time - last_notification_time))
- if [ $time_diff -lt $snooze_duration ]; then
- log "Skipping notification (snooze active): $from_network to $to_network (shown ''${time_diff}s ago, snooze ''${snooze_duration}s)"
- return 1
- fi
- fi
- # Record this notification time
- echo "$current_time" > "$snooze_file"
- log "Requesting user authorization to switch from $from_network to $to_network ($reason)"
- # Create request file for user session to pick up
- local request_file="/tmp/wifi-switch-request-$$"
- local response_file="/tmp/wifi-switch-response-$$"
- # Create request with all details - encode newlines to avoid parsing issues
- log "DEBUG: Original reason: $reason"
- reason_encoded=$(echo "$reason" | tr '\n' '|' | sed 's/|$//' | sed 's/|/|NEWLINE|/g')
- log "DEBUG: Encoded reason: $reason_encoded"
- {
- echo "FROM=$from_network"
- echo "TO=$to_network"
- printf 'REASON=%q\n' "$reason_encoded"
- echo "TIMESTAMP=$(date +%s)"
- echo "RESPONSE_FILE=$response_file"
- } > "$request_file"
- # Make request readable by user
- chmod 644 "$request_file"
- chown adingbatponder:users "$request_file" 2>/dev/null || true
- log "Created authorization request file: $request_file"
- # Wait for user response (up to 30 seconds)
- local wait_count=0
- while [ ! -f "$response_file" ] && [ $wait_count -lt 30 ]; do
- sleep 1
- wait_count=$((wait_count + 1))
- done
- # Check response
- if [ -f "$response_file" ]; then
- local response=$(cat "$response_file" 2>/dev/null)
- rm -f "$request_file" "$response_file" 2>/dev/null || true
- if [ "$response" = "APPROVE" ]; then
- log "User APPROVED switch from $from_network to $to_network"
- echo "APPROVE:$from_network:$to_network:$(date +%s)" >> "$USER_DECISIONS_FILE"
- return 0 # approved
- else
- log "User DECLINED switch from $from_network to $to_network"
- echo "DECLINE:$from_network:$to_network:$(date +%s)" >> "$USER_DECISIONS_FILE"
- return 1 # declined
- fi
- else
- log "No user response received (timeout)"
- rm -f "$request_file" 2>/dev/null || true
- echo "TIMEOUT:$from_network:$to_network:$(date +%s)" >> "$USER_DECISIONS_FILE"
- return 1 # timeout
- fi
- }
- # Clean up decline decisions for networks that no longer exist
- cleanup_stale_decisions() {
- if [ -f "$USER_DECISIONS_FILE" ]; then
- log "Cleaning up stale network decisions"
- # Get list of currently available networks
- local available_managed=$(get_available_networks)
- local all_available_networks=$(nmcli -t -f SSID dev wifi list 2>/dev/null | sort -u)
- # Create temporary file for valid decisions
- local temp_file=$(mktemp)
- # Process each decision line
- while IFS=':' read -r decision from to timestamp; do
- local keep_decision=true
- if [ "$decision" = "DECLINE" ]; then
- # Check if source network still exists (in any form)
- if ! echo "$all_available_networks" | grep -q "^$from$"; then
- log "Source network '$from' no longer available - removing decision"
- keep_decision=false
- # Check if target managed network still exists
- elif ! echo "$available_managed" | grep -q "^$to$"; then
- log "Target managed network '$to' no longer available - removing decision"
- keep_decision=false
- fi
- fi
- # Keep valid decisions
- if [ "$keep_decision" = true ] && [ -n "$decision" ]; then
- echo "$decision:$from:$to:$timestamp" >> "$temp_file"
- fi
- done < "$USER_DECISIONS_FILE"
- # Replace old file with cleaned version
- mv "$temp_file" "$USER_DECISIONS_FILE"
- log "Stale decision cleanup completed"
- fi
- }
- # Check if user has previously declined switching from source to target network
- user_declined_switch() {
- local from_network="$1"
- local to_network="$2"
- if [ -f "$USER_DECISIONS_FILE" ]; then
- # Check for recent decline (within last 24 hours)
- local day_ago=$(($(date +%s) - 86400))
- while IFS=':' read -r decision from to timestamp; do
- if [ "$decision" = "DECLINE" ] && [ "$from" = "$from_network" ] && [ "$to" = "$to_network" ]; then
- if [ "$timestamp" -gt "$day_ago" ]; then
- return 0 # recently declined
- fi
- fi
- done < "$USER_DECISIONS_FILE"
- fi
- return 1 # no recent decline
- }
- # ======================================================================
- # BASIC MONITORING FUNCTIONS (SIMPLIFIED FOR EXAMPLE)
- # ======================================================================
- # Get currently connected WiFi network (any network, managed or unmanaged)
- get_current_network() {
- nmcli -t connection show --active | grep "802-11-wireless" | head -1 | cut -d: -f1 || echo ""
- }
- # Get the SSID of the currently connected WiFi network
- get_current_ssid() {
- # Try multiple methods to get the current SSID
- local ssid=""
- # Method 1: Get SSID directly from WiFi device (most reliable)
- ssid=$(nmcli -t -f WIFI.SSID device show wlp61s0 2>/dev/null | cut -d: -f2)
- if [ -n "$ssid" ]; then
- echo "$ssid"
- return
- fi
- # Method 2: Get SSID from active connection details
- local connection_name=$(nmcli -t connection show --active | grep "802-11-wireless" | head -1 | cut -d: -f1)
- if [ -n "$connection_name" ]; then
- ssid=$(nmcli -t -f 802-11-wireless.ssid connection show "$connection_name" 2>/dev/null | cut -d: -f2)
- if [ -n "$ssid" ]; then
- echo "$ssid"
- return
- fi
- fi
- # Method 3: Get from device status as fallback
- ssid=$(nmcli -t -f GENERAL.CONNECTION device show wlp61s0 2>/dev/null | head -1 | cut -d: -f2)
- if [ -n "$ssid" ] && [[ "$ssid" == auto-* ]]; then
- # If we got a connection name like "auto-Eva", extract the SSID part
- echo "''${ssid#auto-}"
- return
- fi
- # Method 4: Ultimate fallback
- ssid=$(nmcli -t -f WIFI.SSID device show 2>/dev/null | head -1 | cut -d: -f2)
- echo "$ssid"
- }
- # Get currently connected MANAGED WiFi network (any network with agenix secrets)
- get_current_managed_network() {
- local current_ssid=$(get_current_ssid)
- if [ -n "$current_ssid" ] && [ -f "/run/agenix/wifi-$current_ssid" ]; then
- echo "$current_ssid"
- else
- echo ""
- fi
- }
- # Check if current connection is managed by our system
- is_current_connection_managed() {
- local current_ssid=$(get_current_ssid)
- [ -n "$current_ssid" ] && [ -f "/run/agenix/wifi-$current_ssid" ]
- }
- # Check if a network name indicates it's a VIP network
- is_vip_network() {
- local network_name="$1"
- # Check for VPN in name (case insensitive)
- [[ "$network_name" =~ [Vv][Pp][Nn] ]]
- }
- # Get list of available networks with our stored secrets (works with existing connections)
- get_available_networks() {
- nmcli -t -f SSID dev wifi list 2>/dev/null | while read -r ssid; do
- if [ -n "$ssid" ] && [ -f "/run/agenix/wifi-$ssid" ]; then
- echo "$ssid"
- fi
- done | sort -u
- }
- # Convert SSID to connection name (maps "Eva" -> "auto-Eva")
- ssid_to_connection() {
- local ssid="$1"
- echo "auto-$ssid"
- }
- # Get network signal strength and rate for comparison
- get_network_quality() {
- local network_name="$1"
- local signal_info rate_info
- # Always get quality from WiFi scan (more reliable than device properties)
- signal_info=$(nmcli -t -f SSID,SIGNAL dev wifi list | grep "^$network_name:" | head -1 | cut -d: -f2)
- rate_info=$(nmcli -t -f SSID,RATE dev wifi list | grep "^$network_name:" | head -1 | cut -d: -f2)
- if [ -n "$signal_info" ] && [ -n "$rate_info" ]; then
- echo "$signal_info:$rate_info" # Returns "signal:rate" like "100:270 Mbit/s"
- else
- echo "unknown:unknown"
- fi
- }
- # Restore any missing connection files from our secrets
- restore_missing_connections() {
- local restored_count=0
- ${concatStringsSep "\n" (mapAttrsToList (secretName: secret:
- let
- networkName = secretToNetworkName secretName;
- connectionName = "auto-${networkName}";
- connectionPath = "/etc/NetworkManager/system-connections/${connectionName}.nmconnection";
- isVip = isVipNetwork networkName;
- in ''
- if [ ! -f "${connectionPath}" ]; then
- log "Restoring missing connection: ${connectionName}"
- cat > "${connectionPath}" << 'EOF'
- [connection]
- id=${connectionName}
- type=wifi
- interface-name=wlp61s0
- autoconnect=true
- autoconnect-priority=${if isVip then "100" else "0"}
- [wifi]
- ssid=${networkName}
- [wifi-security]
- key-mgmt=wpa-psk
- psk-file=${secret.path}
- [ipv4]
- method=auto
- [ipv6]
- method=auto
- EOF
- chmod 0600 "${connectionPath}"
- chown root:root "${connectionPath}"
- nmcli connection reload >/dev/null 2>&1
- restored_count=$((restored_count + 1))
- fi
- ''
- ) wifiSecrets)}
- if [ $restored_count -gt 0 ]; then
- log "Restored $restored_count missing connection(s)"
- fi
- }
- # ======================================================================
- # MAIN MONITORING LOOP
- # ======================================================================
- fast_loop_counter=0
- # Calculate stability loop interval (minimum 1 to avoid division by zero)
- stability_loop_interval=$((STABILITY_INTERVAL / FAST_INTERVAL))
- [ $stability_loop_interval -lt 1 ] && stability_loop_interval=1
- log "WiFi Auto-Monitor started with zenity user authorization"
- log "Fast loop: ''${FAST_INTERVAL}s, Stability loop: ''${STABILITY_INTERVAL}s"
- log "Interactive popups enabled for network switching decisions"
- while true; do
- # Fast loop: Always restore missing connections and cleanup stale decisions
- restore_missing_connections
- cleanup_stale_decisions
- # Get connection status
- current_connection=$(get_current_network)
- current_ssid=$(get_current_ssid)
- current_managed_network=$(get_current_managed_network)
- # Debug logging
- log "DEBUG: current_connection='$current_connection', current_ssid='$current_ssid', current_managed='$current_managed_network'"
- if [ -n "$current_connection" ]; then
- if is_current_connection_managed; then
- log "Connected to MANAGED network: $current_managed_network $(is_vip_network "$current_managed_network" && echo "[VIP]" || echo "[NORMAL]")"
- # Clear any old decline decisions TO this network - manual connection overrides previous declines
- # If user manually connected to a network they previously declined, their preferences have changed
- if [ -f "$USER_DECISIONS_FILE" ]; then
- # Remove any DECLINE entries where the target was this current network
- sed -i "/DECLINE:.*:$current_managed_network:/d" "$USER_DECISIONS_FILE" 2>/dev/null || true
- log "Cleared any previous decline decisions for manually connected network: $current_managed_network"
- fi
- else
- log "Connected to UNMANAGED network: $current_ssid"
- # Clear any old decline decisions FROM managed networks TO this unmanaged network
- # If user manually connected to an unmanaged network, respect their choice
- if [ -f "$USER_DECISIONS_FILE" ]; then
- # Remove any DECLINE entries where this unmanaged network was the source
- sed -i "/DECLINE:$current_ssid:/d" "$USER_DECISIONS_FILE" 2>/dev/null || true
- log "Cleared previous decline decisions from manually connected unmanaged network: $current_ssid"
- fi
- # Check if we should offer to switch to a managed network
- available_networks=$(get_available_networks)
- if [ -n "$available_networks" ]; then
- best_managed_network=$(echo "$available_networks" | head -1)
- log "Available managed network found: $best_managed_network"
- # ALWAYS ask user permission when switching from unmanaged to managed
- # Never assume managed networks are automatically better
- if ! user_declined_switch "$current_ssid" "$best_managed_network"; then
- # Get quality information for both networks
- current_quality=$(get_network_quality "$current_ssid")
- managed_quality=$(get_network_quality "$best_managed_network")
- current_signal=$(echo "$current_quality" | cut -d: -f1)
- current_rate=$(echo "$current_quality" | cut -d: -f2)
- managed_signal=$(echo "$managed_quality" | cut -d: -f1)
- managed_rate=$(echo "$managed_quality" | cut -d: -f2)
- # Ensure we have signal values, fallback to generic text if empty
- [ -z "$current_signal" ] && current_signal="unknown"
- [ -z "$managed_signal" ] && managed_signal="unknown"
- [ -z "$current_rate" ] && current_rate="unknown"
- [ -z "$managed_rate" ] && managed_rate="unknown"
- # Create beautiful multi-line reason with % symbol and recommendation
- switch_reason="Current ($current_ssid): $current_signal%, $current_rate
- Managed ($best_managed_network): $managed_signal%, $managed_rate
- Recommendation: Switch for better performance"
- if ask_user_authorization "$current_ssid" "$best_managed_network" "$switch_reason"; then
- log "User approved switch from unmanaged to managed network"
- local connection_name=$(ssid_to_connection "$best_managed_network")
- if nmcli connection up "$connection_name" >/dev/null 2>&1; then
- log "Successfully switched to managed network: $best_managed_network"
- # Send success notification to user session
- local success_notification="/tmp/wifi-switch-success-$$"
- {
- echo "SWITCHED_FROM=$current_ssid"
- echo "SWITCHED_TO=$best_managed_network"
- echo "MESSAGE=Successfully switched WiFi networks"
- echo "TIMESTAMP=$(date +%s)"
- } > "$success_notification"
- chmod 644 "$success_notification"
- chown adingbatponder:users "$success_notification" 2>/dev/null || true
- else
- log "Failed to switch to managed network: $best_managed_network"
- fi
- else
- log "User declined switch from unmanaged ($current_ssid) to managed ($best_managed_network)"
- fi
- else
- log "User previously declined switch from $current_ssid to $best_managed_network - not asking again"
- fi
- else
- log "No managed networks currently available"
- fi
- fi
- else
- log "No WiFi connection at all"
- # No connection - try to connect to best available managed network
- available_networks=$(get_available_networks)
- if [ -n "$available_networks" ]; then
- best_managed_network=$(echo "$available_networks" | head -1)
- log "Connecting to best available managed network: $best_managed_network"
- local connection_name=$(ssid_to_connection "$best_managed_network")
- if nmcli connection up "$connection_name" >/dev/null 2>&1; then
- log "Successfully connected to managed network: $best_managed_network"
- else
- log "Failed to connect to managed network: $best_managed_network"
- fi
- else
- log "No managed networks available"
- fi
- fi
- # Stability loop: Only for managed networks
- if [ $((fast_loop_counter % stability_loop_interval)) -eq 0 ] && [ -n "$current_managed_network" ]; then
- log "Stability check cycle for managed network: $current_managed_network"
- # Example: If we find multiple managed networks, demonstrate authorization popup
- available_networks=$(get_available_networks)
- network_count=$(echo "$available_networks" | wc -l)
- if [ "$network_count" -gt 1 ]; then
- # Find an alternative managed network
- alternative_network=$(echo "$available_networks" | grep -v "^$current_managed_network$" | head -1)
- if [ -n "$alternative_network" ] && is_vip_network "$current_managed_network"; then
- # Only prompt occasionally to avoid spam (every 4th stability cycle)
- if [ $((fast_loop_counter / stability_loop_interval % 4)) -eq 0 ]; then
- if ! user_declined_switch "$current_managed_network" "$alternative_network"; then
- if ask_user_authorization "$current_managed_network" "$alternative_network" "Alternative managed network available"; then
- log "Switching to user-approved managed network: $alternative_network"
- local connection_name=$(ssid_to_connection "$alternative_network")
- nmcli connection up "$connection_name" >/dev/null 2>&1 || log "Switch failed"
- fi
- fi
- fi
- fi
- fi
- fi
- fast_loop_counter=$((fast_loop_counter + 1))
- sleep "$FAST_INTERVAL"
- done
- '';
- };
- };
- # Create state directory for the monitor service
- systemd.tmpfiles.rules = [
- "d /var/lib/wifi-auto-monitor 0755 root root -"
- ];
- # ============================================================================
- # USER SESSION POPUP HANDLER (runs in user GNOME session)
- # ============================================================================
- # Add CLI response commands (notification handler is now a systemd user service)
- users.users.adingbatponder.packages = with pkgs; [
- # ======================================================================
- # IMMEDIATE WIFI SWITCH APPROVAL COMMAND: wifi-switch-approve
- # ======================================================================
- # This command switches to the best available managed network IMMEDIATELY
- # No timing dependencies - works on-demand when user wants to switch
- # Checks for agenix secrets to determine which networks are available
- # ======================================================================
- (writeShellScriptBin "wifi-switch-approve" ''
- #!/usr/bin/env bash
- # Switch to the currently recommended network from the active request
- # This script needs to access agenix secrets, so run with elevated privileges if needed
- if [ "$EUID" -ne 0 ] && [ -z "$SUDO_USER" ]; then
- echo "🔄 Requesting elevated privileges to access WiFi secrets..."
- exec sudo "$0" "$@"
- fi
- echo "🔄 Approving WiFi switch..."
- # Get the most recent recommendation from debug logs (most reliable method)
- target_network=$(tail -1 /tmp/notification-debug.log 2>/dev/null | grep "TO=" | sed 's/.*TO=\([^,]*\).*/\1/')
- if [ -z "$target_network" ]; then
- echo "❌ No recent WiFi recommendation found"
- echo " Make sure you've seen a WiFi switch popup recently"
- exit 1
- fi
- echo "📡 Approving switch to: $target_network"
- # Try to find active request file to send proper approval signal
- request_file=$(ls /tmp/wifi-switch-request-* 2>/dev/null | head -1)
- if [ -f "$request_file" ]; then
- source "$request_file"
- # Signal approval to monitoring system
- if [ -n "$RESPONSE_FILE" ]; then
- echo "APPROVE" > "$RESPONSE_FILE"
- fi
- fi
- echo "📡 Switching to network: $target_network"
- # Use proper connection name format (auto-NetworkName)
- connection_name="auto-$target_network"
- if ${networkmanager}/bin/nmcli connection up "$connection_name" >/dev/null 2>&1; then
- echo "✅ Successfully switched to $target_network"
- ${libnotify}/bin/notify-send "WiFi Switch Approved" "Successfully switched to $target_network"
- else
- echo "❌ Failed to switch to $target_network (connection: $connection_name)"
- ${libnotify}/bin/notify-send "WiFi Switch Failed" "Could not switch to $target_network"
- exit 1
- fi
- '')
- # ======================================================================
- # WIFI SWITCH DECLINE COMMAND: wifi-switch-decline
- # ======================================================================
- # This command declines the current WiFi switch request and stays on current network
- # ======================================================================
- (writeShellScriptBin "wifi-switch-decline" ''
- #!/usr/bin/env bash
- # Decline pending WiFi network switch
- echo "⏰ Will decline the NEXT WiFi switch request automatically..."
- # Function to check and decline
- check_and_decline() {
- local request_file=$(ls /tmp/wifi-switch-request-* 2>/dev/null | head -1)
- if [ -n "$request_file" ]; then
- local response_file=$(grep "RESPONSE_FILE=" "$request_file" 2>/dev/null | cut -d= -f2)
- if [ -n "$response_file" ]; then
- echo "DECLINE" > "$response_file"
- echo "❌ DECLINED WiFi switch - staying on current network"
- ${libnotify}/bin/notify-send "WiFi Switch" "Staying on current network"
- return 0
- fi
- fi
- return 1
- }
- # Check if there's already a request
- if check_and_decline; then
- exit 0
- fi
- # Otherwise wait for next request (up to 60 seconds)
- echo "🔍 Waiting for next WiFi switch request (up to 60s)..."
- for i in {1..60}; do
- if check_and_decline; then
- exit 0
- fi
- sleep 1
- done
- echo "❌ No request appeared within 60 seconds"
- '')
- ];
- # GNOME autostart file is created above in environment.etc merge
- # ========================================================================
- # SYSTEMD USER SERVICE: WiFi Notification Handler
- # ========================================================================
- #
- # WHAT THIS DOES:
- # Creates a systemd user service that runs in the user's session (not as root)
- # This service monitors for WiFi switch requests and shows desktop notifications
- #
- # WHY SYSTEMD USER SERVICE INSTEAD OF DESKTOP AUTOSTART:
- # 1. More reliable - systemd manages the process lifecycle
- # 2. Auto-restart if crashes - "Restart = always" ensures it never stays dead
- # 3. Proper session integration - runs with user permissions and desktop access
- # 4. Better logging - can use "journalctl --user" to debug issues
- # 5. Water-tight operation - no manual intervention needed after rebuilds
- #
- # HOW IT WORKS:
- # - Starts automatically when user logs into desktop ("wantedBy graphical-session.target")
- # - Runs continuously, checking for request files every 1 second
- # - Shows popup notifications when WiFi switches are recommended
- # - Cleans up request/success files after processing them
- # ========================================================================
- systemd.user.services.wifi-notification-handler = {
- description = "WiFi Auto-Switch Notification Handler";
- # WHEN TO START: Start automatically when user logs into desktop session
- # "graphical-session.target" = when desktop environment (GNOME/KDE/etc) starts
- wantedBy = [ "graphical-session.target" ];
- # DEPENDENCIES: Wait for desktop session to be fully ready before starting
- # This ensures DISPLAY, notification system, etc. are available
- after = [ "graphical-session.target" ];
- serviceConfig = {
- # SERVICE TYPE: "simple" = run the command and keep it running
- # (as opposed to "oneshot" which runs once and exits)
- Type = "simple";
- # AUTO-RESTART: If the service crashes or exits, restart it automatically
- # This makes the system "water-tight" - it always recovers from failures
- Restart = "always";
- # RESTART DELAY: Wait 5 seconds before restarting (prevents rapid restart loops)
- RestartSec = "5";
- # THE ACTUAL PROGRAM TO RUN:
- # pkgs.writeShellScript creates a shell script in the Nix store that systemd executes
- ExecStart = "${pkgs.writeShellScript "wifi-notification-handler" ''
- #!/usr/bin/env bash
- # ================================================================
- # MAIN NOTIFICATION HANDLER LOOP
- # ================================================================
- # This script runs continuously, checking for WiFi switch requests
- # from the root wifi-auto-monitor service every 1 second
- # ================================================================
- # Rate limiter: minimum 30 minutes between notifications (matches scan interval)
- NOTIFICATION_COOLDOWN=1800
- LAST_NOTIFICATION_FILE="/tmp/wifi-notification-last-shown"
- can_show_notification() {
- local current_time=$(date +%s)
- if [ -f "$LAST_NOTIFICATION_FILE" ]; then
- local last_time=$(cat "$LAST_NOTIFICATION_FILE" 2>/dev/null || echo 0)
- local elapsed=$((current_time - last_time))
- if [ $elapsed -lt $NOTIFICATION_COOLDOWN ]; then
- echo "Rate limited: ''${elapsed}s since last notification (cooldown: ''${NOTIFICATION_COOLDOWN}s)" >> /tmp/notification-debug.log
- return 1
- fi
- fi
- echo "$current_time" > "$LAST_NOTIFICATION_FILE"
- return 0
- }
- while true; do
- # ============================================================
- # STEP 1: Check for WiFi switch requests
- # ============================================================
- # The root service creates files like "/tmp/wifi-switch-request-12345"
- # containing FROM=network, TO=network, REASON=signal_info
- for request_file in /tmp/wifi-switch-request-*; do
- if [ -f "$request_file" ]; then
- # PARSE the request file to extract network names and reason
- # "source" loads the variables FROM, TO, REASON from the file
- source "$request_file"
- # CLEAN UP the reason text for display:
- # The root service encodes newlines as "|NEWLINE|" to avoid file parsing issues
- # We convert them to bullet points (•) for a clean single-line notification
- REASON_FORMATTED=$(printf '%s\n' "$REASON" | sed 's/|NEWLINE|/ • /g')
- # DEBUG logging (helps troubleshoot if notifications don't appear)
- echo "DEBUG: FROM=$FROM, TO=$TO, REASON=$REASON_FORMATTED" >> /tmp/notification-debug.log
- # Rate limit check - only show one notification per cooldown period
- if can_show_notification; then
- # CREATE the popup notification message
- # Shows: current network → target network, with signal details and CLI commands
- notification_message=$(printf "Switch: %s → %s|%s\n\nApprove: 'wifi-switch-approve' | Decline: 'wifi-switch-decline'" "$FROM" "$TO" "$REASON_FORMATTED")
- # SHOW THE POPUP using notify-send (GNOME's notification system)
- ${pkgs.libnotify}/bin/notify-send \
- "🔗 WiFi Network Switch Available" \
- "$notification_message" \
- --urgency=critical \
- --expire-time=30000
- fi
- # CLEAN UP the request file immediately (even if rate limited)
- # The root service will timeout after 30 seconds if no CLI response
- rm -f "$request_file"
- fi
- done
- # ============================================================
- # STEP 2: Check for WiFi switch success notifications
- # ============================================================
- # When a switch succeeds, show a confirmation popup
- for success_file in /tmp/wifi-switch-success-*; do
- if [ -f "$success_file" ]; then
- # PARSE success notification (contains SWITCHED_FROM, SWITCHED_TO)
- source "$success_file"
- # SHOW success popup (brief, 5-second display)
- ${pkgs.libnotify}/bin/notify-send \
- "✅ WiFi Switch Complete" \
- "Successfully switched from $SWITCHED_FROM to $SWITCHED_TO" \
- --urgency=normal \
- --expire-time=5000
- # CLEAN UP success file
- rm -f "$success_file"
- fi
- done
- # WAIT 1 second before checking again
- # This prevents excessive CPU usage while being responsive
- sleep 1
- done
- ''}";
- };
- };
- };
- }
Advertisement