#!/bin/zsh
# ^^ does not work in bash for some reason. Dunno why.

host=${1:?Need host}
port=${2:-9618}

command -v nc &>/dev/null || { echo "nc not found" >&2; exit 127; }

header=$'\x01'                                  # CEDAR header
length=$'\x00\x00\x00\x08'                      # 8 bytes
dc_command=$'\x00\x00\x00\x00\x00\x00\xea\x8d'  # 60045 which is DC_QUERY_INSTANCE

OLDIFS=$IFS
IFS=
printf "%s" "${header}" "${length}" "${dc_command}" | nc "${host}" "${port}" | read -r response
IFS=$OLDIFS
response_payload=${response#?????}  # skip first 5 bytes

if [[ $response_payload =~ ^[a-z0-9]{16}$ ]]; then
    printf "ok: instance ID %s\n" "$response_payload"
    exit 0
else
    echo "unexpected response:"
    xxd <<<"$response"
    exit 1
fi
