#!/bin/bash

# $Id: whoisvn.sh 10 2008-12-24 05:31:08Z kyanh $

# Domain LookUP (vietnamese support)
# Author: KyAnh <xkyanh at gmail.com>
# License: GPL
# Home: http://viettug.org/wiki/linux/whoisvn


#
# test for curl
#

which curl 2>/dev/null 1>&2

if [ $? -ge 1 ]; then
        echo "cannot locate curl. please install curl first"
        exit 1
fi


#
# test for parameters
#

services=""

case "$1" in
"--matbao")
	services="$services matbao"
	shift
	;;
"--fibo")
	services="$services fibo"
	shift
	;;
"--all")
	services="$services matbao fibo"
	shift
	;;
*)
	services="$services matbao"
	;;
esac


if [ -z "$1" ]; then
	echo "info:"
	echo -e "\tdomain lookup with vietnamese support"
	echo -e "\tauthor: kyanh <xkyanh_at_gmail.com>"
	echo -e "\tlicense: GPL"
	echo -e "\tversion "'$Id: whoisvn.sh 10 2008-12-24 05:31:08Z kyanh $'
	echo -e "\thomepage: http://viettug.org/wiki/linux/whoisvn"
	echo "examples:"
	echo -e "\twhoisvn.sh kyanh.net"
	echo -e "\twhoisvn.sh you.edu.vn me.com.vn viettug.org"
	echo -e "\twhoisvn.sh --fibo kyanh.net yahoo.com google.com"
	echo -e "\twhoisvn.sh xyz."'*'" ( xyz.com, xyz.net, xyz.vn, xyz.com.vn,... )"
	echo -e "options:"
	echo -e "\t--fibo:\tuse http://fibo.com.vn/"
	echo -e "\t--matbao:\tuse http://matbao.net/ (default)"
	echo -e "\t--all:\tuse all available services"
	exit 1
fi

#
# functions
#

#
# report the result
#
lookup_report() {
        if [ "x$1" == "x$2" ]; then
                echo -e "\tregistered"
        else
                echo -e "\tavailable"
        fi
}

#
# to VNNIC: could you support external lookup?
#
lookup_by_vnnic() {
	echo "vnnic doesnot support external lookup"
}

#
# lookup using http://fibo.com.vn/
#
lookup_by_fibo() {
	domain="$1"
	echo -en "fibo.com.vn: ${domain} "
	curl -s \
		-A "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)" \
		--referer "http://google.com/" \
		"http://fibo.com.vn/ff.php?domain=${domain}" \
		| grep -q 0
	lookup_report $? 0
}

#
# lookup using http://matbao.net/
# WARNING: there some typo error in MatBao's result ;)
#
lookup_by_matbao() {
	domain="$1"
	echo -en "matbao.net: ${domain} "
	togrep="<avaiable>False</avaiable>"
	curl -s "http://www.matbao.net/whoisXML.aspx?Domain=${domain}" \
		| grep -qi ${togrep}
	lookup_report $? 1
}

# main routine #

last_names="${WHOISVN_SUFFIX:-com net org info edu biz vn com.vn net.vn org.vn edu.vn info.vn biz.vn}"

while [ ! -z "$1" ]; do
	domain="$1"
	echo $domain | grep -q '\.'
	if [ $? -ge 1 ]; then
		domain="$domain."'*'
	fi

	if [ "x${domain:0 -2}" == 'x.*' ]; then
		domains=""
		for dtd in $last_names; do
			domains="${domains} ${domain%.*}.${dtd}"
		done
	else
		domains="${domain}"
	fi
	
	for domain in $domains; do
		for s in ${services}; do
			lookup_by_${s} "${domain}"
		done
	done

	# next domain
	shift
done

# end of file #

