use Irssi;
use Socket;

my($webchatserver, $webhatchanname, $webchatnick, $webchathost, $webchatjoindelaytag);

sub print_realhost {
        my ($server, $channame, $nick, $host) = @_;

#       if("$server" eq "foo") {
#               Irssi::timeout_remove($webchatjoindelaytag);
#       };              
#       if($webchatjoindelaytag) {
#               Irssi::timeout_remove($webchatjoindelaytag);
#               $server = $webchatserver;
#               $channame = $webchatchanname;
#               $nick = $webchatnick;
#               $host = $webchathost;
#               $webchatjoindelaytag = unset;
#               $webchatserver = unset;
#               $webchatchanname = unset;
#               $webchatnick = unset;
#               $webchathost = unset;
#       };

        $host =~ /(.*)@(.*)/;
        my $hostname = webhost_resolve($1);
        if ($hostname) {
                $server->print($channame, "-!- ".$nick."'s real hostname: ".$hostname, MSGLEVEL_CLIENTCRAP);
        };
};

sub print_webhost {
        my ($server, $webhost) = @_;
        my $hostname = webhost_resolve($webhost);
        $server->print("status", "-!- ".$webhost." = ".$hostname, MSGLEVEL_CLIENTCRAP);
};

sub webhost_resolve {
        $_ = @_[0];
        if (/.?([a-f]|[0-9]){8}$/) {
                /.?(..)(..)(..)(..)$/;
                my $ipaddr = hex($1).".".hex($2).".".hex($3).".".hex($4);
                my $hostname = gethostbyaddr(inet_aton($ipaddr), AF_INET);
                if ("$hostname" eq "") {
                        $hostname = $ipaddr;
                };
                return $hostname;
        } else {
                return 0;
        };
};

sub msg_join {
        my ($server, $channame, $nick, $host) = @_;
#       $webchatjoindelaytag = Irssi::timeout_add(200, "print_realhost", "foo");
#       $webchatserver = $server;
#       $webchatchanname = $channame;
#       $webchatnick = $nick;
#       $webchathost = $host;
        print_realhost(@_);
};

sub cmd_webchat {
        my ($nick, $server) = @_;
        return if !$nick;
        $server->redirect_event("userhost", 1, $nick, 0, "", { "event 302" => "redir webchat host" } );
        $server->send_raw("USERHOST :$nick");
        $_ = $nick;
        if (/.?([a-f]|[0-9]){8}$/) {
                print_webhost($server, $nick);
        };
};

sub sig_userhost {
        my ($server, $data) = @_;
        $data =~ s/^[^ ]* :?//;
        if ($data =~ /^([^=\*]*)\*?=.(.*@.*)/) {
                my $nick = lc($1);
                my $userhost = $2;
                if($userhost) {
                        print_realhost($server, "status", $nick, $userhost);
                };
        };      
};

Irssi::command_bind("webchat", "cmd_webchat");
Irssi::signal_add_last("message join", "msg_join");
Irssi::signal_add("redir webchat host", "sig_userhost");

