#!/usr/bin/perl
use strict;
use warnings;
use RFC::Main;
use Socket;
use SocketClient;
my $name = shift;
my $address = inet_ntoa(inet_aton($name));
my $port    = get_cv('passwds','passwd_server_port');
$port = shift if (@ARGV);
my %keys;
&load_known_hosts();
foreach my $server ($name,$address)
{
    print $server,"\n";
    my $key = $keys{$server};
    my $remkey = SocketClient::socket_client($server,$port,'public_key');
    unless ($remkey)
    {
	print "Error: Could not get public key from $server!\n";
    }
    if ($key && $remkey)
    {
	my @l = split(/\n/,$remkey);
	pop @l;
	shift @l;
	$remkey = join('',@l);
	my $k1 = substr $key , -16;
	my $k2 = substr $remkey , -16;
	if ($k1 ne $k2)
	{
	    print "WARNING: $server has public key with fingerprint '$k2' but local cached public key for this server has fingerprint '$k1'\n";
	    print "This could potentially mean that a man in the middle attack is taking place, or that the server has been reinstalled and\n";
	    print "Thus a new public key has been generated.\n";
	    print "If the later, then remove key from $server from the known host file /home/celltest/known_hosts\n";
	    next;
	}
    }
    my $res = RFC::Main::passwd_client_raw($server,$port,'ping');
    if ($res)
    {
	print "Communication with $server OK!\n";
    }
}

sub load_known_hosts()
{
    my $state = 0;
    my @list = ();
    my $host_name = '';
    my $ssl_lock = $RFC::Header::homedir.'ssl.lock';
    my $known = SemaforeFile->new($RFC::Header::homedir.'known_hosts',$ssl_lock);
    foreach my $line ($known->readlines())
    {
        if ($state)
        {
            if ($line =~ /^\s*$/)
            {
                $state = 0;
		pop @list;
		shift @list;
		my $str = join('',@list);
                $keys{$host_name} = $str;
                next;
            }
            push @list,$line;
            next;       
        }
        next if ($line =~ /^\s*$/);
        @list = ();
        $host_name = $line;
        $state = 1;
    }
}
