#!/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 }
  '
}

freq_band() {
  local f="$1"
  if   [ "$f" -ge 6000 ] 2>/dev/null; then echo "6 GHz"
  elif [ "$f" -ge 5000 ] 2>/dev/null; then echo "5 GHz"
  elif [ "$f" -ge 2400 ] 2>/dev/null; then echo "2.4 GHz"
  else echo ""; fi
}

wifi_gen_label() {
  case "$1" in
    7) echo "Wi-Fi 7" ;; 6) echo "Wi-Fi 6" ;;
    5) echo "Wi-Fi 5" ;; 4) echo "Wi-Fi 4" ;;
    *) echo "" ;;
  esac
}

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 }')

  local wifi_ssid="" wifi_ip="" wifi_freq=0 wifi_band="" wifi_gen="" wifi_signal=0
  if [ -n "$wifi_iface" ] && ip -4 addr show "$wifi_iface" 2>/dev/null | grep -q "inet "; then
    local wpa
    wpa=$(wpa_cli -g "/run/wpa_supplicant/$wifi_iface" status 2>/dev/null)
    wifi_ssid=$(echo "$wpa"    | awk -F= '/^ssid=/            { print $2 }')
    wifi_ip=$(ip -4 addr show "$wifi_iface" | awk '/inet / { print $2 }')
    wifi_freq=$(echo "$wpa"   | awk -F= '/^freq=/             { print $2 }')
    local gen
    gen=$(echo "$wpa"         | awk -F= '/^wifi_generation=/  { print $2 }')
    wifi_band=$(freq_band "$wifi_freq")
    wifi_gen=$(wifi_gen_label "$gen")
    wifi_signal=$(awk -v iface="$wifi_iface" \
      '$1 == iface ":" { gsub(/\./, "", $4); print $4; exit }' /proc/net/wireless)
  fi

  local eth_ip="" eth_speed="" eth_state="down"
  if [ -n "$eth_iface" ]; then
    eth_state=$(ip link show "$eth_iface" 2>/dev/null | awk '/state/ { print tolower($9) }')
    if [ "$eth_state" = "up" ]; then
      eth_ip=$(ip -4 addr show "$eth_iface" | awk '/inet / { print $2 }')
      local spd
      spd=$(cat /sys/class/net/"$eth_iface"/speed 2>/dev/null)
      [ "${spd:-0}" -gt 0 ] 2>/dev/null && eth_speed="${spd} Mbps"
    fi
  fi

  local usb_iface usb_ip=""
  usb_iface=$(get_usb_iface)
  if [ -n "$usb_iface" ] && ip -4 addr show "$usb_iface" 2>/dev/null | grep -q "inet "; then
    usb_ip=$(ip -4 addr show "$usb_iface" | awk '/inet / { print $2 }')
  fi

  # shellcheck disable=SC2059
  printf '{"wifi":{"ssid":"%s","ip":"%s","freq":%s,"band":"%s","gen":"%s","signal":%s},' \
    "$wifi_ssid" "$wifi_ip" "${wifi_freq:-0}" "$wifi_band" "$wifi_gen" "${wifi_signal:-0}"
  printf '"ethernet":{"state":"%s","ip":"%s","speed":"%s","interface":"%s"},' \
    "$eth_state" "$eth_ip" "$eth_speed" "${eth_iface:-}"
  printf '"usb":{"interface":"%s","ip":"%s"}}\n' \
    "${usb_iface:-}" "$usb_ip"
}

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