#!/usr/local/bin/perl -Tw
# plgrenouille 0.70       -- don't forget to update Grenouille::Vars
# version 0.4 by momtchev, <momtchev@fil.univ-lille1.fr>
# modified by Pierre Etchemaite, <petchema@concept-micro.com>

# This software may be used and distributed according to the terms
# of the GNU General Public License, incorporated herein by reference.

require 5.004;
use strict;
#use diagnostics;
use Getopt::Long qw(GetOptions);
use Fcntl qw(O_RDONLY);
#use IO::Handle qw();
use Time::HiRes qw(time sleep);
use Net::Ping qw();
use Net::FTP qw();

use Grenouille::Vars qw(%VERSION %DEBUG
                        $MYRC $DATAPATH $DOWNLOADFILE $UPLOADFILE $QUEUEFILE
                        $LASTCONFIGFILE $LASTVERSIONFILE $PIDFILE
			$BEFOREFILE $AFTERFILE
                        $ASAP $SEC $MIN $DAY
                        %vars);
use Grenouille::Numbers qw(digits jitter);
use Grenouille::Log qw(open_log mark_log close_log display_and_log
                       set_log_level set_verbose_level);
use Grenouille::Scheduler qw(schedule_event get_next_event);
use Grenouille::Preferences qw(%preferences 
                               get_preferences ask_preferences);
use Grenouille::Queue qw(init_result_queue load_result_queue queue_result
                         send_results);
use Grenouille::Config qw(load_config store_config %config);
use Grenouille::Comm qw(contact_server pick_host_addr $SERVERNAME);
use Grenouille::Version qw(display_version check_last_version); 
use Grenouille::System qw(init_privileges swap_privileges
                          autodetect_interface get_traffic_counters);

$ENV{'PATH'} = '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin';

# ---------------------------------------------------------------

sub usage($) {
    my($exitcode) = @_;
    print <<"EOUSAGE";
Usage: $VERSION{'client'} [-c|--configure] [-b|--background] [-h|-?|--help]
              [[-l |--log=]priorit] [[-v |--verbose=]priorit]

priorit: [debug | info | notice | warning | error]

--configure: (re)configuration
--background: passe en dtach
--log: change le niveau de dtail du log (def. notice)
--verbose: change le niveau de dtail de l'affichage (def. info)
--help: cette aide

EOUSAGE
    exit($exitcode);
}

sub init_grenouille() {
    init_privileges();

    unless (-d $DATAPATH) {
	swap_privileges();
	eval {
	    mkdir $DATAPATH, 0755;
	    chown $<, -1, $DATAPATH;
	};
	swap_privileges();
    }
    die "$DATAPATH n'existe pas!" unless -d $DATAPATH;
# more runtime checks here ?
}

# lame scrambling algorithm
sub crypt_pass($) {
    my ($pass) = lc shift;
    my ($seed, $i, $p, $c, $crypt);
    
    $seed = 'pasfaciledetrouverlaclefpourouvrirlaporte';
    $crypt = '';
    for ($i = 0; $i < length $pass; $i++) {
	$p = ord(substr($pass, $i, 1));
	$c = ord(substr($seed, $i, 1));
	if ($p >= ord('a') and $p <= ord('z')) {
	    $crypt = chr(($p + $c) % 26 + ord('a')) . $crypt;
	}
	elsif ($p >= ord('0') and $p <= ord('9')) {
	    $crypt = chr(($p + $c) % 10 + ord('0')) . $crypt;
	}
	else {
	    $crypt = '_' . $crypt;
	}
    }
    
    return $crypt;
}

# pretty-print a FTP URL
sub ftp_url($$$) {
    my($site, $path, $filename) = @_;
    my($result) = "$site/$path/$filename";
    $result =~ s!^/+!!;
    $result =~ s!//+!/!g;
    return "ftp://$result";
}

# --------------------------- INITIALISATION ----------------------------

my (%params);

sub init_vars() {
    init_result_queue();
    load_result_queue();
}

# --------------------------- INTERFACE ----------------------------

sub interface_up() {
    if($preferences{'interface'}) {
	eval {
	    # will fail if the interface disappeared under us
	    my($dummy) = get_traffic_counters($preferences{'interface'});
	};
	if ($@) {
	    display_and_log('NOTICE', "L'interface $preferences{'interface'} a disparu: $@");
	    delete $preferences{'interface'};
            delete $vars{'ip'};
	}
    }
    if(not $preferences{'interface'}) {
        ($preferences{'interface'}, $vars{'ip'}) = autodetect_interface();
        display_and_log('NOTICE', "$preferences{'interface'} sera utilis pour les mesures") if $preferences{'interface'};
    }

    return $preferences{'interface'};
}

