#!/bin/bash

set -euo pipefail

########################### Helpers ###########################################

function yell {
	echo "$@" >&2
}

function die {
	yell "$@"
	exit 1
}

function say {
	if "$verbose" ; then
		yell "$@"
	fi
}

########################### Options ###########################################

verbose=false
if [ "$1" = '-v' ] ; then
	verbose=true
	shift
fi

########################### arguments ##########################################

if [ "$#" -ne 1 ] ; then
	die "Usage: $0 [options] <domain_name>
	  options : -v verbose"
fi

name="$1"

########################### script ############################################

while true ; do
	if "$verbose" ; then
	say "Querying $name"
	fi
	while read line ; do
		if [[ "$line" = *"is an alias for "* ]] ; then
			name="$(echo "$line" | cut -d ' ' -f 6)"
			break
		elif [[ "$line" = *" has address "* ]] ; then
			echo  "$line" | cut -d ' ' -f 4
			exit 0
		elif [[ "$line" = *" not found: "* ]] ; then
			exit 0
		elif [[ "$line" = *" has no A record" ]] ; then
			exit 0
		else
			say "unmatched: $line"
		fi
	done <<< "$(host -W 2 -t A "$name" localhost)"
done