#!/usr/bin/env bash

get_wifi_iface() {
  awk 'NR > 2 { gsub(":", "", $1); print $1; exit }' /proc/net/wireless
}

get_usb_iface() {
  ip link 2>/dev/null | awk '
    /^[0-9]+: usb[0-9]/ { gsub(":", "", $2); print $2; exit }
    /^[0-9]+: enx/      { gsub(":", "", $2); print $2; exit }
  '
}

signal_icon() {
  local dbm="$1"
  if [ -z "$dbm" ]; then echo "󰤮"; return; fi
  if   [ "$dbm" -ge -50 ]; then echo "󰤨"
  elif [ "$dbm" -ge -60 ]; then echo "󰤥"
  elif [ "$dbm" -ge -70 ]; then echo "󰤢"
  elif [ "$dbm" -ge -80 ]; then echo "󰤟"
  else echo "󰤯"; fi
}

make_content() {
  local wifi_iface eth_iface

  wifi_iface=$(get_wifi_iface)
  eth_iface=$(ip link | awk '/^[0-9]+: en[po]/ { gsub(":",""); print $2; exit }')

  # Ethernet
  local eth_connected=false
  if [ -n "$eth_iface" ]; then
    eth_state=$(ip link show "$eth_iface" 2>/dev/null | awk '/state/ { print $9 }')
    [ "$eth_state" = "UP" ] && eth_connected=true
  fi

  # USB tethering
  local usb_iface usb_connected=false
  usb_iface=$(get_usb_iface)
  if [ -n "$usb_iface" ] && ip -4 addr show "$usb_iface" 2>/dev/null | grep -q "inet "; then
    usb_connected=true
  fi

  # WiFi - use IP presence as connection indicator (more reliable than wpa_cli)
  local wifi_connected=false wifi_enabled=false wifi_icon="󰤮" wifi_ssid=""
  if ! rfkill list wlan 2>/dev/null | grep -q "Soft blocked: yes"; then
    wifi_enabled=true
  fi
  if [ -n "$wifi_iface" ] && ip -4 addr show "$wifi_iface" 2>/dev/null | grep -q "inet "; then
    wifi_connected=true
    wifi_ssid=$(wpa_cli -g "/run/wpa_supplicant/$wifi_iface" status 2>/dev/null \
      | awk -F= '/^ssid=/ { print $2 }')
    signal=$(awk -v iface="$wifi_iface" '$1 == iface ":" { gsub(/\./, "", $4); print $4; exit }' /proc/net/wireless)
    wifi_icon=$(signal_icon "$signal")
  fi

  printf '{"wifi":{"connected":%s,"enabled":%s,"icon":"%s","ssid":"%s"},"ethernet":{"connected":%s},"usb":{"connected":%s}}\n' \
    "$wifi_connected" "$wifi_enabled" "$wifi_icon" "$wifi_ssid" "$eth_connected" "$usb_connected"
}

make_content
ip monitor | while read -r _; do
  make_content
done