# --------------------------- EVENT HANDLERS ----------------------------

sub open_session($) { # EVENT
    my($schedule_time) = shift;
    return if $vars{'id'};
    
    # the server wants to know the IP (from our pov), check the interface
    # earlier than we used to
    interface_up();

    my($pass, %answer);
    $pass = crypt_pass($preferences{'pass'});
    eval {
	%answer = contact_server("command=hello&username=$preferences{'user'}&password=$pass&system=$VERSION{'system'}&client=$VERSION{'client'}&version=$VERSION{'version'}" . ($VERSION{'beta'} ? "&beta=$VERSION{'beta'}" : '') . "&ip=$vars{'ip'}");
    };
    if(not $@) {
	display_and_log('INFO', "Ouverture de session");
	$vars{'id'} = $answer{'id'};
	schedule_event($ASAP, \&read_config);
        schedule_event($ASAP, \&send_results);
	schedule_event($ASAP, \&check_last_version);
    } else {
	display_and_log('WARNING', "Ouverture de session impossible pour l'instant ($@)");
	schedule_event($schedule_time + jitter(5 * $MIN, 0, 5), \&open_session);
	# for now, run tests with saved parameters
	schedule_event($ASAP, \&read_config);
    }
}

sub _eqhash($$) {
    my($rh1, $rh2) = @_;
    return 0 unless scalar keys %$rh1 == scalar keys %$rh2;
    my($k, $v);
    while(($k, $v) = each %$rh1) {
	return 0 unless exists $rh2->{$k} and ($rh2->{$k} eq $v);
    }
    return 1;
}

sub read_config($) { # EVENT
    my($schedule_time) = shift;
    my ($modified) = 0;
    if($vars{'id'}) {
	my(%newconfig);
	eval {
	    %newconfig = contact_server("command=get_config&id=$vars{'id'}");
	};
	if (not $@) {
	    $modified = not _eqhash(\%config, \%newconfig);
	    if($modified) {
		%config = %newconfig;
		store_config(\%config, $LASTCONFIGFILE);
	    }
	    schedule_event($schedule_time + $config{'config_timetolive'} * $SEC, \&read_config);
	} else {
	    display_and_log('WARNING', "Impossible d'obtenir des paramtres de configuration  jour pour l'instant !");
	    schedule_event(time() + jitter(10 * $MIN, 0, 5), \&read_config);
	}
    }

    # old config is better than no config;
    # also, we do not reschedule, open_session should be already scheduled
    # and it will in turn schedule read_config 
    if(not scalar %config) {
	%config = load_config($LASTCONFIGFILE);
	if(scalar %config) {
	    $modified = 1;
	    display_and_log('INFO', 'Utilisation de la configuration sauvegarde');
	}
    }

    if($modified) {
	display_and_log('INFO', 'Prise en compte des paramtres');
	if ($config{'ul_host'} and 
	    (not (-f $UPLOADFILE) or 
	     ((-s $UPLOADFILE) != $config{'ul_size'} * 1024))) {
	    my($i,$j);
	    display_and_log('INFO', "Cration d'un fichier de $config{ul_size} Ko pour les tests d'envoi...");
	    eval {
		open(DUMMY, ">$UPLOADFILE") or die "impossible d'ouvrir $UPLOADFILE: $!";
		for($i=0;$i < $config{'ul_size'};$i++) {
		    my($buffer) = '';
		    for($j=0;$j < 1024;$j++) {
			# we use random bytes to defeat any link compression
			$buffer .= pack('C', rand 256);
		    }
		    print DUMMY $buffer or die "impossible d'crire dans $UPLOADFILE: $!";
		}
		close(DUMMY);
	    };
	    if ($@) {
		display_and_log('ERROR', $@);
		delete $config{'up_host'};
	    }
	}

	# schedule optimistically all tests
	schedule_event($ASAP, \&test_ping);
	schedule_event($ASAP, \&test_dl);
	schedule_event($ASAP, \&test_ul);
	schedule_event($ASAP, \&test_breakdown);
    }
}

