#!/bin/bash
#
# Print the "best" IP for the tmux status bar.
# Preference: DO reserved/floating IP > public egress (ipify) > first local IP.
#

set -u

META="http://169.254.169.254/metadata/v1"
CURL="curl -sf --connect-timeout 1 --max-time 2"

is_digitalocean() {
  [ -r /sys/class/dmi/id/sys_vendor ] \
    && grep -qi digitalocean /sys/class/dmi/id/sys_vendor
}

do_anchor_ip() {
  local kind active ip
  for kind in reserved_ip floating_ip; do
    active=$($CURL "$META/$kind/ipv4/active" 2>/dev/null) || continue
    [ "$active" = "true" ] || continue
    ip=$($CURL "$META/$kind/ipv4/ip_address" 2>/dev/null) || continue
    [ -n "$ip" ] && { printf '%s\n' "$ip"; return 0; }
  done
  return 1
}

if is_digitalocean && do_anchor_ip; then
  exit 0
fi

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

ip=$(curl -s --connect-timeout 3 https://api.ipify.org 2>/dev/null || true)
[ -z "${ip:-}" ] && ip=$(print_local_ip)
printf '%s\n' "${ip:-}"
