adingbatponder

Untitled

Apr 6th, 2026
269
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 46.88 KB | None | 0 0
  1. # ============================================================================
  2. # NIXOS INTELLIGENT WIFI AUTO-SWITCHING MODULE
  3. # ============================================================================
  4. #
  5. # 📊 VISUAL FLOWCHART: See wifi-auto-flowchart.md for complete system diagram
  6. #
  7. # This module creates a complete WiFi management system that:
  8. #
  9. # 1. MONITORS WiFi connections every 30 seconds via systemd service
  10. # 2. DETECTS when managed networks (with agenix secrets) become available
  11. # 3. NOTIFIES user via desktop notifications when switches are recommended
  12. # 4. SWITCHES networks immediately when user approves via CLI commands
  13. # 5. REMEMBERS user decisions to avoid repeated prompts
  14. #
  15. # COMPONENTS:
  16. # - wifi-auto-monitor.service: Background daemon monitoring WiFi status
  17. # - wifi-notification-handler: User session service showing notifications
  18. # - wifi-switch-approve: CLI command for immediate network switching
  19. # - wifi-switch-decline: CLI command to decline network switches
  20. #
  21. # HOW TO USE:
  22. # 1. Store WiFi passwords: nix develop .#secrets -> encrypt-wifi <name> <password>
  23. # 2. Enable module: networking.wifi-auto.enable = true;
  24. # 3. Rebuild: sudo nixos-rebuild switch --flake .
  25. # 4. When notification appears: run 'wifi-switch-approve' or 'wifi-switch-decline'
  26. #
  27. # EXAMPLE WORKFLOW:
  28. # - Currently on AndroidAP (unmanaged hotspot)
  29. # - VM2530351 network becomes available (managed with agenix secret)
  30. # - Notification appears: "Switch to VM2530351?"
  31. # - User runs: wifi-switch-approve
  32. # - System immediately switches to VM2530351
  33. # ============================================================================
  34.  
  35. { config, lib, pkgs, ... }:
  36.  
  37. with lib;
  38.  
  39. let
  40. # ============================================================================
  41. # STEP 1: DISCOVER WIFI SECRETS
  42. # ============================================================================
  43.  
  44. # Find all WiFi secrets in the agenix configuration
  45. # Looks for any secret names starting with "wifi-"
  46. # Example: "wifi-MyVPN", "wifi-CoffeeShop" -> both found automatically
  47. #
  48. # MACHINE-SPECIFIC: The USB WiFi dongle (meshchat-usb-dongle.nix) manages its
  49. # own NetworkManager connection with special routing (never-default, route-metric=700).
  50. # We must exclude it here, otherwise wifi-auto generates a second "auto-" connection
  51. # for the same SSID WITHOUT those routing protections, and NetworkManager may pick
  52. # that one instead — stealing the default route from wlp61s0 and killing internet.
  53. excludedSecrets = [
  54. "wifi-Meshchat-192-168-4-1" # managed by modules/parts/meshchat-usb-dongle.nix
  55. ];
  56. wifiSecrets = filterAttrs (name: _: hasPrefix "wifi-" name && !(builtins.elem name excludedSecrets)) config.age.secrets;
  57.  
  58. # Convert agenix secret names to actual WiFi network names
  59. # Strips the "wifi-" prefix to get the real network SSID
  60. # Example: "wifi-VM2530351" -> "VM2530351"
  61. secretToNetworkName = secretName:
  62. removePrefix "wifi-" secretName;
  63.  
  64. # ============================================================================
  65. # STEP 2: VIP NETWORK DETECTION
  66. # ============================================================================
  67.  
  68. # Check if a network is a VIP network (should not be auto-switched from)
  69. # VIP networks include:
  70. # - Networks with "vpn" or "VPN" in the name
  71. # - Networks manually preferred in GNOME (detected at runtime)
  72. isVipNetwork = networkName:
  73. (builtins.match ".*[Vv][Pp][Nn].*" networkName) != null;
  74.  
  75. # ============================================================================
  76. # STEP 3: GENERATE NETWORKMANAGER CONNECTION FILES
  77. # ============================================================================
  78.  
  79. # Create NetworkManager connection files for each discovered WiFi secret
  80. # These .nmconnection files tell NetworkManager which networks it can connect to
  81. # and where to find their passwords
  82. generateWifiConnections = mapAttrsToList (secretName: secret:
  83. let
  84. # Extract the actual network name (SSID)
  85. networkName = secretToNetworkName secretName;
  86. # Create a unique connection identifier
  87. connectionName = "auto-${networkName}";
  88. # Determine if this is a VIP network
  89. isVip = isVipNetwork networkName;
  90. in {
  91. # File location: /etc/NetworkManager/system-connections/auto-NetworkName.nmconnection
  92. name = "NetworkManager/system-connections/${connectionName}.nmconnection";
  93.  
  94. # File properties and content
  95. value = {
  96. mode = "0600"; # Secure permissions - only root can read/write
  97. user = "root"; # NetworkManager requires root ownership
  98. group = "root";
  99.  
  100. # NetworkManager connection file in INI format
  101. # This is the standard format NetworkManager expects
  102. text = ''
  103. [connection]
  104. id=${connectionName}
  105. type=wifi
  106. interface-name=wlp61s0
  107. autoconnect=true
  108. autoconnect-priority=${if isVip then "100" else "0"}
  109.  
  110. [wifi]
  111. mode=infrastructure
  112. ssid=${networkName}
  113.  
  114. [wifi-security]
  115. key-mgmt=wpa-psk
  116.  
  117. [ipv4]
  118. method=auto
  119.  
  120. [ipv6]
  121. addr-gen-mode=default
  122. method=auto
  123.  
  124. [proxy]
  125. '';
  126. };
  127. }
  128. ) wifiSecrets;
  129.  
  130. in {
  131. # ============================================================================
  132. # MODULE OPTIONS
  133. # ============================================================================
  134.  
  135. options.networking.wifi-auto = {
  136. enable = mkEnableOption "automatic WiFi connection using agenix secrets";
  137.  
  138. # Monitoring intervals for the intelligent network selection
  139. fastScanInterval = mkOption {
  140. type = types.int;
  141. default = 30;
  142. description = "Seconds between fast scans for new networks and connection restoration";
  143. };
  144.  
  145. stabilityScanInterval = mkOption {
  146. type = types.int;
  147. default = 300; # 5 minutes
  148. description = "Seconds between stability tests and potential network switching";
  149. };
  150.  
  151. # Quality thresholds for network selection
  152. stabilityThreshold = mkOption {
  153. type = types.float;
  154. default = 0.95; # 95% success rate
  155. description = "Minimum stability score (0.0-1.0) required for normal network switching";
  156. };
  157.  
  158. emergencyThreshold = mkOption {
  159. type = types.float;
  160. default = 0.50; # 50% success rate
  161. description = "Emergency threshold below which VIP networks can be auto-switched";
  162. };
  163.  
  164. minSpeedMbps = mkOption {
  165. type = types.int;
  166. default = 1;
  167. description = "Minimum speed in Mbps below which a connection is considered emergency-level bad";
  168. };
  169. };
  170.  
  171. # ============================================================================
  172. # MODULE CONFIGURATION
  173. # ============================================================================
  174.  
  175. config = mkIf config.networking.wifi-auto.enable {
  176. # Ensure NetworkManager is enabled
  177. networking.networkmanager.enable = true;
  178.  
  179. # Install required packages for network testing and monitoring
  180. environment.systemPackages = with pkgs; [
  181. speedtest-cli # Ookla speed testing
  182. iperf3 # Network bandwidth testing
  183. iw # WiFi signal strength and scanning
  184. networkmanager # nmcli for connection management
  185. libnotify # Desktop notifications
  186. zenity # GNOME dialog boxes for user authorization
  187. bc # Calculator for stability score math
  188. ];
  189.  
  190. # NetworkManager connections are now created dynamically via nmcli service
  191.  
  192. # WiFi connections are now managed manually via fix-wifi-connections.sh script
  193. # This avoids systemd dependency issues during system rebuild
  194.  
  195. # ============================================================================
  196. # INTELLIGENT WIFI MONITORING SERVICE WITH ZENITY POPUPS
  197. # ============================================================================
  198.  
  199. # Main WiFi monitoring service with interactive user authorization
  200. systemd.services.wifi-auto-monitor = {
  201. description = "Intelligent WiFi Auto-Connection Monitor with User Authorization";
  202. documentation = [ "Custom NixOS WiFi management with stability-based selection" ];
  203. wantedBy = [ "multi-user.target" ];
  204. after = [ "NetworkManager.service" "network.target" "graphical-session.target" ];
  205. wants = [ "NetworkManager.service" ];
  206.  
  207. # Service configuration for robust operation
  208. serviceConfig = {
  209. Type = "simple";
  210. Restart = "always";
  211. RestartSec = "10";
  212. User = "root"; # Required for NetworkManager control
  213. Group = "root";
  214.  
  215. # Security hardening (Tier A/B applied via basicHardening module)
  216. NoNewPrivileges = true;
  217. ProtectSystem = "strict";
  218. ProtectHome = true;
  219. ReadWritePaths = [
  220. "/etc/NetworkManager/system-connections"
  221. "/var/lib/wifi-auto-monitor"
  222. "/tmp"
  223. ];
  224.  
  225. # Allow access to display for zenity popups (X11 and Wayland compatible)
  226. Environment = [
  227. "DISPLAY=:0"
  228. "WAYLAND_DISPLAY=wayland-0"
  229. "XDG_RUNTIME_DIR=/run/user/1000"
  230. "XDG_SESSION_TYPE=wayland"
  231. "XDG_CURRENT_DESKTOP=GNOME"
  232. "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus,guid=ae228eab7c9054b61adddc9768aba0e3"
  233. ];
  234.  
  235. # ======================================================================
  236. # MAIN WIFI AUTO-SWITCHING SERVICE SCRIPT
  237. # ======================================================================
  238. # This is the core daemon that:
  239. # 1. Monitors current WiFi connection every 30 seconds
  240. # 2. Detects when managed networks (with agenix secrets) become available
  241. # 3. Creates authorization requests for user approval via notifications
  242. # 4. Switches networks when approved via CLI commands
  243. # 5. Remembers user decisions to avoid repeated prompts
  244. # ======================================================================
  245. ExecStart = pkgs.writeShellScript "wifi-auto-monitor" ''
  246. #!/bin/bash
  247.  
  248. # ========================================================================
  249. # WIFI AUTO-MONITOR SERVICE WITH USER AUTHORIZATION
  250. # ========================================================================
  251. #
  252. # How it works:
  253. # - Runs every 30 seconds to check network status
  254. # - When on unmanaged network (like AndroidAP), offers to switch to managed (VM2530351)
  255. # - Creates request files in /tmp/ that CLI commands can respond to
  256. # - User approves with: wifi-switch-approve (switches immediately)
  257. # - User declines with: wifi-switch-decline
  258. # - Notifications appear via desktop notification system
  259.  
  260. set -euo pipefail
  261.  
  262. # Add required tools to PATH
  263. 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"
  264.  
  265. # Configuration from NixOS module options
  266. FAST_INTERVAL=${toString config.networking.wifi-auto.fastScanInterval}
  267. STABILITY_INTERVAL=${toString config.networking.wifi-auto.stabilityScanInterval}
  268. STABILITY_THRESHOLD=${toString config.networking.wifi-auto.stabilityThreshold}
  269. EMERGENCY_THRESHOLD=${toString config.networking.wifi-auto.emergencyThreshold}
  270. MIN_SPEED_MBPS=${toString config.networking.wifi-auto.minSpeedMbps}
  271.  
  272. # State directory for persistent data
  273. STATE_DIR="/var/lib/wifi-auto-monitor"
  274. mkdir -p "$STATE_DIR"
  275.  
  276. # State files for decision memory
  277. USER_DECISIONS_FILE="$STATE_DIR/user_decisions.txt"
  278. NETWORK_HISTORY_FILE="$STATE_DIR/network_history.txt"
  279.  
  280. # Logging function with timestamps
  281. log() {
  282. echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" >&2
  283. }
  284.  
  285. # ======================================================================
  286. # STARTUP CLEANUP: Remove stale auto-* connection files
  287. # ======================================================================
  288. # The monitor script creates real files in /etc/NetworkManager/system-connections/
  289. # which persist across rebuilds and ignore declarative config changes.
  290. # On startup, remove them so the "restore missing connections" block below
  291. # recreates them with the current settings (e.g. interface-name=wlp61s0).
  292. log "Cleaning up stale auto-* connection files"
  293. shopt -s nullglob
  294. for f in /etc/NetworkManager/system-connections/auto-*.nmconnection; do
  295. rm -f "$f" && log "Removed stale: $f"
  296. done
  297. shopt -u nullglob
  298. nmcli connection reload 2>/dev/null || true
  299. log "Connection reload complete"
  300.  
  301. # ======================================================================
  302. # INTERACTIVE USER AUTHORIZATION WITH ZENITY
  303. # ======================================================================
  304.  
  305. # Ask user for authorization using file-based communication with user session
  306. ask_user_authorization() {
  307. local from_network="$1"
  308. local to_network="$2"
  309. local reason="$3"
  310.  
  311. # Check if we've recently shown a notification for this network pair
  312. # Snooze duration matches the scan interval to prevent duplicate popups
  313. local snooze_duration=$((FAST_INTERVAL + 60)) # scan interval + 1 minute buffer
  314. local snooze_file="/tmp/wifi-notification-snooze-$from_network-to-$to_network"
  315. local current_time=$(date +%s)
  316.  
  317. if [ -f "$snooze_file" ]; then
  318. local last_notification_time=$(cat "$snooze_file" 2>/dev/null || echo 0)
  319. local time_diff=$((current_time - last_notification_time))
  320. if [ $time_diff -lt $snooze_duration ]; then
  321. log "Skipping notification (snooze active): $from_network to $to_network (shown ''${time_diff}s ago, snooze ''${snooze_duration}s)"
  322. return 1
  323. fi
  324. fi
  325.  
  326. # Record this notification time
  327. echo "$current_time" > "$snooze_file"
  328.  
  329. log "Requesting user authorization to switch from $from_network to $to_network ($reason)"
  330.  
  331. # Create request file for user session to pick up
  332. local request_file="/tmp/wifi-switch-request-$$"
  333. local response_file="/tmp/wifi-switch-response-$$"
  334.  
  335. # Create request with all details - encode newlines to avoid parsing issues
  336. log "DEBUG: Original reason: $reason"
  337. reason_encoded=$(echo "$reason" | tr '\n' '|' | sed 's/|$//' | sed 's/|/|NEWLINE|/g')
  338. log "DEBUG: Encoded reason: $reason_encoded"
  339. {
  340. echo "FROM=$from_network"
  341. echo "TO=$to_network"
  342. printf 'REASON=%q\n' "$reason_encoded"
  343. echo "TIMESTAMP=$(date +%s)"
  344. echo "RESPONSE_FILE=$response_file"
  345. } > "$request_file"
  346.  
  347. # Make request readable by user
  348. chmod 644 "$request_file"
  349. chown adingbatponder:users "$request_file" 2>/dev/null || true
  350.  
  351. log "Created authorization request file: $request_file"
  352.  
  353. # Wait for user response (up to 30 seconds)
  354. local wait_count=0
  355. while [ ! -f "$response_file" ] && [ $wait_count -lt 30 ]; do
  356. sleep 1
  357. wait_count=$((wait_count + 1))
  358. done
  359.  
  360. # Check response
  361. if [ -f "$response_file" ]; then
  362. local response=$(cat "$response_file" 2>/dev/null)
  363. rm -f "$request_file" "$response_file" 2>/dev/null || true
  364.  
  365. if [ "$response" = "APPROVE" ]; then
  366. log "User APPROVED switch from $from_network to $to_network"
  367. echo "APPROVE:$from_network:$to_network:$(date +%s)" >> "$USER_DECISIONS_FILE"
  368. return 0 # approved
  369. else
  370. log "User DECLINED switch from $from_network to $to_network"
  371. echo "DECLINE:$from_network:$to_network:$(date +%s)" >> "$USER_DECISIONS_FILE"
  372. return 1 # declined
  373. fi
  374. else
  375. log "No user response received (timeout)"
  376. rm -f "$request_file" 2>/dev/null || true
  377. echo "TIMEOUT:$from_network:$to_network:$(date +%s)" >> "$USER_DECISIONS_FILE"
  378. return 1 # timeout
  379. fi
  380. }
  381.  
  382. # Clean up decline decisions for networks that no longer exist
  383. cleanup_stale_decisions() {
  384. if [ -f "$USER_DECISIONS_FILE" ]; then
  385. log "Cleaning up stale network decisions"
  386.  
  387. # Get list of currently available networks
  388. local available_managed=$(get_available_networks)
  389. local all_available_networks=$(nmcli -t -f SSID dev wifi list 2>/dev/null | sort -u)
  390.  
  391. # Create temporary file for valid decisions
  392. local temp_file=$(mktemp)
  393.  
  394. # Process each decision line
  395. while IFS=':' read -r decision from to timestamp; do
  396. local keep_decision=true
  397.  
  398. if [ "$decision" = "DECLINE" ]; then
  399. # Check if source network still exists (in any form)
  400. if ! echo "$all_available_networks" | grep -q "^$from$"; then
  401. log "Source network '$from' no longer available - removing decision"
  402. keep_decision=false
  403. # Check if target managed network still exists
  404. elif ! echo "$available_managed" | grep -q "^$to$"; then
  405. log "Target managed network '$to' no longer available - removing decision"
  406. keep_decision=false
  407. fi
  408. fi
  409.  
  410. # Keep valid decisions
  411. if [ "$keep_decision" = true ] && [ -n "$decision" ]; then
  412. echo "$decision:$from:$to:$timestamp" >> "$temp_file"
  413. fi
  414. done < "$USER_DECISIONS_FILE"
  415.  
  416. # Replace old file with cleaned version
  417. mv "$temp_file" "$USER_DECISIONS_FILE"
  418. log "Stale decision cleanup completed"
  419. fi
  420. }
  421.  
  422. # Check if user has previously declined switching from source to target network
  423. user_declined_switch() {
  424. local from_network="$1"
  425. local to_network="$2"
  426.  
  427. if [ -f "$USER_DECISIONS_FILE" ]; then
  428. # Check for recent decline (within last 24 hours)
  429. local day_ago=$(($(date +%s) - 86400))
  430. while IFS=':' read -r decision from to timestamp; do
  431. if [ "$decision" = "DECLINE" ] && [ "$from" = "$from_network" ] && [ "$to" = "$to_network" ]; then
  432. if [ "$timestamp" -gt "$day_ago" ]; then
  433. return 0 # recently declined
  434. fi
  435. fi
  436. done < "$USER_DECISIONS_FILE"
  437. fi
  438. return 1 # no recent decline
  439. }
  440.  
  441. # ======================================================================
  442. # BASIC MONITORING FUNCTIONS (SIMPLIFIED FOR EXAMPLE)
  443. # ======================================================================
  444.  
  445. # Get currently connected WiFi network (any network, managed or unmanaged)
  446. get_current_network() {
  447. nmcli -t connection show --active | grep "802-11-wireless" | head -1 | cut -d: -f1 || echo ""
  448. }
  449.  
  450. # Get the SSID of the currently connected WiFi network
  451. get_current_ssid() {
  452. # Try multiple methods to get the current SSID
  453. local ssid=""
  454.  
  455. # Method 1: Get SSID directly from WiFi device (most reliable)
  456. ssid=$(nmcli -t -f WIFI.SSID device show wlp61s0 2>/dev/null | cut -d: -f2)
  457. if [ -n "$ssid" ]; then
  458. echo "$ssid"
  459. return
  460. fi
  461.  
  462. # Method 2: Get SSID from active connection details
  463. local connection_name=$(nmcli -t connection show --active | grep "802-11-wireless" | head -1 | cut -d: -f1)
  464. if [ -n "$connection_name" ]; then
  465. ssid=$(nmcli -t -f 802-11-wireless.ssid connection show "$connection_name" 2>/dev/null | cut -d: -f2)
  466. if [ -n "$ssid" ]; then
  467. echo "$ssid"
  468. return
  469. fi
  470. fi
  471.  
  472. # Method 3: Get from device status as fallback
  473. ssid=$(nmcli -t -f GENERAL.CONNECTION device show wlp61s0 2>/dev/null | head -1 | cut -d: -f2)
  474. if [ -n "$ssid" ] && [[ "$ssid" == auto-* ]]; then
  475. # If we got a connection name like "auto-Eva", extract the SSID part
  476. echo "''${ssid#auto-}"
  477. return
  478. fi
  479.  
  480. # Method 4: Ultimate fallback
  481. ssid=$(nmcli -t -f WIFI.SSID device show 2>/dev/null | head -1 | cut -d: -f2)
  482. echo "$ssid"
  483. }
  484.  
  485. # Get currently connected MANAGED WiFi network (any network with agenix secrets)
  486. get_current_managed_network() {
  487. local current_ssid=$(get_current_ssid)
  488. if [ -n "$current_ssid" ] && [ -f "/run/agenix/wifi-$current_ssid" ]; then
  489. echo "$current_ssid"
  490. else
  491. echo ""
  492. fi
  493. }
  494.  
  495. # Check if current connection is managed by our system
  496. is_current_connection_managed() {
  497. local current_ssid=$(get_current_ssid)
  498. [ -n "$current_ssid" ] && [ -f "/run/agenix/wifi-$current_ssid" ]
  499. }
  500.  
  501. # Check if a network name indicates it's a VIP network
  502. is_vip_network() {
  503. local network_name="$1"
  504. # Check for VPN in name (case insensitive)
  505. [[ "$network_name" =~ [Vv][Pp][Nn] ]]
  506. }
  507.  
  508. # Get list of available networks with our stored secrets (works with existing connections)
  509. get_available_networks() {
  510. nmcli -t -f SSID dev wifi list 2>/dev/null | while read -r ssid; do
  511. if [ -n "$ssid" ] && [ -f "/run/agenix/wifi-$ssid" ]; then
  512. echo "$ssid"
  513. fi
  514. done | sort -u
  515. }
  516.  
  517. # Convert SSID to connection name (maps "Eva" -> "auto-Eva")
  518. ssid_to_connection() {
  519. local ssid="$1"
  520. echo "auto-$ssid"
  521. }
  522.  
  523. # Get network signal strength and rate for comparison
  524. get_network_quality() {
  525. local network_name="$1"
  526. local signal_info rate_info
  527.  
  528. # Always get quality from WiFi scan (more reliable than device properties)
  529. signal_info=$(nmcli -t -f SSID,SIGNAL dev wifi list | grep "^$network_name:" | head -1 | cut -d: -f2)
  530. rate_info=$(nmcli -t -f SSID,RATE dev wifi list | grep "^$network_name:" | head -1 | cut -d: -f2)
  531.  
  532. if [ -n "$signal_info" ] && [ -n "$rate_info" ]; then
  533. echo "$signal_info:$rate_info" # Returns "signal:rate" like "100:270 Mbit/s"
  534. else
  535. echo "unknown:unknown"
  536. fi
  537. }
  538.  
  539. # Restore any missing connection files from our secrets
  540. restore_missing_connections() {
  541. local restored_count=0
  542.  
  543. ${concatStringsSep "\n" (mapAttrsToList (secretName: secret:
  544. let
  545. networkName = secretToNetworkName secretName;
  546. connectionName = "auto-${networkName}";
  547. connectionPath = "/etc/NetworkManager/system-connections/${connectionName}.nmconnection";
  548. isVip = isVipNetwork networkName;
  549. in ''
  550. if [ ! -f "${connectionPath}" ]; then
  551. log "Restoring missing connection: ${connectionName}"
  552.  
  553. cat > "${connectionPath}" << 'EOF'
  554. [connection]
  555. id=${connectionName}
  556. type=wifi
  557. interface-name=wlp61s0
  558. autoconnect=true
  559. autoconnect-priority=${if isVip then "100" else "0"}
  560.  
  561. [wifi]
  562. ssid=${networkName}
  563.  
  564. [wifi-security]
  565. key-mgmt=wpa-psk
  566. psk-file=${secret.path}
  567.  
  568. [ipv4]
  569. method=auto
  570.  
  571. [ipv6]
  572. method=auto
  573. EOF
  574.  
  575. chmod 0600 "${connectionPath}"
  576. chown root:root "${connectionPath}"
  577. nmcli connection reload >/dev/null 2>&1
  578.  
  579. restored_count=$((restored_count + 1))
  580. fi
  581. ''
  582. ) wifiSecrets)}
  583.  
  584. if [ $restored_count -gt 0 ]; then
  585. log "Restored $restored_count missing connection(s)"
  586. fi
  587. }
  588.  
  589. # ======================================================================
  590. # MAIN MONITORING LOOP
  591. # ======================================================================
  592.  
  593. fast_loop_counter=0
  594. # Calculate stability loop interval (minimum 1 to avoid division by zero)
  595. stability_loop_interval=$((STABILITY_INTERVAL / FAST_INTERVAL))
  596. [ $stability_loop_interval -lt 1 ] && stability_loop_interval=1
  597.  
  598. log "WiFi Auto-Monitor started with zenity user authorization"
  599. log "Fast loop: ''${FAST_INTERVAL}s, Stability loop: ''${STABILITY_INTERVAL}s"
  600. log "Interactive popups enabled for network switching decisions"
  601.  
  602. while true; do
  603. # Fast loop: Always restore missing connections and cleanup stale decisions
  604. restore_missing_connections
  605. cleanup_stale_decisions
  606.  
  607. # Get connection status
  608. current_connection=$(get_current_network)
  609. current_ssid=$(get_current_ssid)
  610. current_managed_network=$(get_current_managed_network)
  611.  
  612. # Debug logging
  613. log "DEBUG: current_connection='$current_connection', current_ssid='$current_ssid', current_managed='$current_managed_network'"
  614.  
  615. if [ -n "$current_connection" ]; then
  616. if is_current_connection_managed; then
  617. log "Connected to MANAGED network: $current_managed_network $(is_vip_network "$current_managed_network" && echo "[VIP]" || echo "[NORMAL]")"
  618.  
  619. # Clear any old decline decisions TO this network - manual connection overrides previous declines
  620. # If user manually connected to a network they previously declined, their preferences have changed
  621. if [ -f "$USER_DECISIONS_FILE" ]; then
  622. # Remove any DECLINE entries where the target was this current network
  623. sed -i "/DECLINE:.*:$current_managed_network:/d" "$USER_DECISIONS_FILE" 2>/dev/null || true
  624. log "Cleared any previous decline decisions for manually connected network: $current_managed_network"
  625. fi
  626. else
  627. log "Connected to UNMANAGED network: $current_ssid"
  628.  
  629. # Clear any old decline decisions FROM managed networks TO this unmanaged network
  630. # If user manually connected to an unmanaged network, respect their choice
  631. if [ -f "$USER_DECISIONS_FILE" ]; then
  632. # Remove any DECLINE entries where this unmanaged network was the source
  633. sed -i "/DECLINE:$current_ssid:/d" "$USER_DECISIONS_FILE" 2>/dev/null || true
  634. log "Cleared previous decline decisions from manually connected unmanaged network: $current_ssid"
  635. fi
  636.  
  637. # Check if we should offer to switch to a managed network
  638. available_networks=$(get_available_networks)
  639. if [ -n "$available_networks" ]; then
  640. best_managed_network=$(echo "$available_networks" | head -1)
  641. log "Available managed network found: $best_managed_network"
  642.  
  643. # ALWAYS ask user permission when switching from unmanaged to managed
  644. # Never assume managed networks are automatically better
  645. if ! user_declined_switch "$current_ssid" "$best_managed_network"; then
  646. # Get quality information for both networks
  647. current_quality=$(get_network_quality "$current_ssid")
  648. managed_quality=$(get_network_quality "$best_managed_network")
  649.  
  650. current_signal=$(echo "$current_quality" | cut -d: -f1)
  651. current_rate=$(echo "$current_quality" | cut -d: -f2)
  652. managed_signal=$(echo "$managed_quality" | cut -d: -f1)
  653. managed_rate=$(echo "$managed_quality" | cut -d: -f2)
  654.  
  655. # Ensure we have signal values, fallback to generic text if empty
  656. [ -z "$current_signal" ] && current_signal="unknown"
  657. [ -z "$managed_signal" ] && managed_signal="unknown"
  658. [ -z "$current_rate" ] && current_rate="unknown"
  659. [ -z "$managed_rate" ] && managed_rate="unknown"
  660.  
  661. # Create beautiful multi-line reason with % symbol and recommendation
  662. switch_reason="Current ($current_ssid): $current_signal%, $current_rate
  663. Managed ($best_managed_network): $managed_signal%, $managed_rate
  664. Recommendation: Switch for better performance"
  665.  
  666. if ask_user_authorization "$current_ssid" "$best_managed_network" "$switch_reason"; then
  667. log "User approved switch from unmanaged to managed network"
  668. local connection_name=$(ssid_to_connection "$best_managed_network")
  669. if nmcli connection up "$connection_name" >/dev/null 2>&1; then
  670. log "Successfully switched to managed network: $best_managed_network"
  671.  
  672. # Send success notification to user session
  673. local success_notification="/tmp/wifi-switch-success-$$"
  674. {
  675. echo "SWITCHED_FROM=$current_ssid"
  676. echo "SWITCHED_TO=$best_managed_network"
  677. echo "MESSAGE=Successfully switched WiFi networks"
  678. echo "TIMESTAMP=$(date +%s)"
  679. } > "$success_notification"
  680. chmod 644 "$success_notification"
  681. chown adingbatponder:users "$success_notification" 2>/dev/null || true
  682.  
  683. else
  684. log "Failed to switch to managed network: $best_managed_network"
  685. fi
  686. else
  687. log "User declined switch from unmanaged ($current_ssid) to managed ($best_managed_network)"
  688. fi
  689. else
  690. log "User previously declined switch from $current_ssid to $best_managed_network - not asking again"
  691. fi
  692. else
  693. log "No managed networks currently available"
  694. fi
  695. fi
  696. else
  697. log "No WiFi connection at all"
  698.  
  699. # No connection - try to connect to best available managed network
  700. available_networks=$(get_available_networks)
  701. if [ -n "$available_networks" ]; then
  702. best_managed_network=$(echo "$available_networks" | head -1)
  703. log "Connecting to best available managed network: $best_managed_network"
  704. local connection_name=$(ssid_to_connection "$best_managed_network")
  705. if nmcli connection up "$connection_name" >/dev/null 2>&1; then
  706. log "Successfully connected to managed network: $best_managed_network"
  707. else
  708. log "Failed to connect to managed network: $best_managed_network"
  709. fi
  710. else
  711. log "No managed networks available"
  712. fi
  713. fi
  714.  
  715. # Stability loop: Only for managed networks
  716. if [ $((fast_loop_counter % stability_loop_interval)) -eq 0 ] && [ -n "$current_managed_network" ]; then
  717. log "Stability check cycle for managed network: $current_managed_network"
  718.  
  719. # Example: If we find multiple managed networks, demonstrate authorization popup
  720. available_networks=$(get_available_networks)
  721. network_count=$(echo "$available_networks" | wc -l)
  722.  
  723. if [ "$network_count" -gt 1 ]; then
  724. # Find an alternative managed network
  725. alternative_network=$(echo "$available_networks" | grep -v "^$current_managed_network$" | head -1)
  726.  
  727. if [ -n "$alternative_network" ] && is_vip_network "$current_managed_network"; then
  728. # Only prompt occasionally to avoid spam (every 4th stability cycle)
  729. if [ $((fast_loop_counter / stability_loop_interval % 4)) -eq 0 ]; then
  730. if ! user_declined_switch "$current_managed_network" "$alternative_network"; then
  731. if ask_user_authorization "$current_managed_network" "$alternative_network" "Alternative managed network available"; then
  732. log "Switching to user-approved managed network: $alternative_network"
  733. local connection_name=$(ssid_to_connection "$alternative_network")
  734. nmcli connection up "$connection_name" >/dev/null 2>&1 || log "Switch failed"
  735. fi
  736. fi
  737. fi
  738. fi
  739. fi
  740. fi
  741.  
  742. fast_loop_counter=$((fast_loop_counter + 1))
  743. sleep "$FAST_INTERVAL"
  744. done
  745. '';
  746. };
  747. };
  748.  
  749. # Create state directory for the monitor service
  750. systemd.tmpfiles.rules = [
  751. "d /var/lib/wifi-auto-monitor 0755 root root -"
  752. ];
  753.  
  754. # ============================================================================
  755. # USER SESSION POPUP HANDLER (runs in user GNOME session)
  756. # ============================================================================
  757.  
  758. # Add CLI response commands (notification handler is now a systemd user service)
  759. users.users.adingbatponder.packages = with pkgs; [
  760. # ======================================================================
  761. # IMMEDIATE WIFI SWITCH APPROVAL COMMAND: wifi-switch-approve
  762. # ======================================================================
  763. # This command switches to the best available managed network IMMEDIATELY
  764. # No timing dependencies - works on-demand when user wants to switch
  765. # Checks for agenix secrets to determine which networks are available
  766. # ======================================================================
  767. (writeShellScriptBin "wifi-switch-approve" ''
  768. #!/usr/bin/env bash
  769. # Switch to the currently recommended network from the active request
  770. # This script needs to access agenix secrets, so run with elevated privileges if needed
  771. if [ "$EUID" -ne 0 ] && [ -z "$SUDO_USER" ]; then
  772. echo "🔄 Requesting elevated privileges to access WiFi secrets..."
  773. exec sudo "$0" "$@"
  774. fi
  775.  
  776. echo "🔄 Approving WiFi switch..."
  777.  
  778. # Get the most recent recommendation from debug logs (most reliable method)
  779. target_network=$(tail -1 /tmp/notification-debug.log 2>/dev/null | grep "TO=" | sed 's/.*TO=\([^,]*\).*/\1/')
  780.  
  781. if [ -z "$target_network" ]; then
  782. echo "❌ No recent WiFi recommendation found"
  783. echo " Make sure you've seen a WiFi switch popup recently"
  784. exit 1
  785. fi
  786.  
  787. echo "📡 Approving switch to: $target_network"
  788.  
  789. # Try to find active request file to send proper approval signal
  790. request_file=$(ls /tmp/wifi-switch-request-* 2>/dev/null | head -1)
  791. if [ -f "$request_file" ]; then
  792. source "$request_file"
  793. # Signal approval to monitoring system
  794. if [ -n "$RESPONSE_FILE" ]; then
  795. echo "APPROVE" > "$RESPONSE_FILE"
  796. fi
  797. fi
  798.  
  799. echo "📡 Switching to network: $target_network"
  800.  
  801. # Use proper connection name format (auto-NetworkName)
  802. connection_name="auto-$target_network"
  803.  
  804. if ${networkmanager}/bin/nmcli connection up "$connection_name" >/dev/null 2>&1; then
  805. echo "✅ Successfully switched to $target_network"
  806. ${libnotify}/bin/notify-send "WiFi Switch Approved" "Successfully switched to $target_network"
  807. else
  808. echo "❌ Failed to switch to $target_network (connection: $connection_name)"
  809. ${libnotify}/bin/notify-send "WiFi Switch Failed" "Could not switch to $target_network"
  810. exit 1
  811. fi
  812. '')
  813.  
  814. # ======================================================================
  815. # WIFI SWITCH DECLINE COMMAND: wifi-switch-decline
  816. # ======================================================================
  817. # This command declines the current WiFi switch request and stays on current network
  818. # ======================================================================
  819. (writeShellScriptBin "wifi-switch-decline" ''
  820. #!/usr/bin/env bash
  821. # Decline pending WiFi network switch
  822. echo "⏰ Will decline the NEXT WiFi switch request automatically..."
  823.  
  824. # Function to check and decline
  825. check_and_decline() {
  826. local request_file=$(ls /tmp/wifi-switch-request-* 2>/dev/null | head -1)
  827. if [ -n "$request_file" ]; then
  828. local response_file=$(grep "RESPONSE_FILE=" "$request_file" 2>/dev/null | cut -d= -f2)
  829. if [ -n "$response_file" ]; then
  830. echo "DECLINE" > "$response_file"
  831. echo "❌ DECLINED WiFi switch - staying on current network"
  832. ${libnotify}/bin/notify-send "WiFi Switch" "Staying on current network"
  833. return 0
  834. fi
  835. fi
  836. return 1
  837. }
  838.  
  839. # Check if there's already a request
  840. if check_and_decline; then
  841. exit 0
  842. fi
  843.  
  844. # Otherwise wait for next request (up to 60 seconds)
  845. echo "🔍 Waiting for next WiFi switch request (up to 60s)..."
  846. for i in {1..60}; do
  847. if check_and_decline; then
  848. exit 0
  849. fi
  850. sleep 1
  851. done
  852.  
  853. echo "❌ No request appeared within 60 seconds"
  854. '')
  855. ];
  856.  
  857. # GNOME autostart file is created above in environment.etc merge
  858.  
  859. # ========================================================================
  860. # SYSTEMD USER SERVICE: WiFi Notification Handler
  861. # ========================================================================
  862. #
  863. # WHAT THIS DOES:
  864. # Creates a systemd user service that runs in the user's session (not as root)
  865. # This service monitors for WiFi switch requests and shows desktop notifications
  866. #
  867. # WHY SYSTEMD USER SERVICE INSTEAD OF DESKTOP AUTOSTART:
  868. # 1. More reliable - systemd manages the process lifecycle
  869. # 2. Auto-restart if crashes - "Restart = always" ensures it never stays dead
  870. # 3. Proper session integration - runs with user permissions and desktop access
  871. # 4. Better logging - can use "journalctl --user" to debug issues
  872. # 5. Water-tight operation - no manual intervention needed after rebuilds
  873. #
  874. # HOW IT WORKS:
  875. # - Starts automatically when user logs into desktop ("wantedBy graphical-session.target")
  876. # - Runs continuously, checking for request files every 1 second
  877. # - Shows popup notifications when WiFi switches are recommended
  878. # - Cleans up request/success files after processing them
  879. # ========================================================================
  880.  
  881. systemd.user.services.wifi-notification-handler = {
  882. description = "WiFi Auto-Switch Notification Handler";
  883.  
  884. # WHEN TO START: Start automatically when user logs into desktop session
  885. # "graphical-session.target" = when desktop environment (GNOME/KDE/etc) starts
  886. wantedBy = [ "graphical-session.target" ];
  887.  
  888. # DEPENDENCIES: Wait for desktop session to be fully ready before starting
  889. # This ensures DISPLAY, notification system, etc. are available
  890. after = [ "graphical-session.target" ];
  891.  
  892. serviceConfig = {
  893. # SERVICE TYPE: "simple" = run the command and keep it running
  894. # (as opposed to "oneshot" which runs once and exits)
  895. Type = "simple";
  896.  
  897. # AUTO-RESTART: If the service crashes or exits, restart it automatically
  898. # This makes the system "water-tight" - it always recovers from failures
  899. Restart = "always";
  900.  
  901. # RESTART DELAY: Wait 5 seconds before restarting (prevents rapid restart loops)
  902. RestartSec = "5";
  903. # THE ACTUAL PROGRAM TO RUN:
  904. # pkgs.writeShellScript creates a shell script in the Nix store that systemd executes
  905. ExecStart = "${pkgs.writeShellScript "wifi-notification-handler" ''
  906. #!/usr/bin/env bash
  907.  
  908. # ================================================================
  909. # MAIN NOTIFICATION HANDLER LOOP
  910. # ================================================================
  911. # This script runs continuously, checking for WiFi switch requests
  912. # from the root wifi-auto-monitor service every 1 second
  913. # ================================================================
  914.  
  915. # Rate limiter: minimum 30 minutes between notifications (matches scan interval)
  916. NOTIFICATION_COOLDOWN=1800
  917. LAST_NOTIFICATION_FILE="/tmp/wifi-notification-last-shown"
  918.  
  919. can_show_notification() {
  920. local current_time=$(date +%s)
  921. if [ -f "$LAST_NOTIFICATION_FILE" ]; then
  922. local last_time=$(cat "$LAST_NOTIFICATION_FILE" 2>/dev/null || echo 0)
  923. local elapsed=$((current_time - last_time))
  924. if [ $elapsed -lt $NOTIFICATION_COOLDOWN ]; then
  925. echo "Rate limited: ''${elapsed}s since last notification (cooldown: ''${NOTIFICATION_COOLDOWN}s)" >> /tmp/notification-debug.log
  926. return 1
  927. fi
  928. fi
  929. echo "$current_time" > "$LAST_NOTIFICATION_FILE"
  930. return 0
  931. }
  932.  
  933. while true; do
  934.  
  935. # ============================================================
  936. # STEP 1: Check for WiFi switch requests
  937. # ============================================================
  938. # The root service creates files like "/tmp/wifi-switch-request-12345"
  939. # containing FROM=network, TO=network, REASON=signal_info
  940.  
  941. for request_file in /tmp/wifi-switch-request-*; do
  942. if [ -f "$request_file" ]; then
  943.  
  944. # PARSE the request file to extract network names and reason
  945. # "source" loads the variables FROM, TO, REASON from the file
  946. source "$request_file"
  947.  
  948. # CLEAN UP the reason text for display:
  949. # The root service encodes newlines as "|NEWLINE|" to avoid file parsing issues
  950. # We convert them to bullet points (•) for a clean single-line notification
  951. REASON_FORMATTED=$(printf '%s\n' "$REASON" | sed 's/|NEWLINE|/ • /g')
  952.  
  953. # DEBUG logging (helps troubleshoot if notifications don't appear)
  954. echo "DEBUG: FROM=$FROM, TO=$TO, REASON=$REASON_FORMATTED" >> /tmp/notification-debug.log
  955.  
  956. # Rate limit check - only show one notification per cooldown period
  957. if can_show_notification; then
  958. # CREATE the popup notification message
  959. # Shows: current network → target network, with signal details and CLI commands
  960. notification_message=$(printf "Switch: %s → %s|%s\n\nApprove: 'wifi-switch-approve' | Decline: 'wifi-switch-decline'" "$FROM" "$TO" "$REASON_FORMATTED")
  961.  
  962. # SHOW THE POPUP using notify-send (GNOME's notification system)
  963. ${pkgs.libnotify}/bin/notify-send \
  964. "🔗 WiFi Network Switch Available" \
  965. "$notification_message" \
  966. --urgency=critical \
  967. --expire-time=30000
  968. fi
  969.  
  970. # CLEAN UP the request file immediately (even if rate limited)
  971. # The root service will timeout after 30 seconds if no CLI response
  972. rm -f "$request_file"
  973. fi
  974. done
  975.  
  976. # ============================================================
  977. # STEP 2: Check for WiFi switch success notifications
  978. # ============================================================
  979. # When a switch succeeds, show a confirmation popup
  980.  
  981. for success_file in /tmp/wifi-switch-success-*; do
  982. if [ -f "$success_file" ]; then
  983.  
  984. # PARSE success notification (contains SWITCHED_FROM, SWITCHED_TO)
  985. source "$success_file"
  986.  
  987. # SHOW success popup (brief, 5-second display)
  988. ${pkgs.libnotify}/bin/notify-send \
  989. "✅ WiFi Switch Complete" \
  990. "Successfully switched from $SWITCHED_FROM to $SWITCHED_TO" \
  991. --urgency=normal \
  992. --expire-time=5000
  993.  
  994. # CLEAN UP success file
  995. rm -f "$success_file"
  996. fi
  997. done
  998.  
  999. # WAIT 1 second before checking again
  1000. # This prevents excessive CPU usage while being responsive
  1001. sleep 1
  1002. done
  1003. ''}";
  1004. };
  1005. };
  1006. };
  1007. }
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment