summaryrefslogtreecommitdiffstats
path: root/mdkapplet
blob: f2bd4d556df6ed85ad3616cb38a630a36fbb0218 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
#!/usr/bin/perl
################################################################################
# Mandriva Online                                                              # 
#                                                                              #
# Copyright (C) 2003-2006 Mandriva                                             #
#                                                                              #
# Daouda Lo                                                                    #
# Thierry Vignaud <tvignaud at mandriva dot com>                               #
#                                                                              #
# This program is free software; you can redistribute it and/or modify         #
# it under the terms of the GNU General Public License Version 2 as            #
# published by the Free Software Foundation.                                   #
#                                                                              #
# This program is distributed in the hope that it will be useful,              #
# but WITHOUT ANY WARRANTY; without even the implied warranty of               #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                #
# GNU General Public License for more details.                                 #
#                                                                              #
# You should have received a copy of the GNU General Public License            #
# along with this program; if not, write to the Free Software                  #
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.   #
################################################################################

use strict;
use POSIX ":sys_wait_h";
use Config;
use lib qw(/usr/lib/libDrakX);
use standalone; # for explanations
use interactive;
use common;
use run_program;

use Gtk2::Pango;

BEGIN { unshift @::textdomains, 'mdkonline' }

use mygtk2 qw(gtknew); #- do not import gtkadd which conflicts with ugtk2 version
use ugtk2 qw(:all);
use lib qw(/usr/lib/libDrakX/drakfirsttime);
use mdkonline;
use Gtk2::TrayIcon;
use Gtk2::NotificationBubble;

# POSIX unmasks the sigprocmask properly
my $sigset = POSIX::SigSet->new;
my $action = POSIX::SigAction->new('restart_applet',
                                   $sigset,
                                   &POSIX::SA_NODEFER);
POSIX::sigaction(&POSIX::SIGHUP, $action);

if (!find { $_ eq '--auto-update' } @ARGV) {
    if (my $pid = mdkonline::is_running('mdkapplet')) {
        die "mdkapplet already running ($pid)\n";
    }
}

my $in = interactive->vnew('');

ugtk2::add_icon_path("/usr/share/mdkonline/pixmaps/");
my $online_site = "https://www.mandrivaonline.com/";
my ($menu, $timeout, $eventbox, $img, $mLog, $buffer, $textview, $wlog, $textvw, $state_global, $MW_vbox);
my ($raisedwindow, $debug, $conf_launched) = (0, 0, 0);
my $applet_window;


my $conffile = '/etc/sysconfig/mdkonline';
my $localdir = "$ENV{HOME}/.MdkOnline";
my $localfile = "$localdir/mdkonline";

my $release = mdkonline::get_release();


my %config = getVarsFromSh('/etc/sysconfig/mdkapplet');
$config{UPDATE_FREQUENCY} ||= 3*60*60; # default to 3hours
$config{FIRST_CHECK_DELAY} ||= 25 * 1000; # default to 25 seconds

sub my_sprintf_fixutf8 {
    mdkonline::get_release() < 2006.0 ? common::sprintf_fixutf8(@_) : @_;
}


my $insensitive_while_running_a_child;

#compatibility
mkdir_p($localdir) if !-d $localdir;
-e "$ENV{HOME}/.mdkonline" and system("mv", "$ENV{HOME}/.mdkonline", $localfile);

