#!/usr/bin/env bash
# cleat: {"name":"IP Address","keyword":"ip","icon":"network","subtitle":"Copy a local or public IP address","version":"1.1.1","requires":["curl"],"examples":["ip "]}
set -euo pipefail

if [ "${1:-}" = "--run" ]; then
    printf '%s' "$2" | pbcopy
    exit 0
fi

for iface in en0 en1 en2; do
    ip="$(ipconfig getifaddr "$iface" 2>/dev/null || true)"
    if [ -n "$ip" ]; then
        printf '{"title":"%s","subtitle":"Local · %s","arg":"%s"}\n' "$ip" "$iface" "$ip"
    fi
done

# -f: an error page or a captive portal's HTML is not an address, and its
# quotes would break the JSON row.
public="$(curl -fsS --max-time 1.5 https://api.ipify.org 2>/dev/null || true)"
if [[ "$public" =~ ^[0-9a-fA-F.:]+$ ]]; then
    printf '{"title":"%s","subtitle":"Public","arg":"%s"}\n' "$public" "$public"
fi
