#!/usr/bin/env bash
# shellcheck shell=bash

# check dependencies
# if ! command -v system_profiler >/dev/null 2>&1; then
#   echo "#[fg=red]system_profiler not found" >&2
#   exit 1
# fi

# if ! command -v jq >/dev/null 2>&1; then
#   echo "#[fg=red]jq not found; brew install jq" >&2
#   exit 1
# fi

red() { printf '\e[31m%b\e[0m\n' "$*"; }

# retrieve JSON data
json=$(system_profiler -json SPAirPortDataType -detailLevel basic 2>/dev/null)
if [ -z "${json}" ]; then
  # echo "#[fg=red]offline"
  red "offline"
  exit 1
fi

# detect active interface
# shellcheck disable=SC2312
interfaces=$(
  jq -r '
  .SPAirPortDataType[0]
  .spairport_airport_interfaces[]
  | select(.spairport_current_network_information._name != null)
  | ._name
' <<EOF
${json}
EOF
)
iface=$(echo "${interfaces}" | head -n 1)

if [ -z "${iface}" ]; then
  # echo "#[fg=red]offline"
  red "offline"
  exit 1
fi

# extract SSID, RSSI, and transmit rate
ssid=$(
  jq -r --arg IF "${iface}" '
  .SPAirPortDataType[0]
  .spairport_airport_interfaces[]
  | select(._name == $IF)
  | .spairport_current_network_information._name
' <<EOF
${json}
EOF
)

# shellcheck disable=SC2312
rssis=$(
  jq -r --arg IF "${iface}" '
  .SPAirPortDataType[0]
  .spairport_airport_interfaces[]
  | select(._name == $IF)
  | .spairport_current_network_information.spairport_signal_noise
' <<EOF
${json}
EOF
)
rssi=$(echo "${rssis}" | awk '{ print $1 }')

rate=$(
  jq -r --arg IF "${iface}" '
  .SPAirPortDataType[0]
  .spairport_airport_interfaces[]
  | select(._name == $IF)
  | .spairport_current_network_information.spairport_network_rate
' <<EOF
${json}
EOF
)

# build signal strength blocks
signals='▂▅▇'
signal=""
for idx in "${!signals[@]}"; do
  threshold=$((idx == 0 ? -100 : idx == 1 ? -80 : -50))
  if [ "${rssi}" -gt "${threshold}" ]; then
    signal+="${signals[idx]}"
  fi
done

# handle no connection
if [ "${rate}" = 0 ]; then
  # echo "#[fg=red]no_wifi"
  red "no_wifi"
  exit 1
fi

# output formatted for tmux status-right
printf '\033[0;97m%s\033[0m \033[32;1m%b\033[0m %b' "${ssid}" "${rate}Mbps" "${signal}"