my %state = (
	     delayed => {
		      colour => [ 'busy' ],
		      changes => [ 'busy', 'critical', 'disconnected' ],
		      menu => [ 'check', 'weblink' ],
		      tt => [
                    #-PO: here %s will be replaced by the local time (eg: "Will check updates at 14:03:50"
                    N("Will check updates at %s", POSIX::strftime("%T", localtime(time() + $config{FIRST_CHECK_DELAY}/1000)))
                ],
                      #localtime(time() + 
		     },
    
	     okay => {
		      colour => [ 'okay' ],
		      changes => [ 'busy', 'critical', 'disconnected' ],
		      menu => [ 'check', 'weblink' ],
		      tt => [ N_("Your system is up-to-date") ]
		     },
 	     critical => {
		      colour => [ 'noconf' ],
		      changes => [ 'okay', 'busy', 'critical', 'disconnected' ],
		      menu => [ 'check', 'weblink' ],
		      tt => [ N_("Service configuration problem. Please check logs and send mail to support\@mandrivaonline.com") ]
		     },
	     busy => {
		      colour => [ 'busy' ], 
		      changes => [ 'okay', 'critical', 'error', 'disconnected' ],
		      menu => [],
		      tt => [ N_("Please wait, finding available packages...") ]
		     },
	     updates => {
		      colour => [ 'error' ],
		      changes => [ 'okay' ],
		      menu => [ 'update', 'check', 'weblink' ],
		      tt => [ N_("New updates are available for your system") ]
		     },
	     bundles => {
		      colour => [ 'bundle' ],
		      changes => [ 'okay' ],
		      menu => [ 'update', 'check', 'weblink' ],
		      tt => [ N_("New bundles are available for your system") ]
		      },
	     noconfig => {
		      colour => [ 'noconf' ],
		      changes => [ 'okay' ],
		      menu => [ 'weblink', 'register' ],
		      tt => [ N_("Service is not configured. Please click on \"Configure the service\"") ]
		     },
	     disconnected => {
		      colour => [ 'disconnect' ],
		      changes => [ 'okay', 'busy', 'critical', 'error' ],
		      menu => [ 'confNetwork' ],
		      tt => [ N_("Network is down. Please configure your network") ]
		     },
	     disabled => {
		      colour => [ 'disabled' ],
		      changes => [ 'okay', 'busy', 'critical', 'error' ],
		      menu => [ 'weblink' ],
		      tt => [ N_("Service is not activated. Please click on \"Online Website\"") ]
		     },
          locked => {
		      colour => [ 'noconf' ],
		      changes => [ 'okay', 'busy', 'critical', 'disconnected' ],
		      menu => [ 'check', 'weblink' ],
                tt => [ N_("urpmi database locked") ],
          },
	     notsupported => {
		      colour => [ 'disabled' ],
		      changes => [ 'okay', 'busy', 'critical', 'error' ],
		      menu => [ 'weblink' ],
		      tt => [ N_("Release not supported (too old release, or development release)") ]
		     },
          no_update_medium => {
		      colour => [ 'noconf' ],
		      changes => [ 'okay', 'busy', 'critical', 'disconnected' ],
		      menu => [ 'check', 'weblink' ],
                tt => [ N_("No medium found. You must add some media through 'Software Media Manager'.") ],
          },
          no_enabled_medium => {
		      colour => [ 'noconf' ],
		      changes => [ 'okay', 'busy', 'critical', 'disconnected' ],
		      menu => [ 'check', 'weblink' ],
                tt => [ N("You already have at least one update medium configured, but
all of them are currently disabled. You should run the Software
Media Manager to enable at least one (check it in the \"%s\"
column).

Then, restart \"%s\".", N("Enabled"), 'mdkapplet') ],
          },
	    );

my %comm_codes = (
    locked => {
        code => 2,
        status => 'locked',
        log => N_("urpmi database locked") . ", skipping updating urpmi database",
    },
    error_updating => {
        code => 3,
        status => 'critical',
        log => N_("Error updating media"),
    },
    no_update_medium => {
        code => 4,
        status => 'no_update_medium',
        log => "no update media configured",
    },
    no_enabled_medium => {
        code => 5,
        status => 'no_enabled_medium',
        log => "all update media are disabled",
    },
    updates => {
        code => 6,
        status => 'updates',
        log => N_("Checking... Updates are available\n") . "\n",
    },
    uptodate => {
        code => 7,
        status => 'okay',
        log => N_("Packages are up to date") . "\n",
    },
    db_not_open => {
        code => 8,
        status => 'critical',
        log => N_("Failed to open urpmi database") . "\n",
    },
);

my %actions = (
	       'update' => { name => N("Install updates"), launch => sub { installUpdates() } },
	       'configureApplet' => { name => N("Configure the service"), launch => sub { configure() } },
	       'check' => { name => N("Check Updates"), launch => sub { 
				my $_w = $in->wait_message(N("Please wait"), N("Check updates") . '...');
				checkUpdates();
                } },
	       'weblink' => { name => N("Online WebSite"), launch => sub { mdkonline::get_site($online_site, 'info.php') } },
	       'confNetwork' => { name => N("Configure Network"), launch => sub { configNetwork() } },
	       'register' => { name => N("Configure Now!"), launch => sub { configure() } }
	      );

