#!/usr/bin/env zsh

function get_time_ms {
  date -u +%s%3N
}

icons=("󰤯" "󰤟" "󰤢" "󰤥" "󰤨")

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

function toggle() {
  status=$(rfkill | grep wlan | awk '{print $4}')

  if [ "$status" = "unblocked" ]; then
    rfkill block wlan
  else
    rfkill unblock wlan
  fi
}

function gen_wifi() {
  wifi_iface=$(get_wifi_interface)
  signal=$(awk -v iface="$wifi_iface" '$1 == iface ":" { print $3; exit }' /proc/net/wireless)
  level=$(awk -v n="$signal" 'BEGIN{print int((n-1)/20)}')
  if [ "$level" -gt 4 ]; then
    level=4
  fi

  icon=${icons[$level]}
  ip="-"
  class="net-connected"
  name_raw=$(wpa_cli -g "/run/wpa_supplicant/$wifi_iface" status | grep \^ssid= | sed 's/ssid=//g')
  name=$(printf "%s" "$name_raw")
}

function gen_ethernet() {
  icon="󰈀"
  class="net-connected"
  ip=""
  name=Wired
}

function make_content() {
  local ethernet wifi wifi_iface
  ethernet=$(ip link | rg "^[0-9]+: en[po]+" | head -n1 | sed 's/[a-zA-Z0-9_,><:\ -]*state //g' | sed 's/ mode [a-zA-Z0-9 ]*//g')
  wifi_iface=$(get_wifi_interface)
  if [ -n "$wifi_iface" ]; then
    wifi=$(wpa_cli -g "/run/wpa_supplicant/$wifi_iface" status | rg "^wpa_state=" | sed 's/wpa_state=//g')
  fi

  # test ethernet first
  if [[ $ethernet == "UP" ]]; then
    gen_ethernet
  elif [[ $wifi == "COMPLETED" ]]; then
    gen_wifi
  else
    icon="󰤮"
    ip="-"
    class="net-disconnected"
    name="Disconnected"
  fi

  echo '{"icon": "'$icon'", "name": "'$name'", "ip": "'$ip'", "class": "'$class'"}'
}

if [ "$1" = "toggle" ]; then
  toggle
else
  last_time=$(get_time_ms)
  make_content
  ip monitor | while read -r _; do
    current_time=$(get_time_ms)
    delta=$((current_time - last_time))
    if [[ $delta -gt 50 ]]; then
      make_content
      last_time=$(get_time_ms)
    fi
  done
fi
