#!/usr/bin/bash
# ======================================================================
#
# DNS search in infoblox API
#
# ----------------------------------------------------------------------
# 2021-10-29  v1.0  <axel.hahn@iml.unibe.ch>
# 2022-01-14  v1.0  <axel.hahn@iml.unibe.ch>  1st public version
# 2022-03-01  v1.1  <axel.hahn@iml.unibe.ch>  fix usage with 1st param "name"
# 2022-03-03  v1.2  <axel.hahn@iml.unibe.ch>  no param: 2 searches in name and alias
# 2022-06-14  v1.3  <axel.hahn@iml.unibe.ch>  added search for cname objects; debug comments are written to stderr 
# 2022-09-13  v1.4  <axel.hahn@iml.unibe.ch>  add search for ip address; fix cname as 1st param
# ======================================================================

returnFields='&_return_fields%2B=aliases,ttl'

# ----------------------------------------------------------------------
# HELP
# ----------------------------------------------------------------------
if [ -z "$1" ] || [ "$1" = "-h" ]; then
cat <<EOH

Search for hostnames or aliases in Infoblox API
It uses dns-api.sh and adds the return field for aliases.

SYNTAX: dns-search.sh [name|alias|cname|ipv4addr] REGEX

EXAMPLES:

(1)
search for a hostname / A record
    dns-search.sh name www.iml.unibe.ch

(2)
search for CNAME - use "alias" as 1st parameter
    dns-search.sh alias www.ufive.ch

(3)
The search supports regex:
    dns-search.sh name ^assets
    dns-search.sh name "^(connector|examinator).*measured.stage"

(4)
search for an IP - use "ipv4addr" as 1st parameter
    dns-search.sh ipv4addr .79.30

(5)
Lazy mode: do not add name or alias or cname to start 4 requests to search 
in all object types
    dns-search.sh ufive

EOH
exit 0
fi

# ----------------------------------------------------------------------
# MAIN
# ----------------------------------------------------------------------
mytype=
if echo "$1" | grep -E '^(name|alias|cname|ipv4addr)$' >/dev/null
then
    mytype=$1
    shift 1
fi


mysearch=$1

# ----------------------------------------------------------------------

>&2 echo ";"
>&2 echo "; === INFOBLOX DNS SEARCH"
>&2 echo ";"
>&2 echo "; search for type : $mytype"
>&2 echo "; search regex    : $mysearch"
>&2 echo ";"
if [ -n "$mytype" ]; then
    test "$mytype" = "cname" || "$( dirname $0 )"/dns-api.sh GET "/record:host?${mytype}~=${mysearch}${returnFields}"
    test "$mytype" = "cname" && "$( dirname $0 )"/dns-api.sh GET "/record:cname?name~=${mysearch}&_return_fields%2B=ttl"
else
    for mytype in name alias ipv4addr
    do
        "$( dirname $0 )"/dns-api.sh GET "/record:host?${mytype}~=${mysearch}${returnFields}"
    done
    "$( dirname $0 )"/dns-api.sh GET "/record:cname?name~=${mysearch}&_return_fields%2B=ttl"
fi

# ----------------------------------------------------------------------