sub before_test() {
# stop or pause processes that could interfere with bandwidth measurements,
# etc.
    if(-x '$BEFOREFILE') {
	eval {
	    system '$BEFOREFILE';
	};
	display_and_log('ERROR', "plgrenouille-before: $@") if $@;
    }
}

sub after_test() {
# revert anything done by before_test()
    if(-x '$AFTERFILE') {
	eval {
	    system '$AFTERFILE';
	};
	display_and_log('ERROR', "plgrenouille-after: $@") if $@;
    }
}

sub test_ping($) { # EVENT
    my($schedule_time) = shift;
    return unless $config{'ping_host'};
    if(not interface_up()) {
	schedule_event(time() + jitter(1 * $MIN, -1, 1), \&test_ping);
	return;
    }
    display_and_log('INFO', "Ping de $config{'ping_host'}...");
    my($h) = pick_host_addr($config{'ping_host'});
    if(not $h) {
	display_and_log('WARNING', 'Serveur DNS indisponible ?');
	schedule_event(time() + jitter(5 * $MIN, 0, 5), \&test_ping);
	return;
    }
    
    before_test();
    my ($p);
    swap_privileges();
    $p = Net::Ping->new('icmp', 5, length($config{'ping_string'}));
    swap_privileges();
    # ugly, but Net::Ping doesn't allow to specify the string
    $p->{"data"} = $config{'ping_string'};

    my($sent, $received, $total_time) = (0, 0, 0);
    while($sent < $config{'ping_quantity'}) {
	my($start_time, $stop_time);
	$sent++;
	$start_time = time();
	if ($p->ping($h)) {
	    $stop_time = time();
	    $total_time += $stop_time - $start_time;
	    $received++;
	}
	else {
	    display_and_log('INFO', "Ping de $config{'ping_host'} perdu");
	}
	sleep(jitter(1 * $SEC, -1, 1) / $SEC);
    }
    $p->close();
    $total_time /= $SEC;
    after_test();
	
    queue_result("command=post_ping&sent=$sent&received=$received&total_time=" . digits($total_time*1000, 2));
	
    my($lost, $rtt);
    $lost = digits((1- $received / $sent) * 100, 1);
    $rtt = $received ? digits($total_time*1000 / $received,0) . ' ms' : 'N/A';
    display_and_log('LOG', "PING host=$config{'ping_host'} sent=$sent received=$received total_time=" . digits($total_time*1000, 2));
    display_and_log('DISPLAY', "Pings OK, RTT $rtt, perdu $lost%");
	
    schedule_event($schedule_time + jitter($config{'ping_frequency'} * $SEC, -1, 1), \&test_ping);
}

# credit: man perlfaq4
# fisher yates shuffle: generate a random permutation of array in place
sub shuffle($) {
    my($array) = $_[0];
    my($i);
    for ($i = scalar @$array; --$i; ) {
        my($j) = int rand ($i+1);
        @$array[$i,$j] = @$array[$j,$i] unless $i == $j;
    }
}

my $ALIVETRIES ||= 5;

