#!/bin/sh
# Resolve a catalogue's local name through the existing stock service.
# The session's cancellable command runner bounds the complete request.
set -eu
fail() { printf '%s\n' "$*" >&2; exit 1; }
[ "$#" -eq 1 ] || fail 'One local host name is required.'
name=$(printf '%s' "$1" | tr 'A-Z' 'a-z')
case "$name" in ''|[-.]*|*[!a-z0-9.-]*) fail 'That local host name is not valid.' ;; esac
case "$name" in *.local) ;; *) fail 'Use a host name ending in .local.' ;; esac
[ "${#name}" -le 253 ] || fail 'That local host name is too long.'
resolver=${INKHUB_RESOLVECTL:-/usr/bin/resolvectl}
[ -x "$resolver" ] || fail 'Local name lookup is not available. Use the catalogue IP address.'
reply=$("$resolver" -4 --legend=no --protocol=mdns query "$name") || fail "$name could not be found. Check that it is on the same network."
printf '%s\n' "$reply" | awk '
    NF >= 2 {
        n=split($2,a,"."); valid=(n==4)
        for(i=1;i<=n;i++) if(a[i] !~ /^[0-9]+$/ || a[i]+0>255) valid=0
        if(valid) {print $2; found=1; exit}
    }
    END {if(!found) exit 1}
' || fail "$name did not return an IPv4 address."
