#!/usr/bin/perl

$version = "4";

# sert à l'automatisation des updates du côté serveur
if ($#ARGV == 0) {
	if ($ARGV[0] eq "v") {
		print "$version";
		exit;
	}
}


$server_host = shift;
$TIMEOUT = shift;
$ask = shift;
chomp $ask;
$options = shift;
chomp $options;

if ($TIMEOUT eq "") {
  print "Il faut au moins 3 paramètres :";
  print "\t1° paramètre = 'host' = adresse IP ou nom de serveur";
  print "\n";
  print "\t2° paramètre = 'timeout' = délai d'attente en secondes";
  print "\n";
  print "\t\texprimé en 'virgule flottante' : doit contenir un point : ex. : 0.1";
  print "\n";
  print "\t\texprimé en 'virgule flottante' : jusqu'à la nanoseconde !";
  print "\n";
  print "\t3° paramètre = nom du fichier dont on demande le contenu";
  print "\n";
  print "\n";
  print "\t4° paramètre (optionnel) = 'd' pour 'debug' : affichage des étapes";
  print "\t";
  print "\n";
  exit;
}

use IO::Socket;
use Time::HiRes;

$nom_du_script = $0;
# $0 est une variable prédéfinie qui contient la commande qui a lancée l'exdecution du script
$nom_du_script =~ s/.*\///;
# enlever l'éventuel chemin précédant le nom du script


sub ifdprint {
($string) = @_;
  if ($options ne "") {
    if ($options =~ /d/) {
    # si le script est exécuté avec l'option 'd' pour ('debug')
	  print "$nom_du_script : $string";
    }
  }
}

$hdnb = `/bin/cat /etc/hd.nb`;
$msg = "$ask $hdnb";


$local_PORTNO  = 52001;
$server_PORTNO  = 52000;
$MAXLEN  = 1024;

&ifdprint ("création du socket pour le transfert 'udp'\n");
# création du socket pour le transfert 'udp'
$sock = IO::Socket::INET->new(Proto     => 'udp',
                              LocalPort => $local_PORTNO,
                              PeerPort  => $server_PORTNO,
                              PeerAddr  => $server_host)
    or die "Creating socket: $!\n";

# transmettre $ask par udp :	
&ifdprint ("envoi du message au serveur\n");

$start = Time::HiRes::time;

eval {
    local $SIG{ALRM} = sub { die "alarm time out" };
    Time::HiRes::alarm ($TIMEOUT);
$sock->send($msg) or die "send: $!";
    Time::HiRes::alarm 0;
    1;  # return value from eval on normalcy
}  or &ifdprint ("send to $server_host timed out after $TIMEOUT seconds.\n");

$after = Time::HiRes::time;
$relatif = $after - $start;
&ifdprint ("after = $relatif\n");


# attendre la réponse udp :	
&ifdprint ("attente de la réponse du serveur\n");

$start = Time::HiRes::time;
eval {
    local $SIG{ALRM} = sub { die "alarm time out" };
    Time::HiRes::alarm ($TIMEOUT);
    $sock->recv($answer, $MAXLEN)      or die "recv: $!";
    Time::HiRes::alarm 0;
    1;  # return value from eval on normalcy
} or &ifdprint ("recv from $server_host timed out after $TIMEOUT seconds.\n");


$after = Time::HiRes::time;
$relatif = $after - $start;
&ifdprint ("after = $relatif\n");


&ifdprint ("Server $server_host $PORTNO responded '$answer'\n");