sub test_breakdown($) { # EVENT
    my($schedule_time) = shift;
    return unless scalar %config;
    if(not interface_up()) {
	schedule_event(time() + jitter(1 * $MIN, 0, 5), \&test_breakdown);
	return;
    }

    before_test();
    # parse breakdown_host into an arrayref
    my(@list_to_go) = map { s/^\s+//; s/\s+$//; $_ } split(/,/, $config{'breakdown_host'});
    return unless scalar @list_to_go;
    # not required by specs, but adds to the fun
    shuffle(\@list_to_go);

    my ($p, $host, $alive);
    swap_privileges();
    $p = Net::Ping->new('icmp', 5, length($config{'ping_string'}));
    swap_privileges();
    # ugly, but Net::Ping doesn't allow to specify the string
    $p->{"data"} = $config{'ping_string'};
    $alive = 0;

  HOSTS: foreach $host (@list_to_go) {
      display_and_log('INFO', "Ping d'une adresse ($host)...");
      my($h) = pick_host_addr($host);
      if(not $h) {
	  display_and_log('WARNING', 'Serveur DNS indisponible ?');
      } else {
	  my($tries);
	  for($tries=0;$tries < $ALIVETRIES; $tries++) {
	      if($p->ping($h)) {
		  $alive = 1;
		  last HOSTS;
	      }
	      sleep(jitter(1 * $SEC, -1, 1) / $SEC);
	  }
      }
  }
    $p->close();
    after_test();
    
    if (not $alive) {
	# we exhausted the list, none replied
	display_and_log('LOG', "BREAKDOWN link=down hosts=$config{'breakdown_host'}");
	display_and_log('DISPLAY', 'La connexion semble morte !');
	queue_result("command=post_breakdown");
    } else {
	display_and_log('LOG', 'BREAKDOWN link=up');
	display_and_log('DISPLAY', 'Connexion OK');
    }

    schedule_event($schedule_time + jitter($config{'breakdown_frequency'} * $SEC, -1, 1), \&test_breakdown);
}

my $TIMEOUT_DL ||= 120;

sub test_dl($) { # EVENT
    my($schedule_time) = shift;
    return unless $config{'dl_host'};
    if(not interface_up()) {
	schedule_event(time() + jitter(1 * $MIN, 0, 5), \&test_dl);
	return;
    }
    display_and_log('DISPLAY', 'Chargement de ' . ftp_url($config{'dl_host'}, $config{'dl_path'}, $config{'dl_file'}) . '...');
    my($h) = pick_host_addr($config{'dl_host'});
    if(not $h) {
	display_and_log('WARNING', 'Serveur DNS indisponible ?');
	schedule_event(time() + jitter(1 * $MIN, 0, 5), \&test_dl);
	return;
    }
    
    before_test();
    my ($dl, $start_time, $stop_time, $success,
	$start_traffic_counters, $stop_traffic_counters,
	$dl_bandwidth, $dl_total_bandwidth, $ul_total_bandwidth,
	$ratio_same_direction, $ratio_opposite_direction,
	$local_file, @file_stats);
    
    $success = 0;
    $dl = undef;
    eval {
        local $SIG{ALRM} = sub { die 'timeout' };
        alarm $TIMEOUT_DL;

	$dl = Net::FTP->new($h, 'Passive' => $preferences{'passive_ftp'}) or die "Couldn't create Net::FTP object";
	$dl->login('anonymous', $preferences{'email'}) or 
	    die "Login failure at $config{'dl_host'}";
	$dl->cwd($config{'dl_path'}) or
	    die "Can't change directory to $config{'dl_path'}";
	$dl->binary() or
	    die "Can't change transfer mode to binary";
	$start_traffic_counters = get_traffic_counters($preferences{'interface'});
	$start_time = time();
	{
	    # ugly, avoid a "use of undefined variable" at Net::FTP::I.pm:29
	    local $SIG{__WARN__} = sub { };
	    $local_file = $dl->get($config{'dl_file'}, $DOWNLOADFILE) or
		die "Can't open remote file $config{'dl_file'}";
	}
	$stop_time = time();
	$stop_traffic_counters = get_traffic_counters($preferences{'interface'});
	$success = 1;
        alarm 0;
    };
    alarm 0;
    $dl->quit() if defined $dl;
    display_and_log('ERROR', $@) if $@;
    if ($success and not (@file_stats = stat($local_file))) {
	display_and_log('WARNING', "Fichier tlcharg $local_file incomplet");
	$success = 0;
    }
    unlink $local_file if defined $local_file;
    after_test();
    if ($success) {
	$dl_bandwidth = digits(
           ($file_stats[7] / 1024) / (($stop_time - $start_time) / $SEC), 2);
	$dl_total_bandwidth = digits(
           (($stop_traffic_counters->{'rx'} - $start_traffic_counters->{'rx'}) / 1024)
	    / (($stop_time - $start_time) / $SEC), 2);
	$ul_total_bandwidth = digits(
           (($stop_traffic_counters->{'tx'} - $start_traffic_counters->{'tx'}) / 1024)
	    / (($stop_time - $start_time) / $SEC), 2);
	$ratio_same_direction = int(($dl_total_bandwidth / $dl_bandwidth - 1) * 100);
	$ratio_opposite_direction = int(($ul_total_bandwidth / $dl_bandwidth) * 100);
	
	if (($dl_total_bandwidth < 0) or ($ratio_same_direction < 0)) {
	    display_and_log('WARNING', "compteurs d'octets de l'interface trop faibles, rsultat rejet !");
	    delete $preferences{'interface'};
	    $success = 0;
	}
	if ($ratio_same_direction > $config{'dl_ratiomaxdl'}) {
	    display_and_log('WARNING', 'Traffic descendant trop lev durant le test, rsultat rejet');
	    $success = 0;
	}
	if ($ratio_opposite_direction > $config{'dl_ratiomaxul'}) {
	    display_and_log('WARNING', 'Traffic montant trop lev durant le test, rsultat rejet');
	    $success = 0;
	}
    }
    if ($success) {
#	if ($config{'dl_max'} and ($dl_bandwidth > $config{'dl_max'})) {
#	    display_and_log('WARNING', "Bande passante mesure (${dl_bandwidth} Ko/s) > bande passante maximale prvue ($config{'dl_max'} Ko/s)");
#	    $dl_bandwidth=1.03 * $config{'dl_max'};
#	}
	queue_result("command=post_dl&bandwidth=$dl_bandwidth");
	display_and_log('LOG', "DOWNLOAD bandwidth=$dl_bandwidth ratiodl=$ratio_same_direction ratioul=$ratio_opposite_direction host=$config{'dl_host'}");
	display_and_log('DISPLAY', "Chargement OK, ${dl_bandwidth} Ko/s (ratio dl=$ratio_same_direction%, ratio ul=$ratio_opposite_direction%)");
    }
    if ($success) {
	schedule_event($schedule_time + jitter($config{'dl_frequency'} * $SEC, -1, 1), \&test_dl);
    } else {
	schedule_event($schedule_time + jitter($config{'dl_frequency'} / 2 * $SEC, -1, 1), \&test_dl);
    }
}

my $TIMEOUT_UL ||= 120;

sub test_ul($) { # EVENT
    my($schedule_time) = shift;
    return unless $config{'ul_host'};
    if(not interface_up()) {
	schedule_event(time() + jitter(1 * $MIN, 0, 5), \&test_ul);
	return;
    }
    display_and_log('DISPLAY', 'Envoi de ' . ftp_url($config{'ul_host'}, $config{'ul_path'}, $config{'ul_file'}) . '...');
    my($h) = pick_host_addr($config{'ul_host'});
    if(not $h) {
	display_and_log('WARNING', 'Serveur DNS indisponible ?');
	schedule_event(time() + jitter(1 * $MIN, 0, 5), \&test_ul);
	return;
    }

    before_test();
    my ($ul, $start_time, $stop_time, $success,
	$start_traffic_counters, $stop_traffic_counters,
	$ul_bandwidth, $ul_total_bandwidth, $dl_total_bandwidth,
	$ratio_same_direction, $ratio_opposite_direction,
	$local_file, $remote_size);
    
    $success = 0;
    $ul = undef;
    eval {
        local $SIG{ALRM} = sub { die 'timeout' };
        alarm $TIMEOUT_UL;

	$ul = Net::FTP->new($h, 'Passive' => $preferences{'passive_ftp'}) or die "Couldn't create Net::FTP object";
	$ul->login('anonymous', $preferences{'email'}) or 
	    die "Login failure at $config{'ul_host'}";
	$ul->cwd($config{'ul_path'}) or
	    die "Can't change directory to $config{'ul_path'}";
	$ul->binary() or
	    die "Can't change transfer mode to binary";
	$start_traffic_counters = get_traffic_counters($preferences{'interface'});
	$start_time = time();
	$local_file = $ul->put($UPLOADFILE, $config{'ul_file'}) or
	    die "Can't open remote file $config{'ul_file'}";
#	$remote_size = $ul->size($config{'ul_file'});
#	if (not defined $remote_size) {
#	    display_and_log('WARNING', 'Impossible d'obtenir la taille du fichier envoy, soyons optimistes');
	    $remote_size = $config{'ul_size'} * 1024;
#	}
	$stop_time = time();
	$stop_traffic_counters = get_traffic_counters($preferences{'interface'});
	$success = 1;
        alarm 0;
	$ul->delete($config{'ul_file'});
#	$ul->quit(); $ul = undef;
#	$stop_time = time();
#	$stop_traffic_counters = get_traffic_counters($preferences{'interface'});
    };
    alarm 0;
    $ul->quit() if defined $ul;
    display_and_log('ERROR', $@) if $@;
    if ($success and (defined $remote_size)  and ($remote_size ne $config{'ul_size'} * 1024)) { 
	display_and_log('WARNING', "Envoi de $local_file interrompu");
	$success = 0;
    }
    after_test();
    if ($success) {
	$ul_bandwidth = digits(
           ($remote_size / 1024) / (($stop_time - $start_time) / $SEC), 2);
	$ul_total_bandwidth = digits(
           (($stop_traffic_counters->{'tx'} - $start_traffic_counters->{'tx'}) / 1024)
	    / (($stop_time - $start_time) / $SEC), 2);
	$dl_total_bandwidth = digits(
	   (($stop_traffic_counters->{'rx'} - $start_traffic_counters->{'rx'}) / 1024)
            / (($stop_time - $start_time) / $SEC), 2);
	$ratio_same_direction = int(($ul_total_bandwidth / $ul_bandwidth - 1) * 100);
	$ratio_opposite_direction = int(($dl_total_bandwidth / $ul_bandwidth) * 100);
	
	if (($ul_total_bandwidth < 0) or ($ratio_same_direction < 0)) {
	    display_and_log('WARNING', "compteurs d'octets de l'interface trop faibles, rsultat rejet !");
	    delete $preferences{'interface'};
	    $success = 0;
	}
	if ($ratio_same_direction > $config{'ul_ratiomaxul'}) {
	    display_and_log('WARNING', 'Traffic montant trop lev durant le test, rsultat rejet');
	    $success = 0;
	}
	if ($ratio_opposite_direction > $config{'ul_ratiomaxdl'}) {
	    display_and_log('WARNING', 'Traffic descendant trop lev durant le test, rsultat rejet');
	    $success = 0;
	}
    }
    if ($success) {
#	if ($config{'ul_max'} and ($ul_bandwidth > $config{'ul_max'})) {
#	    display_and_log('WARNING', "Bande passante mesure (${ul_bandwidth} Ko/s) > bande passante maximale prvue ($config{'ul_max'} Ko/s)");
#	    $ul_bandwidth=1.03 * $config{'ul_max'};
#	}
	queue_result("command=post_ul&bandwidth=$ul_bandwidth");
	display_and_log('LOG', "UPLOAD bandwidth=$ul_bandwidth ratioul=$ratio_same_direction ratiodl=$ratio_opposite_direction host=$config{'ul_host'}");
	display_and_log('DISPLAY', "Envoi OK, ${ul_bandwidth} Ko/s (ratio ul=$ratio_same_direction%, ratio dl=$ratio_opposite_direction%)");
	
    }
    if ($success) {
	schedule_event($schedule_time + jitter($config{'ul_frequency'} * $SEC, -1, 1), \&test_ul);
    } else {
	schedule_event($schedule_time + jitter($config{'ul_frequency'} / 2 * $SEC, -1, 1), \&test_ul);
    }
}

sub daemonize() {
    my($f) = fork();
    die "Couldn't fork in background" unless defined $f;
    if($f) {
        # parent
        swap_privileges();
        open(PID, ">$PIDFILE") or die "$PIDFILE: $!";
        print PID "$f\n";
        close PID;
        swap_privileges();
        exit(0);
    } else {
        # child
        chdir('/');
        close STDIN;
        open(STDIN, '</dev/null');
        close STDOUT;
        open(STDOUT, '>/dev/null');
        close STDERR;
        open(STDERR, '>/dev/null');
    }
}

sub RELOADING {
    schedule_event($ASAP, \&load_preferences);
    schedule_event($ASAP, \&read_config);
    $SIG{HUP} = \&RELOADING;
}

# --------------------------- MAIN ----------------------------

Getopt::Long::Configure('bundling'); # 'no_ignore_case'
eval {
  GetOptions(\%params,
             'log|l=s', \&set_log_level,
             'verbose|v=s', \&set_verbose_level,
             'configure|setup|c',
             'background|b',
             'version|V',
             'help|h|?');
};
if ($@) {
  print "$@\n";
  usage(1);
}
usage(1) if scalar @ARGV;
usage(0) if $params{'help'};
if($params{'version'}) {
    display_version();
    exit(0);
}

open_log();
init_grenouille();

eval {
    init_vars();
    if($params{'configure'}) {
	ask_preferences();
	print "Vous pouvez maintenant lancer plgrenouille normalement.\n";
	exit(0);
    }
    get_preferences();
    if($params{'background'}) {
        daemonize();
    }

    schedule_event($ASAP, \&open_session);
# doesn't work as I'd like combined with exceptions :(
# any signal guru reading ?
# $SIG{HUP} = \&RELOADING;

    while (1) {
	my($event_time, $event_action) = @{get_next_event()}{'time', 'action'};
	&$event_action($event_time);
    }
};
display_and_log('ERROR', $@) if $@;

END {
    close_log();
    unlink $PIDFILE if defined $PIDFILE;
}