gtkadd(my $icon = Gtk2::TrayIcon->new("MdkApplet"), 
       gtkadd($eventbox = Gtk2::EventBox->new, 
	      gtkpack($img = Gtk2::Image->new)
	     )
      );
#$icon->shape_combine_mask($img, 0, 0);
$eventbox->signal_connect(button_press_event => sub {
				  if ($_[1]->button == 1) {
                          my %actions = (
                              no_update_medium => sub { fork_exec('/usr/sbin/edit-urpm-sources.pl') },
                              no_enabled_medium => sub { fork_exec('/usr/sbin/edit-urpm-sources.pl') },
                              updates => \&installUpdates,
                          );
                          $actions{$state_global}->() if ref $actions{$state_global};
			      } elsif ($_[1]->button == 3) {
                         $menu and $menu->popup(undef, undef, undef, undef, $_[1]->button, $_[1]->time);
                     }
			  });
my ($opt) = @ARGV;
if ($opt eq '--force' || $opt eq '-f') { setAutoStart('TRUE') }
if ($opt eq '--debug') { $debug = 1 }

shouldStart() or die "$localfile should be set to TRUE: please use --force or -f option to launch applet\n";

$icon->show_all;
go2State('delayed');
gtkflush();
checkConfig();
Glib::Timeout->add($config{FIRST_CHECK_DELAY}, sub { checkUpdates(); 0 });
setup_cyclic_check();


$SIG{USR1} = 'IGNORE';
$SIG{USR2} = 'IGNORE';
$SIG{CHLD} = \&harvester;

Gtk2->main;

ugtk2::exit(0);

my ($mdv_update_pid, $checker_pid);

# Signal management 
sub harvester {
    my ($_signame, $clean) = @_;
    my ($childpid, @pids);
    my $mdvupdate_returned;
    do {
        $childpid = waitpid(-1, &WNOHANG);
        if ($mdv_update_pid && $mdv_update_pid == $childpid) {
            undef $mdv_update_pid;
            $mdvupdate_returned = 1;
        } elsif ($checker_pid && $checker_pid == $childpid) {
            undef $checker_pid;
            my $status = $? >> 8;
            my ($state) = grep { $_->{code} eq $status } values %comm_codes;
            if ($state) {
                logIt($state->{log});
                go2State($state->{status});
            }
        }
        push @pids, $childpid;
        WIFEXITED($?) and refresh_gui(1);
    } while $childpid > 0;
    Glib::Timeout->add(200, sub { silentCheck(); 0 }) if $mdvupdate_returned;
    return @pids;
}
sub fork_exec {
    my $pid = run_program::raw({ detach => 1 }, @_);
    refresh_gui(1);                                                                        
    return $pid;
}
sub refresh_gui {
    my ($sens) = @_;
    #!$conf_launched and silentCheck(); $conf_launched = 0;
    my $w = $::main_window ? $::main_window->window : undef;
    $insensitive_while_running_a_child = !$sens;
    $sens ? gtkset_mousecursor_normal($w) : gtkset_mousecursor_wait($w);
    $MW_vbox and $MW_vbox->set_sensitive($sens);
    gtkflush();
}

