#!/usr/bin/perl -s
use MIME::Base64;
use Data::Dumper;

if (!$name||!$password||!$host){
        print "Please supply login,password and host address as follows:\nget_eid.pl -name=LOGIN -password=PASSWORD -host=HOST\n" ;
        exit 1;
}


#Set $SSL_ON = 1 if you wish to use secure connection.
use constant SSL_ON => 0;
use constant CONF_CONNECTION => {
        ip => $host,
        port => &SSL_ON ? 4434 : 4433,
        class => &SSL_ON ? 'IO::Socket::SSL' : 'IO::Socket::INET'
};

eval "use ".&CONF_CONNECTION->{class};
die $@ if $@;

use constant MSG_TERMINATOR => "\0";
local $/ = &MSG_TERMINATOR;

our $socket = &CONF_CONNECTION->{class}->new(
        PeerAddr => &CONF_CONNECTION->{ip},
        PeerPort=> &CONF_CONNECTION->{port},
        Proto => 'tcp',
);
unless($socket) {
die "Connection refused: $!"
}

my $hello = $socket->getline;
chomp($hello);

my $name = encode_base64($name);
my $password = encode_base64($password);
my $request='
<packet version="4.0.0" id="1">
  <data>
    <system>
      <login>
        <name>'.$name.'</name>
        <realm>00000000-0000-0000-0000-000000000000</realm>
        <password>'.$password.'</password>
      </login>
    </system>
  </data>
</packet>
';

$socket->printflush($request.&MSG_TERMINATOR);


my $response = $socket->getline;
chomp($response);

$request=qq~
<packet version="4.0.0" id="2">
<data><system><get_eid/></system></data></packet>
</packet>
~;
$socket->printflush($request.&MSG_TERMINATOR);
$response = $socket->getline;
chomp($response);
$response =~ m|eid\>(.*)\<.*eid\>|gi;
my $eid = $1;
#print "Node EID: ".$eid." \n";
print $eid."\n";
