#!/bin/bash
#
# Print the "best" IP for the tmux status bar.
#
# Shows a directly-held public/WAN IP when the machine has one on an interface,
# otherwise its LAN/private IP. No external "what's my IP" lookup -- a NAT'd box
# shows its LAN IP, never the gateway's egress. Works the same everywhere: a box
# with a public IP on a NIC (incl. a cloud droplet's eth0) shows that WAN IP; a
# NAT'd box shows its LAN IP. The VPN overlay is added separately by tmux-net via
# tmux-vpn-ip and is untouched here.
#

set -u

# This machine's own non-loopback IPv4 addresses, one per line. VPN tunnels are
# excluded (tmux-net surfaces the VPN address separately as the ⇡ segment).
list_ipv4() {
  if command -v ip >/dev/null 2>&1; then
    ip -4 -o addr show scope global 2>/dev/null \
      | awk '$2 !~ /^(tun|wg|ppp|tap)/ {print $4}' | cut -d/ -f1
  elif hostname -I >/dev/null 2>&1; then
    hostname -I 2>/dev/null | tr ' ' '\n'
  else
    ifconfig 2>/dev/null | awk '/inet /{print $2}'
  fi | grep -E '^([0-9]{1,3}\.){3}[0-9]{1,3}$' | grep -v '^127\.'
}

# RFC1918 / link-local / CGNAT -- not a directly-routable WAN address.
is_private_ipv4() {
  case "$1" in
    10.*|192.168.*|169.254.*) return 0 ;;
    172.1[6-9].*|172.2[0-9].*|172.3[01].*) return 0 ;;
    100.6[4-9].*|100.[7-9][0-9].*|100.1[01][0-9].*|100.12[0-7].*) return 0 ;;
    *) return 1 ;;
  esac
}

# First directly-held public/WAN IP, if the machine has one on an interface.
public_ip() {
  local ip
  while IFS= read -r ip; do
    [ -n "$ip" ] || continue
    is_private_ipv4 "$ip" || { printf '%s\n' "$ip"; return 0; }
  done <<EOF
$(list_ipv4)
EOF
  return 1
}

# Fallback: the machine's primary interface IP (covers macOS and odd setups).
print_local_ip() {
  local iface ip
  if command -v ipconfig >/dev/null 2>&1; then
    for iface in en0 en1 en2; do
      ip=$(ipconfig getifaddr "$iface" 2>/dev/null) || true
      [ -n "${ip:-}" ] && { printf '%s\n' "$ip"; return 0; }
    done
  fi
  if hostname -I >/dev/null 2>&1; then
    hostname -I | awk '{print $1}'
    return 0
  fi
  ifconfig 2>/dev/null | awk '/inet /{ if ($2 != "127.0.0.1") { print $2; exit } }'
}

# A directly-held public/WAN IP if the box has one, else the LAN IP.
ip=$(public_ip || true)
[ -z "${ip:-}" ] && ip=$(print_local_ip)
printf '%s\n' "${ip:-}"