sub showMainWindow() {
    my $w = $applet_window = Gtk2::Window->new('toplevel');
    $::main_window = $w;
    $w->set_title(N("Mandriva Linux Updates Applet"));
    $w->signal_connect(delete_event => sub { $w->destroy; $raisedwindow = 0 });
    gtkset_size_request($w, 400, 300);
    $w->set_position('center');
    $w->set_icon(Gtk2::Gdk::Pixbuf->new_from_file('/usr/share/icons/mini/mdkonline.png'));
    $textvw = Gtk2::TextView->new;
    $textvw->set_wrap_mode('word');
    gtkadd($w,
           gtkpack_($MW_vbox = Gtk2::VBox->new(0, 5),
		    0, gtkadd(gtkset_shadow_type(Gtk2::Frame->new(N("Actions")), 'etched_in'),
			      gtkpack_(Gtk2::VBox->new(0, 3),
				       1, gtksignal_connect(Gtk2::Button->new(N("Install updates")), clicked => sub { installUpdates() }),
				       1, gtksignal_connect(Gtk2::Button->new(N("Configure")), clicked => sub { configure() }),
				       1, gtksignal_connect(Gtk2::Button->new(N("Check updates")), clicked => sub {
								my $w = $in->wait_message(N("Please wait"), N("Check updates") . '...');
								checkUpdates(); undef $w }),
				       1, gtksignal_connect(Gtk2::Button->new(N("See logs")), clicked => sub { if (defined $wlog) { $wlog->{window}->show } else { $wlog = displayLogs(); $wlog->main } }),
				      )
			     ),
		    1, gtkadd(gtkset_shadow_type(Gtk2::Frame->new(N("Status")), 'etched_in'),
			    gtkpack_(Gtk2::VBox->new(0, 3),
				 1, create_scrolled_window(gtktext_insert($textvw, refresh_contents($state_global))))),
		    0, gtkpack(Gtk2::HSeparator->new),
		    0, gtkpack(gtksignal_connect(Gtk2::Button->new(N("Close")), clicked => sub {
						     if (defined $wlog) { $wlog->destroy; undef $wlog }
						     $w->destroy; $raisedwindow = 0;
						 })
			      )
		   )
	  );
    $w->show_all;
    gtkflush();
}
sub setLabel {
    my ($widget, $string) = shift;
    $widget->set_label($string) if defined $widget;
    gtkflush();
}
sub refresh_status {
    my $status = shift;
    gtktext_insert($textvw, refresh_contents($status));
}
sub refresh_contents {
    my $status = shift;
    my $color = {};
    my %h = getVarsFromSh($conffile); 
    foreach my $l (['first', 'red'], ['second', 'royalblue3'], ['third', 'green']) { 
	$color->{$l->[0]} = { 'foreground' => $l->[1], 'weight' => Gtk2::Pango->PANGO_WEIGHT_BOLD };
    }
    my $fixed_tag = { 'font' => 'monospace' };
    setLastTime();
    my $last = lastCheck();
    my $contents = [ [ N("Network Connection: "), $color->{second} ], [ isNetwork() ? N("Up") . "\n" : N("Down") . "\n", isNetwork() ? $color->{third} : $color->{first} ],
		     [ N("Last check: "), $color->{second} ], [ "$last\n", $fixed_tag ],
		     [ N("Machine name:"), $color->{second} ], [ $h{HOST_NAME} . "\n", $fixed_tag ],
		     [ N("Updates: "), $color->{second} ], [ my_sprintf_fixutf8($state{$status}{tt}[0]), $status eq 'okay' ? $color->{third} : $color->{first} ],
		   ];
    $contents;
}
sub configNetwork() { logIt(N_("Launching drakconnect\n")); refresh_gui(0); fork_exec("/usr/sbin/drakconnect") }

sub restart_applet() {
    logIt(N_("Mandriva Online seems to be reinstalled, reloading applet ...."));
    exec($0, '--auto-update');
}

