#!/usr/local/bin/perl

# This is a very simple whois client, but it knows the new server arguments
# No support yet, use if you wish

require "getopts.pl";

$whoishost = "whois.ripe.net";
$port = 43;
$AF_INET = 2;
$SOCK_STREAM = 1;

&Getopts('ah:FrLmMSs:Ut:T:');

if ($#ARGV < 0 && !$opt_t && !$opt_U) {
    print <<"EOF";
usage: whois [-aFrSv] [-h hostname] [-s source] [-T type] [-L|-m|-M] key ...
       whois -t type
where:
-a		search all databases
-F		fast raw output (implies -Fr)
-h hostname	search alternate server
-L		find all Less specific matches
-m		find first level More specific matches
-M		find all More specific matches
-r		turn off recursive lookups
-s source	search databases with source "source"
-S		tell server to leave out "syntactic sugar"
-U logstr	do updates
-t type		requests template for object of type "type"
-T type		only look for objects of type "type"

Please note that most of these flags are NOT understood by
non RIPE whois servers
EOF
	exit(0);
}

if ($opt_h) { $whoishost = $opt_h; }

$sockaddr = 'S n a4 x8';
($name, $aliases, $type, $len, $thataddr) = gethostbyname($whoishost);
$that = pack($sockaddr, $AF_INET, $port, $thataddr);
socket(S, $AF_INET, $SOCK_STREAM, $proto) || die "socket failed\n";
connect(S, $that) || die "Connect failed\n";
select(S); $| = 1; select(STDOUT);

if ($opt_U) {
	if ($child = fork) {
		print S "-U $ENV{'LOGNAME'}\n" if $ENV{'LOGNAME'};
		print S "-U nologname\n" unless $ENV{'LOGNAME'};
		while(<STDIN>) {
			last if /^\.\s*$/;
			print S;
		}
		print S "\n.\n";
		exit;
	}
	else {
		while(<S>) {
			print;
		}
		exit;
	}
}
	

if ($opt_L) {
    print STDERR "whois: warning -L overrides -m\n" if $opt_m;
    print STDERR "whois: warning -L overrides -M\n" if $opt_M;
    $opt_m = 0;
    $opt_M = 0;
}
if ($opt_m) {
    print STDERR "whois: warning -m overrides -M\n" if $opt_M;
    $opt_M = 0;
}

if ($opt_t) {
    print S "-t $opt_t\n";
} else {
    if ($opt_a) { print S "-a ";}
    if ($opt_F) { print S "-F ";}
    if ($opt_L) { print S "-L ";}
    if ($opt_m) { print S "-m ";}
    if ($opt_M) { print S "-M ";}
    if ($opt_r) { print S "-r ";}
    if ($opt_S) { print S "-S ";}
    if ($opt_s) { print S "-s $opt_s ";}
    if ($opt_T) { print S "-T $opt_T ";}
    foreach $i (0 .. $#ARGV) {
	print S $ARGV[$i], " ";
    }
    print S "\n";
}

while (<S>) {
	print;
}
