#!/usr/bin/env python3
# scripts/resolve_tenant_ip.py
# stdin: `openstack server show -f json` output ; env FIP=<floating ip address>
# Print the server's tenant (fixed) IP -- the address that is NOT the floating IP.
# A single-NIC VM has exactly the two once a FIP is attached; before that, the lone
# fixed IP is returned (FIP unset/empty matches nothing, so the first address wins).
# Robust to both the OSC value shape {"net": ["ip", ...]} and the dict shape
# {"net": [{"addr": "ip"}, ...]} and the comma-joined string shape "ip1, ip2".
import os, json, sys

def addrs_to_ips(addrs):
    ips = []
    for v in (addrs or {}).values():
        if isinstance(v, list):
            for item in v:
                if isinstance(item, str):
                    ips.append(item.strip())
                elif isinstance(item, dict) and item.get("addr"):
                    ips.append(str(item["addr"]).strip())
        elif isinstance(v, str):
            ips.extend(x.strip() for x in v.split(",") if x.strip())
    return [ip for ip in ips if ip]

def main():
    try:
        data = json.load(sys.stdin)
    except Exception:
        return ""
    fip = os.environ.get("FIP", "").strip()
    for ip in addrs_to_ips(data.get("addresses", {})):
        if ip != fip:
            return ip
    return ""

if __name__ == "__main__":
    print(main())