sub installUpdates() {
    my $binfile = $0;
    return if $mdv_update_pid;
    my $oldmd5 = $release <= 10.2 ? mdkonline::md5file($binfile) : common::md5file($binfile);
    logIt(N_("Launching MandrivaUpdate\n"));
    refresh_gui(0);
    $mdv_update_pid = fork_exec('MandrivaUpdate', '--no-media-update', '--no-confirmation');
    my $newmd5 = $release <= 10.2 ? mdkonline::md5file($binfile) : common::md5file($binfile);
    restart_applet() if $newmd5 ne $oldmd5;
    #my $w = $in->wait_message(N("Please wait"), N("Check updates"));
    silentCheck(); gtkflush();
    #undef $w;
    my $mdkupdate_status = cat_('/var/tmp/mdkupdate.log');
    if ($mdkupdate_status && $mdkupdate_status !~ /OK/) { logIt($mdkupdate_status); $in->ask_warn(N("Mandriva Linux Updates Applet"), $mdkupdate_status) }
}
sub silentCheck() {
    return if $mdv_update_pid || $checker_pid;
    my %h = getVarsFromSh($conffile); 
    my $u;
    logIt(N_("Computing new updates...\n"));
    logIt(N_("Connecting to") . "  ...\n"); # i18n bug to fix in cooker
    my $w = $::main_window ? $::main_window->window : undef;
    gtkset_mousecursor_wait($w);
    gtkflush(); go2State('busy'); gtkflush();
    gtkset_mousecursor_normal($w) if !$insensitive_while_running_a_child;
    my $response = eval { mdkonline::soap_is_new_update_for_distro($h{HOST_ID}, $h{HOST_KEY}) };
    $response = { code => 0, data => { isUpdateAvailable => 1 } };
    my $status_err = mdkonline::check_server_response($response);
    if ($status_err eq 'OK') {
        # are there any updates ?
        my $data = $response->{data};
        if ($data && $data->{isUpdateAvailable}) {
            $checker_pid = fork();
            if (defined $checker_pid) {
                return if $checker_pid; # parent

                # immediate exit, else forked gtk+ object destructors will badly catch up parent applet
                my $_safe = before_leaving { POSIX::_exit(0) };
                my $exit = sub {
                    my ($state) = @_;
                    POSIX::_exit($comm_codes{$state}{code});
                };
                my $will_not_update_media;
                require urpm;
                require urpm::lock;
                my $urpm = urpm->new;
                {
                    local $urpm->{fatal} = sub {
                        print "Fatal: @_\n";
                        $will_not_update_media = 1;
                    };
                    local $urpm->{error} = $urpm->{fatal};

                    urpm::lock::urpmi_db($urpm, 'exclusive', 1);
                }
                $exit->('locked') if $will_not_update_media;

                if (my $res = !run_program::raw({ sensitive_arguments => 1 }, 'urpmi.update', '--update')) {
                    $exit->('error_updating') if $will_not_update_media;
                }

                require urpm::select;
                require urpm::media;
                urpm::media::configure($urpm, update => 1);
                my @update_medias = grep { $_->{update} } @{$urpm->{media}};
                if (!@update_medias) {
                    $exit->('no_update_medium');
                } elsif (!grep { ! $_->{ignore} } @update_medias) {
                    $exit->('no_enabled_medium');
                }

                if (my $db = urpm::db_open_or_die($urpm)) {
                    my $h = $urpm->request_packages_to_upgrade($db, {}, {});
                    
                    if (my @pkgs = grep { !$_->flag_skip } map { $urpm->{depslist}[$_] } keys %$h) {
                        $exit->('updates');
                    } else {
                        $exit->('uptodate');
                    }
                } else {
                    $exit->('db_not_open');
                }
                $exit->('updates');
            } else {
                logIt("cannot fork: %s", "update checker ($!)");
                go2State('critical');
            }
        } else {
            logIt(N_("An error occurred"));
        }
    } else {
    #   99 - log or host or action or pass empty, wrong action
    #   98 - wrong pass
    #   97 - host not active
    logIt("Returned value after association (silentCheck)= $u\n") if $debug;
    my $retcode = {
		   94 => sub { logIt(N_("Development release not supported by service")); go2State('notsupported') },
		   95 => sub { logIt(N_("Too old release not supported by service")); go2State('notsupported') },
		   96 => sub { logIt(N_("Unknown state")); go2State('critical') },
		   97 => sub { logIt(N_("Online services disabled. Contact Mandriva Online site\n")); go2State('disabled') },
		   98 => sub { logIt(N_("Wrong Password.\n")); go2State('critical') },
		   99 => sub { logIt(N_("Wrong Action or host or login.\n")); go2State('critical') },
                   500 => sub { logIt(N_("Something is wrong with your network settings (check your route, firewall or proxy settings)\n")); go2State('critical') }
		  };
    eval { $retcode->{$response->{code}}->() }; if ($@) { logIt(N_("Problem occured while connecting to the server, please contact the support team")); go2State('critical') }
    }
    if ($debug) {
     require Data::Dumper;
	logIt(N_("Response from Mandriva Online server\n") . Data::Dumper->Dumper($response));
    }
}
sub okState() { logIt(N_("System is up-to-date\n")); go2State('okay') }
sub compareWithInstalled {
    my ($name, $ver, $rel, $t) = @_;
    my $isUpdate = 0;
    foreach my $p (@$t) { 
	my ($n, $v, $r) = $p =~ /(.*)-(.*)-(.*)$/;
	if ($name eq $n) {
	    my ($iu, $ir);
	    if ($debug) { $iu = mdkonline::rpm_ver_cmp($ver, $v); $ir = mdkonline::rpm_ver_cmp($rel, $r) } 
	    if (mdkonline::rpm_ver_cmp($ver, $v) > 0 || mdkonline::rpm_ver_cmp($ver, $v) == 0 && mdkonline::rpm_ver_cmp($rel, $r) > 0) {
		logIt("$name-$ver-$rel $n-$v-$r *** CMPVER=$iu ** CMPREL = $ir \n") if $debug;
		$isUpdate = 1 and last;
	    }
	}
    }
    $isUpdate;
}
sub setup_cyclic_check() {
    Glib::Timeout->add(10*1000, sub {
	checkConfig();
	1;
    });
    $timeout = Glib::Timeout->add($config{UPDATE_FREQUENCY}*1000, sub {
	   my $first_run if 0;
	   if (!$first_run) {
		  $first_run = 1;
		  return 1;
	   }

				      checkUpdates();
				      1;
				  });
}
sub lastCheck() {
    my %h = getVarsFromSh($localfile);
    my $t = $h{LASTCHECK};
    $t =~ s/_/  /g;
    $t || N("No check");
}
sub getTime() {
    my $d = localtime();
    $d =~ s/\s+/_/g;
    $d;
}
sub setLastTime() {
    my $date = getTime();
    setVar($localfile, 'LASTCHECK', $date);
}
sub checkConfig() {
    if (!-e $conffile) {
	my $logged if 0;
	logIt(N_("Checking config file: Not present\n")) if !$logged;
	$logged = 1;
    } elsif (!isNetwork()) {
	logIt(N_("Checking Network: seems disabled\n"));
	go2State('disconnected');
    } elsif (member($state_global, qw(disconnected noconfig))) {
	silentCheck(); #- state has changed, update
    }
}
sub checkUpdates() {
    member($state_global, qw(disconnected noconfig)) or silentCheck();
}
sub go2State {
    my $state = shift;
    $menu->destroy if $menu;
    $menu = setState($state);
    $state_global = $state;
    defined $textvw and refresh_status($state);
}
sub isNetwork() {
    my $network;
    if ($release <= 10.0) {
	$network = gethostbyname("mandrivaonline.com") ? 1 : 0;
    } elsif ($release <= 10.2) {
	require network::netconnect;
 	require network::tools;
	my ($netcnx, $netc, $intf) = ({}, {}, {});
    	network::netconnect::read_net_conf($netcnx, $netc, $intf);
	my ($_gw_intf, $_is_up, $gw_address, $_dns_server) = network::tools::get_internet_connection($netc, $intf);
	$network = to_bool($gw_address);
    } else {
	require network::network;
	require network::tools;
	my $net = {};
    	network::network::read_net_conf($net);
	my ($_gw_intf, $_is_up, $gw_address, $_dns_server) = network::tools::get_internet_connection($net);
	$network = to_bool($gw_address);
    }
    $network;
}
sub configure() {
    refresh_gui(0);
    fork_exec("/usr/sbin/mdkonline");
    $conf_launched = 1;
}
sub displayLogs() {
    my $w = ugtk2->new(N("Logs"), center => 1);
    gtkset_size_request($w->{window}, 500, 400);
    $w->{window}->signal_connect(delete_event => sub { $w->destroy; undef $wlog });
    $textview = Gtk2::TextView->new;
    $buffer = $textview->get_buffer;
    gtkadd($w->{window},
	   gtkpack_(Gtk2::VBox->new(0, 2),
		    1, create_scrolled_window(gtktext_insert($textview, $mLog)),
		    0, Gtk2::HSeparator->new,
		    0,  gtkpack_(Gtk2::HBox->new(0, 5),
				 0, gtksignal_connect(Gtk2::Button->new(N("Close")), 
						      clicked => sub { 
							  $w->destroy;
							  undef $wlog;
						      }),
				 1, Gtk2::Label->new(""),
				 0, gtksignal_connect(Gtk2::Button->new(N("Clear")),
						      clicked => sub {
							  $mLog = '';
							  $buffer->set_text($mLog);
						      }),
				)));
    $w;
}
sub shouldStart() {
    my %p = getVarsFromSh($localfile);
    my $ret = $p{AUTOSTART} eq 'FALSE' ? 0 : 1;
    $ret;
}
sub setState {
    my $state_type = shift;
    my $checkme;
    my $arr = $state{$state_type}{menu};
    my $tmp = gtkcreate_pixbuf($state{$state_type}{colour}[0]);
    $img->set_from_pixbuf($tmp);
    #my $tooltip = Gtk2::Tooltips->new;
    gtkset_tip(new Gtk2::Tooltips, $eventbox, formatAlaTeX(my_sprintf_fixutf8(translate($state{$state_type}{tt}[0]))));
    my $menu = Gtk2::Menu->new;
    foreach (@$arr) { 
	$menu->append(gtksignal_connect(gtkshow(Gtk2::MenuItem->new_with_label($actions{$_}{name})), activate => $actions{$_}{launch}));
    }
    $menu->append(gtkshow(Gtk2::SeparatorMenuItem->new));
    $menu->append(gtksignal_connect(gtkshow(Gtk2::MenuItem->new_with_label(N("About..."))), activate => sub {
                                        my $ver = 1; # automatically set from spec file
                                        my $url = $online_site;
                                        $url =~ s/^https:/http:/;
                                        my $w = gtknew('AboutDialog', name => N("Mandriva Online %s", $ver),
                                                       version => $ver,
                                                       copyright => N("Copyright (C) %s by Mandriva", '2001-2006'),
                                                       license => join('', cat_('/usr/share/common-licenses/GPL')), wrap_license => 1,
                                                       icon => '/usr/share/icons/mini/mdkonline.png',
                                                       comments => N("Mandriva Online gives access to Mandriva web services."),
                                                       website => $url,
                                                       website_label => N("Online WebSite"),
                                                       authors => 'Thierry Vignaud <vignaud@mandriva.com>',
                                                       artists => 'Hélène Durosini <ln@mandriva.com>',
                                                       translator_credits =>
                                                         #-PO: put here name(s) and email(s) of translator(s) (eg: "John Smith <jsmith@nowhere.com>")
                                                         N("_: Translator(s) name(s) & email(s)\n"),
                                                       transient_for => $::main_window, modal => 1, position_policy => 'center-on-parent',
                                                   );

                                        $w->show_all;
                                        $w->run;
                                        return 1;

                                    }));
    $menu->append(gtksignal_connect(gtkset_active($checkme = Gtk2::CheckMenuItem->new_with_label(N("Always launch on startup")), shouldStart()), toggled => sub { setAutoStart(uc(bool2text($checkme->get_active))) }));
    $checkme->show;
    $menu->append(gtksignal_connect(gtkshow(Gtk2::MenuItem->new_with_label(N("Quit"))), activate => sub { mainQuit() }));
    $menu;
}
sub logIt {
    my $log = shift;
    my ($Second, $Minute, $Hour, undef, undef, undef, undef, undef, undef) = localtime();
    $mLog .= $Hour . ':' . $Minute . ':' . $Second . '  ' . translate($log);
    if (defined $wlog) { $buffer->insert_at_cursor($log) }
    log::explanations($log);
}
sub setVar {
    my ($file, $var, $st) = @_;
    my %s = getVarsFromSh($file);
    $s{$var} = $st;
    setVarsInSh($file, \%s);
}
sub setAutoStart {
    my $state = shift;
    my $date = getTime();
    if (-f $localfile) {
	setVar($localfile, 'AUTOSTART', $state);
    } else { output_p $localfile, 
	       qq(AUTOSTART=$state
LASTCHECK=$date
);
	 }
}
sub mainQuit() {
#    setAutoStart('FALSE');
    Glib::Source->remove($timeout) if $timeout;
    Gtk2->main_quit;
}