summaryrefslogtreecommitdiffstats
path: root/mdkonline
blob: cdc2fb45e8541904551521b047a1dceec9837f46 (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
#!/usr/bin/perl
################################################################################
# MandrakeOnline                                                               # 
#                                                                              #
# Copyright (C) 2001-2002-2003-2004 MandrakeSoft                               #
#                                                                              #
# Daouda Lo <daouda@mandrakesoft.com>                                          #
# Renaud Chaillat                                                              #
#
# 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 lib qw(/usr/lib/libDrakX);
use common;
use standalone;
use interactive;

BEGIN { unshift @::textdomains, 'mdkonline', 'drakfw' }
use Config;

#use LWP::Debug qw(+);
use LWP::UserAgent;
use Net::HTTPS;    
use HTTP::Request::Common;
use HTTP::Request;
use Digest::MD5  qw(md5 md5_hex md5_base64);
use MIME::Base64 qw(encode_base64);
use Sys::Hostname;
use ugtk2 qw(:all);

use lib qw(/usr/lib/libDrakX/drakfirsttime);
use comdialog;
use data;

my $confdir = '/root/.MdkOnline';

add_icon_path("/usr/share/drakfirsttime/pixmaps/");

my $in = 'interactive'->vnew('su', 'default');
my $VERSION = '1.0';
my ($create_account, $auto_update) = (0, 0);

my $linkAccount = "http://www.mandrakeexpert.com/index2.php";
my $wideconf = '/etc/sysconfig/mdkonline';

my ($o, $p);

#for compatibilities
mkdir_p($confdir) if !-d $confdir;
mvfiles("/root/.mdkupdate", "$confdir/mdkupdate");
#mvfiles("/root/.mdkonline", "$confdir/mdkonline");

$o->{mw} = ugtk2->new("MandrakeOnline" . " " . $VERSION, center => 1);
gtkset_size_request($o->{mw}{window}, 580, 470);
$o->{mw}{rwindow}->set_position('center');
$o->{mw}{window}->signal_connect( "delete_event", sub { Gtk2->main_quit} );
$o->{nb} = Gtk2::Notebook->new;
$o->{nb}->set_show_tabs(0); $o->{nb}->set_show_border(0);
$o->{bottomHbox} = Gtk2::HBox->new;
my %stage = (
	     0 => sub { if ($o->{account_cb}->get_active) { subsOnline() } else { $o->{nb}->next_page} },
	     1 => sub { $o->{nb}->next_page(); setEntryWithConf() }, 
	     2 => sub { testPasswd() },
	     3 => sub { log::l("[mdkonline] Sending configuration to remote server"); sendConfig() },
	     4 => sub { log::l("[mdkonline] Writing local configuration dir"); setConf() }
	    );
$o->{actions} = {
		 Next => sub {
		     $p = $o->{nb}->get_current_page;
		     $stage{$p}->();
		     $p <= 0 and $o->{Prev}->set_sensitive(1);
		     $p == 4 and mainQuit()
		 },
		 SkipWiz => sub {
		     mainQuit()
		 },
		 Prev => sub {
		     $p = $o->{nb}->get_current_page;
		     $o->{nb}->prev_page();
		     $p <= 1 and init(0)
		 }
		};
foreach my $l (['Next', 'gtk-go-forward', 'stock'], ['SkipWiz', N("Skip Wizard")], ['Prev', 'gtk-go-back', 'stock']) {
    $o->{$l->[0]} = $l->[2] ? Gtk2::Button->new_from_stock($l->[1]) : Gtk2::Button->new(" " . $l->[1] . " ");
    $l->[2] ? $o->{bottomHbox}->pack_end($o->{$l->[0]}, 0, 0, 1) : $o->{bottomHbox}->pack_start($o->{$l->[0]}, 0, 0, 1);
    $o->{$l->[0]}->signal_connect( clicked => sub { $o->{actions}{$l->[0]}->() });
}
gtkadd($o->{mw}{window},
       gtkpack_(Gtk2::VBox->new(0, 2),
		1, $o->{nb},
		0, Gtk2::HSeparator->new,
		0, gtkpack($o->{bottomHbox}),
	       ),
      );
gtkappend_page($o->{nb},
	       gtkpack_(Gtk2::VBox->new(0, 3),
			0, set_darea(N("Welcome to MandrakeOnline"), 'welcome'),
			0, Gtk2::Label->new(N("At this step You are supposed to have an account on MandrakeOnline.\nThis assistant will help you to upload your configuration\n(packages, hardware configuration) to a centralized database in\norder to keep you informed about security updates and useful upgrades.\n")),
			1, gtkadd(Gtk2::Frame->new(N("Create a MandrakeOnline Account")),
				  gtkpack_(Gtk2::VBox->new(0, 3),
					   0, gtksignal_connect(gtkset_active($o->{account_cb} = Gtk2::CheckButton->new(N("I don't have a MandrakeOnline account and I want to ") .  N("Subscribe")), $create_account), clicked => sub { $create_account =! $create_account; $o->{vbox_account}->set_sensitive($create_account) }),
					   1, gtkpack_($o->{vbox_account} = Gtk2::VBox->new(0, 3),
						       1, create_packtable({ homogeneous => 1, col_spacings => 10, row_spacings => 10, mcc => 1 },
									   [],
									   [ N("Login:"), $o->{clogin} = Gtk2::Entry->new(), " " ],
									   [ N("Password:"), $o->{cpasswd} = entry_hidepass(), " " ],
									   [ N("Confirm Password:"), $o->{cconfirm} = entry_hidepass(), " " ],
									   [ N("Mail contact:"), $o->{cmail} = Gtk2::Entry->new() ]
									  ))
					  )
				 ))
	      );
gtkappend_page($o->{nb},
	       gtkpack_(Gtk2::VBox->new(0, 3),
			0, set_darea(N("Mandrakelinux Privacy Policy"), 'privacy'),
			1, create_scrolled_window(gtktext_insert(Gtk2::TextView->new, privacy_text()))
		       )
	      );
gtkappend_page($o->{nb},
	       gtkpack_(Gtk2::VBox->new(0, 3),
			0, set_darea("MandrakeOnline" . " " . N("Authentification"), 'authentification'),
			0, Gtk2::WrappedLabel->new("\n\n" . N("Enter your MandrakeOnline login, password and machine name:")),
			1, create_packtable({ homogeneous => 1, col_spacings => 10, row_spacings => 10, mcc => 1 },
					    [], 
					    [ N("Login:"), $o->{login} = Gtk2::Entry->new(), "" ],
					    [ N("Password:"), $o->{passwd} = entry_hidepass(), "" ],
					    [ N("Machine name:"), $o->{machine} = Gtk2::Entry->new() ],
					   ))
	      );
gtkappend_page($o->{nb},
	       gtkpack_(Gtk2::VBox->new(0, 3),
			0,  set_darea(N("Send Configuration"), 'sendingconf'),
			1, Gtk2::Label->new(N("In order to benefit from MandrakeOnline services,\nwe are about to upload your configuration.\n\nThe Wizard will now send the following information to MandrakeSoft:\n1) the list of packages you have installed on your system,\n2) your hardware configuration.\n\nIf you feel uncomfortable by that idea, or do not want to benefit from this service,\nplease press 'Cancel'. By pressing 'Next', you allow us to keep you informed\nabout security updates and useful upgrades via personalized email alerts.\nFurthermore, you benefit from discounted paid support services on\nwww.mandrakeexpert.com.\nFinally, an email alias with your username\@mandrakeonline.net will be provided to you.")) 
		       )
	      );
gtkappend_page($o->{nb},
	       gtkpack_(Gtk2::VBox->new(0, 3),
			0, set_darea(N("Finish"), 'welcome'),
			1, Gtk2::WrappedLabel->new("\n\n" . N("Your upload was successful!") . "\n\n" . N("From now you will receive on security and updates \nannouncements thanks to MandrakeOnline.") . "\n\n" . N("MandrakeOnline offers you the ability to automate the updates.\nA program will run regulary in your system waiting for new updates\n")),
			0, gtkadd(Gtk2::Frame->new(N("automated Upgrades")),
				  gtkpack_(Gtk2::VBox->new(0, 3),
					   0, gtksignal_connect(gtkset_active($o->{autoup} = Gtk2::CheckButton->new(N("Yes I want automated updates")), $auto_update), clicked => sub { $auto_update =! $auto_update; $o->{vbox_auto}->set_sensitive($auto_update) }),
					   0, gtkpack_($o->{vbox_auto} = Gtk2::VBox->new(0, 3),
						       0, create_packtable({ homogeneous => 1, col_spacings => 5, row_spacings => 5 },
									   [ N("Country:"), $o->{country} = Gtk2::Combo->new ],
									   [" ", " "],
									  ))
					  ))));

init(1);
$o->{country}->set_popdown_strings(sort(getAllCountries()));
$o->{mw}{rwindow}->show_all;

Gtk2->main;
ugtk2->exit(0);

sub subsOnline {
    my $explink = 'http://www.mandrakeexpert.com/online3_CreateAccount.php';
    my $login = $o->{clogin}->get_text;
    my $despwd = $o->{cpasswd}->get_text;
    my $despwdcfm = $o->{cconfirm}->get_text;
    my $cmail = $o->{cmail}->get_text;
    $::error = 0;
    checkErrors($login, $despwd, $despwdcfm, $o->{cmail});
    #    print "Error = $::error";
    if (!$::error) {
	my $url = $explink . '?desuserid=' . $login . '&despwd=' . $despwd . '&user_email=' . $cmail;
	print "LOGIN = $login\nPASSWD = $despwd\nMAIL= $cmail\nURL=$url\n";
	my $ret = requestURL($url);
	my $result = {
		      10 => sub { !$::error and $o->{nb}->next_page},
		      11 => sub { raiseError($o->{mw}->{window},N("Creation"),N("Login and password should be less than 12 characters\n")) },
		      12 => sub { raiseError($o->{mw}->{window},N("Special characters"),N("Special characters are not allowed\n")) },
		      13 => sub { raiseError($o->{mw}->{window},N("Empty fields"),N("Please fill in all fields\n")) },
		      14 => sub { raiseError($o->{mw}->{window},N("Email"),N("Email not valid\n")) },
		      15 => sub { raiseError($o->{mw}->{window},N("Change account"),N("Account already exist\n")) },
		     };
	if ($ret->is_success) {
	    my $content = $ret->content;
#	    print "CODE_RETOUR = $content\n";
	    if ($content =~ m/(\d+)/) { my $code = sprintf("%d",$1); eval { $result->{$code}->() } }
	} else { raiseError($o->{mw}->{window}, N("Server Problem"), N("Problem connecting to server \n")) }
    }
}
sub checkErrors {
    my ($login, $despwd, $despwdcfm, $cmail) = @_;
    $login or raiseError($o->{mw}->{window},N("Error"), N("Please provide a login"));
    if (!$::error && $despwd ne $despwdcfm) {
	raiseError($o->{mw}->{window},N("Error"), N("The passwords do not match\n Please try again\n"))
    } elsif (!$::error and check_valid_email($cmail) != 1) {
	raiseError($o->{mw}->{window},N("Error"), N("Not a valid mail address!\n"))
    }
}
sub setEntryWithConf {
    my %t = getVarsFromSh($wideconf);
    my $host = chomp_(`hostname`) ; $host =~ /(\w+)(.*)/;
    $t{MACHINE} ||= $1;
    foreach (qw(login machine)) { $o->{$_}->get_text or $o->{$_}->set_text($t{uc($_)}) }
}
sub sendConfig {
    # When we arrive here, we're sure the login/passwd is correct
    # print STDERR "Sending config\n";
    my $result = -1; 
    my ($login, $boxname, $passwd);
    $login = $o->{login}->get_text; $boxname = $o->{machine}->get_text; my $passwd = md5_hex($o->{passwd}->get_text);
    reportConfig("$confdir/$login.$passwd.$boxname.online.log");
    `/usr/bin/bzip2 \\\-9 \\\-f $confdir/$login.$passwd.$boxname.online.log`;
    # Turn the binary file into a uuencoded ascii file
    open (FILE, "$confdir/$login.$passwd.$boxname.online.log.bz2") or die "$!";
    my ($chunk, $buffer);
    while (read(FILE, $chunk, 60*57)) {
	$buffer .= $chunk;
    }
    close (FILE);
    open (FILEOUT, "> $confdir/$login.$passwd.$boxname.online.log.bz2.uue") or die "$!";
	print FILEOUT encode_base64($buffer);
    close (FILEOUT);
    my $ua = LWP::UserAgent->new;
    $ua->agent("MdkOnlineAgent/0.15" . $ua->agent);
    $ua->env_proxy;
    my $w = wait_msg(N("Sending configuration..."));
    my $response = $ua->request(POST 'http://www.mandrakeonline.net/wizard.php',

                                Content_Type => 'form-data',
                                Content => [submit => "upload_wizard",
                                            wizard => ["$confdir/$login.$passwd.$boxname.online.log.bz2.uue"]
					   ]);
    #printf("*********** Reponse is %s ***********\n", $response->as_string);
    # Check the outcome of the response
    #print "REPONSE: ".$response->content."\n";
    remove_wait_msg($w);
    if ($response->is_success) {
	$result = ($response->content =~ /^TRUE(.*)/) ? 0 : -1;
	#printf("Send Config :\nNEWKEY=%s\nRESPONSE=%s", $1, $response->content);
	$o->{currentkey} = $1; 
    } else {
	# pb with the connection ?
	$result = -1;
    }
    # if information were sent correctly (exit code: 0 from scp script), go to page 5
    if (! $result) {
	# go to last page
	$o->{nb}->next_page; $o->{Next}->set_label(N("Finish")); $o->{Prev}->hide
    } else {
	# if incorrect, go/stay on page 4 to retry sending data
	# pb with the connection ?
	raiseError($o->{mw}->{window}, N("Connection problem"), N("MandrakeOnline could not be contacted, please try again at a later time"));
    }
}
sub setConf {
    my $login = $o->{login}->get_text;
    my $passwd = md5_hex($o->{passwd}->get_text);
    my $boxname = $o->{machine}->get_text; my $country = getCountry($o->{country}->entry->get_text);
    my $key = $o->{currentkey}; my $auto = 'FALSE';
    if ($o->{autoup}->get_active) { $auto = 'TRUE' }; 
    automatedUpgrades($login, $passwd, $boxname, $key, $country, $auto);
    writeWideConf($login, $boxname, $country);
}
sub init {
    my $i = shift;
    $o->{Prev}->set_sensitive(0); 
    $o->{Next}->grab_focus;
    $i and FirstSettings();
}
sub FirstSettings {
    foreach my $l (qw(vbox_account vbox_auto)) {
       	$o->{$l}->set_sensitive(0);
    }
}
sub final {
    $o->{Prev}->hide; $o->{SkipWiz}->hide;
    $o->{Next}->set_label(N("Finish"))
}
sub getNames {
    my ($login, $passwd, $machine) = @_;
    $login = $o->{login}->get_text;
    $passwd = md5_hex($o->{passwd}->get_text);
    $machine = $o->{machine}->get_text;
    ($login, $passwd, $machine)
}
sub mainQuit {
    # remove local files
    my ($login, $passwd, $boxname) = getNames();
    if ($o->{login}->get_text && $o->{passwd}->get_text) {
	[ -f "$confdir/$login.$passwd.$boxname.online.log.bz2.uue" ] && unlink ("$confdir/$login.$passwd.$boxname.online.log.bz2.uue");
	[ -f "$confdir/$login.$passwd.$boxname.online.log.bz2" ] && unlink ("$confdir/$login.$passwd.$boxname.online.log.bz2");
    }
    # quit
    print N("Quitting Wizard\n");
    Gtk2->main_quit;
}
sub isalphanum {
    my ($str) = @_;
    if ($str =~ /^[[:alnum:]]+$/) {
	return 1;
    } else {
	return 0;
    }
}
sub testPasswd () {
    my $result = -1;
    my $login    = $o->{login}->get_text;
    my $passwd   = $o->{passwd}->get_text;
    my $boxname = $o->{machine}->get_text;
    my $test = isalphanum($boxname);
    #print ("isalnum : $test");
    if ($login && $passwd && $test && $login !~ /\s+/ && $passwd !~ /\s+/) {
# NEW METHOD (http)
	# first, MD5ify the password
	my $w = wait_msg(("Connecting ...\n"));
	$passwd = md5_hex($passwd); # or md5 () or md5_base64 ()
	my $ua = LWP::UserAgent->new;
	$ua->agent("MdkOnlineAgent/0.15" . $ua->agent);	
	$ua->env_proxy;
	my $request = HTTP::Request->new(GET => 'http://www.mandrakeexpert.com/firsttimewizard/validusercheck.php?u=' . $login . '&p=' . $passwd);
	my $response = $ua->request($request);
	remove_wait_msg($w);
	# Check the outcome of the response
	if ($response->is_success) {
	    $result = ($response->content =~ /TRUE/) ? 0 : -1;
	} else {
	    # pb with the connection ? stay on page 2
	    raiseError($o->{mw}->{window}, N("Connection problem"), N("MandrakeOnline could not be contacted, please try again at a later time"));
	    return;
	}
    } else {
	$result = -1; # not needed, but this way it's clear
    }
    
    # if correct, go to page 4
    if (! $result) {
	$o->{nb}->next_page(); 
    } else {
	# if incorrect, clear passwd and stay on page 2
	raiseError($o->{mw}->{window}, N("Wrong password"), N("Your login or password was wrong.\n Either you'll have to type it again, or you'll need to create an account on MandrakeOnline.\n In the latter case, go back to the first step to connect to MandrakeOnline.\n Be aware that you must also provide a Machine name \n (only alphabetical characters are admitted)"));
	$o->{passwd}->set_text("");
    }
}
sub reportConfig {
    my ($file) = @_;
    #touch($file);
    my $w = wait_msg(N("Reading configuration\n"));
    sub header { "
********************************************************************************
* $_[0]
********************************************************************************";
	 }
open (FILE,"> $file") || die "Couldn't open $file : $!"; 
join '', map { chomp; print FILE "$_\n" }
    header("scsi"), cat_("/proc/scsi/scsi"),
    header("lsmod"), cat_("/proc/modules"),
    header("cmdline"), cat_("/proc/cmdline"),
    header("pcmcia: stab"), cat_("/var/lib/pcmcia/stab") || cat_("/var/run/stab"),
    header("usb"), cat_("/proc/bus/usb/devices"),
    header("partitions"), cat_("/proc/partitions"),
    header("cpuinfo"), cat_("/proc/cpuinfo"),
    header("install.log"), cat_("/root/drakx/install.log"),
    header("fstab"), cat_("/etc/fstab"),
    header("lilo.conf"), cat_("/etc/lilo.conf"),
    header("menu.lst"), cat_("/boot/grub/menu.lst"),
    header("/etc/modules.conf"), cat_("/etc/modules.conf"),
    header("rpm -qa"), join ('', sort `rpm -qa`),
    header("mandrake version"), cat_('/etc/mandrake-release');
    close(FILE);
    remove_wait_msg($w);
}
sub wait_msg {
    my ($msg, %options) = @_;
    my $mainw = ugtk2->new('mdkonline', grab => 1, if_(exists $options{transient}, transient => $options{transient}));
    $mainw->{rwindow}->set_position($options{transient} ? 'center_on_parent' : 'center_always') if !$::isEmbedded;
    my $label = ref($msg) =~ /^Gtk/ ? $msg : Gtk2::Label->new($msg);
    gtkadd($mainw->{window}, gtkpack__(gtkadd(Gtk2::VBox->new(0, 5), $label, if_(exists $options{widgets}, @{$options{widgets}}))));
    $label->signal_connect(expose_event => sub { $mainw->{displayed} = 1; 0 });
    $mainw->sync until $mainw->{displayed};
    gtkset_mousecursor_wait($mainw->{rwindow}->window);
    $mainw->flush;
    $mainw;
}
sub remove_wait_msg { $_[0]->destroy }
sub mvfiles {
    my ($source, $dest) = @_;
    -e $source and system("mv","$source","$dest");
}
sub automatedUpgrades {
    my ($login, $passwd, $boxname, $key, $country, $auto) = @_;
    my ($r) = cat_('/etc/mandrake-release') =~ /release\s(\S+)/;
    output "$confdir/mdkupdate",
    qq(# automatically generated file. Please don't edit
LOGIN=$login
PASS=$passwd
MACHINE=$boxname
VER=$r
CURRENTKEY=$key 
COUNTRY=$country
AUTO=$auto
);
    output_p "/etc/cron.daily/mdkupdate",
    qq(#!/bin/bash
if [ -f $confdir/mdkupdate ]; then /usr/bin/mdkupdate --auto; fi
);

chmod 0755, "/etc/cron.daily/mdkupdate";
}
sub writeWideConf {
    my ($login, $boxname, $country) = @_;
    my $d = localtime();
    $d =~ s/\s+/_/g;
    output_with_perm $wideconf, 644,
    qq(LOGIN=$login
MACHINE=$boxname
COUNTRY=$country
LASTCHECK=$d
);
}
d='n1012' href='#n1012'>1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
package install::steps_interactive; # $Id: steps_interactive.pm 267011 2010-03-19 12:00:12Z pterjan $


use strict;
use feature 'state';

our @ISA = qw(install::steps);


#-######################################################################################
#- misc imports
#-######################################################################################
use common;
use partition_table;
use fs::type;
use fs::partitioning;
use fs::partitioning_wizard;
use install::steps;
use install::interactive;
use install::any;
use messages;
use detect_devices;
use run_program;
use devices;
use fsedit;
use mouse;
use modules;
use modules::interactive;
use lang;
use keyboard;
use any;
use log;

#-######################################################################################
#- In/Out Steps Functions
#-######################################################################################
sub errorInStep {
    my ($o, $err) = @_;
    $err = ugtk2::escape_text_for_TextView_markup_format($err) if $o->isa('install::steps_gtk');
    $o->ask_warn(N("Error"), [ N("An error occurred"), formatError($err) ]);
}

sub kill_action {
    my ($o) = @_;
    $o->kill;
}

#-######################################################################################
#- Steps Functions
#-######################################################################################
#------------------------------------------------------------------------------

sub acceptLicense {
    my ($o) = @_;
    return if $o->{useless_thing_accepted};

    any::acceptLicense($o);
}

sub selectLanguage {
    my ($o) = @_;

    any::selectLanguage_install($o, $o->{locale});
    install::steps::selectLanguage($o);

    if ($o->isa('interactive::gtk')) {
	$o->ask_warn('', formatAlaTeX(
"If you see this message it is because you chose a language for
which DrakX does not include a translation yet; however the fact
that it is listed means there is some support for it anyway.

That is, once GNU/Linux will be installed, you will be able to at
least read and write in that language; and possibly more (various
fonts, spell checkers, various programs translated etc. that
varies from language to language).")) if $o->{locale}{lang} !~ /^en/ && !lang::load_mo();
    } else {
	#- no need to have this in po since it is never translated
	$o->ask_warn('', "The characters of your language cannot be displayed in console,
so the messages will be displayed in english during installation") if $ENV{LANGUAGE} eq 'C';
    }
}

#------------------------------------------------------------------------------
sub selectKeyboard {
    my ($o, $clicked) = @_;

    my $from_usb = keyboard::from_usb();
    my $l = keyboard::lang2keyboards(lang::langs($o->{locale}{langs}));

    if ($clicked || !($from_usb || @$l && $l->[0][1] >= 90) || listlength(lang::langs($o->{locale}{langs})) > 1) {
	add2hash($o->{keyboard}, $from_usb);
	my @best = uniq(grep { $_ } $from_usb && $from_usb->{KEYBOARD}, $o->{keyboard}{KEYBOARD},
			map { $_->[0] } @$l);
	@best = () if @best == 1;

	my $format = sub { translate(keyboard::KEYBOARD2text($_[0])) };
	my $other;
	my $ext_keyboard = my $KEYBOARD = $o->{keyboard}{KEYBOARD};
	$o->ask_from_(
		      { title => N("Keyboard"), 
			interactive_help_id => 'selectKeyboard',
			advanced_label => N("More"),
		      },
		      [
                          { label => N("Please choose your keyboard layout"), title => 1 },
                          if_(@best, { val => \$KEYBOARD, type => 'list', format => $format, sort => 1,
				     list => [ @best ], changed => sub { $other = 0 } }),
                          if_(@best,
                              { label => N("Here is the full list of available keyboards:"), title => 1, advanced => 1 }),
			{ val => \$ext_keyboard, type => 'list', format => $format, changed => sub { $other = 1 },
			  list => [ difference2([ keyboard::KEYBOARDs() ], \@best) ], advanced => @best > 1 }
		      ]);
	$o->{keyboard}{KEYBOARD} = !@best || $other ? $ext_keyboard : $KEYBOARD;
	delete $o->{keyboard}{unsafe};
    }
    keyboard::group_toggle_choose($o, $o->{keyboard}) or goto &selectKeyboard;
    install::steps::selectKeyboard($o);
    if ($::isRestore) {
        require MDV::Snapshot::Restore;
        MDV::Snapshot::Restore::main($o);
        $o->exit;
    }
}

#------------------------------------------------------------------------------
sub selectInstallClass {
    my ($o) = @_;

    return if $::isRestore;

    my @l = install::any::find_root_parts($o->{fstab}, $::prefix);
    # Don't list other archs as ugrading between archs is not supported
    my $arch = arch() =~ /i.86/ ? $MDK::Common::System::compat_arch{arch()} : arch();
    # Offer to upgrade only same arch and not mdv-2011+:
    @l = grep { $_->{arch} eq $arch && $_->{version} !~ /201[1-9]/ } @l;
    if (@l) {
        _try_to_upgrade($o, @l);
    }
}

sub _try_to_upgrade {
    my ($o, @l) = @_;
    log::l("proposing to upgrade partitions " . join(" ", map { $_->{part} && $_->{part}{device} } @l));

    my @releases = uniq(map { "$_->{release} $_->{version}" } @l);
    if (@releases != @l) {
        #- same release name so adding the device to differentiate them:
        $_->{release} .= " ($_->{part}{device})" foreach @l;
    }

  askInstallClass:
    my $p;
    $o->ask_from_({ title => N("Install/Upgrade"),
                    interactive_help_id => 'selectInstallClass',
                },
                  [
                      { label => N("Is this an install or an upgrade?"), title => 1 },
                      { val => \$p,
                        list => [ @l, N_("_: This is a noun:\nInstall") ], 
                        type => 'list',
                        format => sub { ref($_[0]) ? N("Upgrade %s", "$_[0]->{release} $_[0]->{version}") : translate($_[0]) }
                    } ]);
    if (ref $p) {
        _check_unsafe_upgrade_and_warn($o, $p->{part}) or $p = undef;
    }

    if (ref $p) {
        _prepare_upgrade($o, $p);
    }
}

sub _prepare_upgrade {
    my ($o, $p) = @_;
    if ($p->{part}) {
        log::l("choosing to upgrade partition $p->{part}{device}");
        $o->{migrate_device_names} = install::any::use_root_part($o->{all_hds}, $p->{part}, $o);
    }

    #- handle encrypted partitions (esp. /home)
    foreach (grep { $_->{mntpoint} } @{$o->{fstab}}) {
        my ($options, $_unknown) = fs::mount_options::unpack($_);
        $options->{encrypted} or next;
        $o->ask_from_({ focus_first => 1 },
                      [ { label => N("Encryption key for %s", $_->{mntpoint}),
                          hidden => 1, val => \$_->{encrypt_key} } ]);
    }

    $o->{previous_release} = $p;
    $o->{isUpgrade} = (find { $p->{release_file} =~ /$_/ } 'mageia', 'mandriva', 'mandrake', 'conectiva', 'redhat') || 'unknown';
    $o->{upgrade_by_removing_pkgs_matching} ||= {
        conectiva => 'cl',
        redhat => '.',          #- everything!
    }->{$o->{isUpgrade}};
    log::l("upgrading $o->{isUpgrade} distribution" . ($o->{upgrade_by_removing_pkgs_matching} ? " (upgrade_by_removing_pkgs_matching $o->{upgrade_by_removing_pkgs_matching})" : ''));
}

sub _check_unsafe_upgrade_and_warn {
    my ($o, $part) = @_;
    !_is_unsafe_upgrade($part) || _warn_unsafe_upgrade($o);
}

sub _is_unsafe_upgrade {
    my ($part) = @_;

    my $r = run_program::get_stdout('dumpe2fs', devices::make($part->{device}));
    my $block_size = $r =~ /^Block size:\s*(\d+)/m && $1;
    log::l("block_size $block_size");
    $block_size == 1024;
}

sub _warn_unsafe_upgrade {
    my ($o) = @_;

    log::l("_warn_unsafe_upgrade");

    my @choices = (
	N_("Cancel installation, reboot system"),
	N_("New Installation"),
	N_("Upgrade previous installation (not recommended)"),
    );

    my $choice;
    $o->ask_from_({ messages => N("Installer has detected that your installed Linux system could not
safely be upgraded to %s.

New installation replacing your previous one is recommended.

Warning : you should backup all your personal data before choosing \"New
Installation\".", '%s') },
		  [ { val => \$choice, type => 'list', list => \@choices, format => \&translate } ]);

    log::l("_warn_unsafe_upgrade: got $choice");

    if ($choice eq $choices[0]) {
	any::reboot();
    } elsif ($choice eq $choices[1]) {
	undef;
    } else {
	1;
    }
}

#------------------------------------------------------------------------------
sub selectMouse {
    my ($o, $force) = @_;

    $force || $o->{mouse}{unsafe} or return;

    mouse::select($o, $o->{mouse}) or return;
   
    if ($o->{mouse}{device} eq "input/mice") {
	modules::interactive::load_category($o, $o->{modules_conf}, 'bus/usb', 1, 0);
	eval { 
	    modules::load('usbhid');
	};
    }
}
#------------------------------------------------------------------------------
sub setupSCSI {
    my ($o) = @_;

    install::any::configure_pcmcia($o);
    { 
	my $_w = $o->wait_message(N("IDE"), N("Configuring IDE"));
	modules::load(modules::category2modules('disk/cdrom'));
    }
    modules::interactive::load_category($o, $o->{modules_conf}, 'bus/firewire', 1);

    my $have_non_scsi = detect_devices::hds(); #- at_least_one scsi device if we have no disks
    modules::interactive::load_category($o, $o->{modules_conf}, 'disk/card_reader|ide|scsi|hardware_raid|sata|firewire|virtual', 1, !$have_non_scsi);
    modules::interactive::load_category($o, $o->{modules_conf}, 'disk/card_reader|ide|scsi|hardware_raid|sata|firewire|virtual') if !detect_devices::hds(); #- we really want a disk!

    install::interactive::tellAboutProprietaryModules($o);

    install::any::getHds($o, $o);
}

#------------------------------------------------------------------------------
sub doPartitionDisks {
    my ($o) = @_;

    if (arch() =~ /ppc/) {
	my $generation = detect_devices::get_mac_generation();
	if ($generation =~ /NewWorld/) {
	    #- mac partition table
	    if (defined $partition_table::mac::bootstrap_part) {
    		#- do not do anything if we've got the bootstrap setup
    		#- otherwise, go ahead and create one somewhere in the drive free space
	    } else {
		my $freepart = $partition_table::mac::freepart;
		if ($freepart && $freepart->{size} >= 1) {
		    log::l("creating bootstrap partition on drive /dev/$freepart->{hd}{device}, block $freepart->{start}");
		    $partition_table::mac::bootstrap_part = $freepart->{part};
		    log::l("bootstrap now at $partition_table::mac::bootstrap_part");
		    my $p = { start => $freepart->{start}, size => MB(1), mntpoint => '' };
		    fs::type::set_pt_type($p, 0x401);
		    fsedit::add($freepart->{hd}, $p, $o->{all_hds}, { force => 1, primaryOrExtended => 'Primary' });
		    $partition_table::mac::new_bootstrap = 1;

    		} else {
		    $o->ask_warn('', N("No free space for 1MB bootstrap! Install will continue, but to boot your system, you'll need to create the bootstrap partition in DiskDrake"));
    		}
	    }
	} elsif ($generation =~ /IBM/) {
	    #- dos partition table
	    $o->ask_warn('', N("You'll need to create a PPC PReP Boot bootstrap! Install will continue, but to boot your system, you'll need to create the bootstrap partition in DiskDrake"));
	}
    }

    if (!$o->{isUpgrade}) {
        fs::partitioning_wizard::main($o, $o->{all_hds}, $o->{fstab}, $o->{manualFstab}, $o->{partitions}, $o->{partitioning}, $::local_install);
    }
}

#------------------------------------------------------------------------------
sub rebootNeeded {
    my ($o) = @_;
    fs::partitioning_wizard::warn_reboot_needed($o);
    install::steps::rebootNeeded($o);
}

#------------------------------------------------------------------------------
sub choosePartitionsToFormat {
    my ($o) = @_;
    fs::partitioning::choose_partitions_to_format($o, $o->{fstab});
}

sub formatMountPartitions {
    my ($o, $_fstab) = @_;
    fs::partitioning::format_mount_partitions($o, $o->{all_hds}, $o->{fstab});
}

#------------------------------------------------------------------------------
#- group by CD
sub ask_deselect_media__copy_on_disk {
    my ($o, $hdlists, $o_copy_rpms_on_disk) = @_;

    log::l("ask_deselect_media__copy_on_disk");

    my @names = uniq(map { $_->{name} } @$hdlists);
    my %selection = map { $_ => 1 } @names;

    $o->ask_from_({ messages => formatAlaTeX(N("The following installation media have been found.
If you want to skip some of them, you can unselect them now.")) },
		[ (map { { type => 'bool', text => $_, val => \$selection{$_}, 
			    if_($_ eq $names[0], disabled => sub { 1 }),
			} } @names),
		  if_($o_copy_rpms_on_disk,
		    { type => 'label', val => \(formatAlaTeX(N("You have the option to copy the contents of the CDs onto the hard disk drive before installation.
It will then continue from the hard disk drive and the packages will remain available once the system is fully installed."))) },
		    { type => 'bool', text => N("Copy whole CDs"), val => $o_copy_rpms_on_disk },
		  ),
		]);
    $_->{ignore} = !$selection{$_->{name}} foreach @$hdlists;
    log::l("keeping media " . join ',', map { $_->{rpmsdir} } grep { !$_->{ignore} } @$hdlists);
}

sub while_suspending_time {
    my ($o, $f) = @_;

    my $time = time();

    my $r = $f->();

    #- add the elapsed time (otherwise the predicted time will be rubbish)
    $o->{install_start_time} += time() - $time;

    $r;
}

# nb: $file can be a directory
sub ask_change_cd {
    my ($o, $medium) = @_;

    while_suspending_time($o, sub { ask_change_cd_($o, $medium) });
}

sub ask_change_cd_ {
    my ($o, $medium) = @_;

    local $::isWizard = 0; # make button name match text, aka being "cancel" rather than "previous"
	$o->ask_okcancel('', N("Change your Cd-Rom!
Please insert the Cd-Rom labelled \"%s\" in your drive and press Ok when done.
If you do not have it, press Cancel to avoid installation from this Cd-Rom.", $medium), 1) or return;

}

sub selectSupplMedia {
    my ($o) = @_;
    install::any::selectSupplMedia($o);
}

#------------------------------------------------------------------------------
sub choosePackages {
    my ($o) = @_;

    require pkgs;
    add2hash_($o, { compssListLevel => pkgs::rpmsrate_rate_default() });

    my $w = $o->wait_message('', N("Looking for available packages..."));
    my $availableC = install::steps::choosePackages($o, pkgs::rpmsrate_rate_max());

    require install::pkgs;

    my $min_size = install::pkgs::selectedSize($o->{packages});
    undef $w;
    if ($min_size >= $availableC) {
	my $msg = N("Your system does not have enough space left for installation or upgrade (%dMB > %dMB)",
		    $min_size / sqr(1024), $availableC / sqr(1024));
	log::l($msg);
	$o->ask_warn('', $msg);
	install::steps::rebootNeeded($o);
    }

    my ($individual, $chooseGroups);

    if (!$o->{isUpgrade}) {
	my $tasks_ok = install::pkgs::packageByName($o->{packages}, 'task-kde4-minimal') &&
	               install::pkgs::packageByName($o->{packages}, 'task-gnome-minimal');
	if ($tasks_ok && $availableC >= 2_500_000_000) { 
	    _chooseDesktop($o, $o->{rpmsrate_flags_chosen}, \$chooseGroups);
	} else {
	    $tasks_ok ? log::l("not asking for desktop since not enough place") :
	                log::l("not asking for desktop since kde and gnome are not available on media (useful for mini iso)");
	    $chooseGroups = 1;
	}
    }

  chooseGroups:
    $o->chooseGroups($o->{packages}, $o->{compssUsers}, \$individual) if $chooseGroups;

    ($o->{packages_}{ind}) =
      install::pkgs::setSelectedFromCompssList($o->{packages}, $o->{rpmsrate_flags_chosen}, $o->{compssListLevel}, $availableC);

    $o->choosePackagesTree($o->{packages}) or goto chooseGroups if $individual;

    install::any::warnAboutRemovedPackages($o, $o->{packages});
}

sub choosePackagesTree {
    my ($o, $packages, $o_limit_to_medium) = @_;

    $o->ask_many_from_list('', N("Choose the packages you want to install"),
			   {
			    list => [ grep { !$o_limit_to_medium || install::pkgs::packageMedium($packages, $_) == $o_limit_to_medium }
				      @{$packages->{depslist}} ],
			    value => \&URPM::Package::flag_selected,
			    label => \&URPM::Package::name,
			    sort => 1,
			   });
}

sub loadSavePackagesOnFloppy {
    my ($o, $packages) = @_;
    $o->ask_from('', 
N("Please choose load or save package selection.
The format is the same as auto_install generated files."),
		 [ { val => \ (my $choice), list => [ N_("Load"), N_("Save") ], format => \&translate, type => 'list' } ]) or return;

    if ($choice eq 'Load') {
	while (1) {
	    log::l("load package selection");
	    my ($_h, $fh) = install::any::media_browser($o, '', 'package_list.pl') or return;
	    my $O = eval { install::any::loadO(undef, $fh) };
	    if ($@) {
		$o->ask_okcancel('', N("Bad file")) or return;
	    } else {
		install::any::unselectMostPackages($o);
		install::pkgs::select_by_package_names($packages, $O->{default_packages} || []);
		return 1;
	    }
	}
    } else {
	log::l("save package selection");
	install::any::g_default_packages($o);
    }
}

sub _chooseDesktop {
    my ($o, $rpmsrate_flags_chosen, $chooseGroups) = @_;

    my @l = group_by2(
	KDE    => N("KDE"),
	GNOME  => N("GNOME"),
	Custom => N("Custom"),
    );
    my $title = N("Desktop Selection");
    my $message = N("You can choose your workstation desktop profile.");

    my $default_choice = (find { $rpmsrate_flags_chosen->{"CAT_" . $_->[0]} } @l) || $l[0];
    my $choice = $default_choice;
    if ($o->isa('interactive::gtk')) {
        # perl_checker: require install::steps_gtk
	$choice = install::steps_gtk::reallyChooseDesktop($o, $title, $message, \@l, $default_choice);
    } else {
	$o->ask_from_({ title => $title, message => $message }, [
	    { val => \$choice, list => \@l, type => 'list', format => sub { $_[0][1] } }, 
	]);
    }
    my $desktop = $choice->[0];
    log::l("chosen Desktop: $desktop");
    my @desktops = ('KDE', 'GNOME');
    if (member($desktop, @desktops)) {
	my ($want, $dontwant) = ($desktop, grep { $desktop ne $_ } @desktops);
	$rpmsrate_flags_chosen->{"CAT_$want"} = 1;
	$rpmsrate_flags_chosen->{"CAT_$dontwant"} = 0;
	my @flags = map_each { if_($::b, $::a) } %$rpmsrate_flags_chosen;
	log::l("flags ", join(' ', sort @flags));
	install::any::unselectMostPackages($o);
    } else {
	$$chooseGroups = 1;
    }
}

sub chooseGroups {
    my ($o, $packages, $compssUsers, $individual) = @_;

    #- for all groups available, determine package which belongs to each one.
    #- this will enable getting the size of each groups more quickly due to
    #- limitation of current implementation.
    #- use an empty state for each one (no flag update should be propagated).
    
    my $b = install::pkgs::saveSelected($packages);
    install::any::unselectMostPackages($o);
    install::pkgs::setSelectedFromCompssList($packages, { CAT_SYSTEM => 1 }, $o->{compssListLevel}, 0);
    my $system_size = install::pkgs::selectedSize($packages);
    my ($sizes, $pkgs) = install::pkgs::computeGroupSize($packages, $o->{compssListLevel});
    install::pkgs::restoreSelected($b);
    log::l("system_size: $system_size");

    my %stable_flags = grep_each { $::b } %{$o->{rpmsrate_flags_chosen}};
    delete $stable_flags{"CAT_$_"} foreach map { @{$_->{flags}} } @{$o->{compssUsers}};

    my $compute_size = sub {
	my %pkgs;
	my %flags = %stable_flags; @flags{@_} = ();
	my $total_size;
	A: while (my ($k, $size) = each %$sizes) {
	    Or: foreach (split "\t", $k) {
		  foreach (split "&&") {
		      exists $flags{$_} or next Or;
		  }
		  $total_size += $size;
		  $pkgs{$_} = 1 foreach @{$pkgs->{$k}};
		  next A;
	      }
	  }
	log::l("computed size $total_size (flags " . join(' ', keys %flags) . ")");
	log::l("chooseGroups: ", join(" ", sort keys %pkgs));

	int $total_size;
    };

    my ($size, $unselect_all);
    my $available_size = install::any::getAvailableSpace($o) / sqr(1024);
    my $size_to_display = sub { 
	my $lsize = $system_size + $compute_size->(map { "CAT_$_" } map { @{$_->{flags}} } grep { $_->{selected} } @$compssUsers);

	#- if a profile is deselected, deselect everything (easier than deselecting the profile packages)
	$unselect_all ||= $size > $lsize;
	$size = $lsize;
	N("Total size: %d / %d MB", install::pkgs::correctSize($size / sqr(1024)), $available_size);
    };

    while (1) {
	if ($available_size < 200) {
	    # too small to choose anything. Defaulting to no group chosen
	    $_->{selected} = 0 foreach @$compssUsers;
	    last;
	}

	$o->reallyChooseGroups($size_to_display, $individual, $compssUsers) or return;

	last if $::testing || install::pkgs::correctSize($size / sqr(1024)) < $available_size || every { !$_->{selected} } @$compssUsers;
       
	$o->ask_warn('', N("Selected size is larger than available space"));	
    }
    install::any::set_rpmsrate_category_flags($o, $compssUsers);

    log::l("compssUsersChoice selected: ", join(', ', map { qq("$_->{path}|$_->{label}") } grep { $_->{selected} } @$compssUsers));

    if (!$o->{isUpgrade}) {
	#- do not try to deselect package (by default no groups are selected).
	install::any::unselectMostPackages($o) if $unselect_all;

	#- if no group have been chosen, ask for using base system only, or no X, or normal.
	offer_minimal_options($o) if !any { $_->{selected} } @$compssUsers;
    }
    1;
}

sub offer_minimal_options {
	my ($o) = @_;
	my $docs = !$o->{excludedocs};	
	state $minimal;
	my $suggests = !$o->{no_suggests};

	$o->ask_from_({ title => N("Type of install"), 
                        message => N("You have not selected any group of packages.
Please choose the minimal installation you want:"),
                        interactive_help_id => 'choosePackages#minimal-install'
                        },
		     [
		      { val => \$o->{rpmsrate_flags_chosen}{CAT_X}, type => 'bool', text => N("With X"), disabled => sub { $minimal } },
		      { val => \$suggests, type => 'bool', text => N("Install suggested packages"), disabled => sub { $minimal } },
		      { val => \$docs, type => 'bool', text => N("With basic documentation (recommended!)"), disabled => sub { $minimal } },
		      { val => \$minimal, type => 'bool', text => N("Truly minimal install (especially no urpmi)") },
		     ],
	) or return &chooseGroups;

	if ($minimal) {
	    $o->{rpmsrate_flags_chosen}{CAT_X} = $docs = $suggests = 0;
	    $o->{rpmsrate_flags_chosen}{CAT_SYSTEM} = 0;
	}
	$o->{excludedocs} = !$docs;
	$o->{rpmsrate_flags_chosen}{CAT_MINIMAL_DOCS} = $docs;
	$o->{no_suggests} = !$suggests;
	$o->{compssListLevel} = pkgs::rpmsrate_rate_max() if !$suggests;
	log::l("install settings: no_suggests=$o->{no_suggests}, excludedocs=$o->{excludedocs}, really_minimal_install=$minimal");

	install::any::unselectMostPackages($o);
}

sub reallyChooseGroups {
    my ($o, $size_to_display, $individual, $compssUsers) = @_;

    my $size_text = &$size_to_display;

    my ($path, $all);
    $o->ask_from_({ messages => N("Package Group Selection"),
		    interactive_help_id => 'choosePackages',
		  }, [
        { val => \$size_text, type => 'label' }, {},
	 (map { 
	       my $old = $path;
	       $path = $_->{path};
	       if_($old ne $path, { val => translate($path) }),
		 {
		  val => \$_->{selected},
		  type => 'bool',
		  disabled => sub { $all },
		  text => translate($_->{label}),
		  help => translate($_->{descr}),
		  changed => sub { $size_text = &$size_to_display },
		 };
	   } @$compssUsers),
	 if_($individual, { text => N("Individual package selection"), val => $individual, advanced => 1, type => 'bool' }),
    ]);

    if ($all) {
	$_->{selected} = 1 foreach @$compssUsers;
    }
    1;    
}

#------------------------------------------------------------------------------
sub installPackages {
    my ($o) = @_;
    my ($current, $total) = (0, 0);

    my ($_w, $wait_message) = $o->wait_message_with_progress_bar(N("Installing"));
    $wait_message->(N("Preparing installation"), 0, 100); #- beware, interactive::curses::wait_message_with_progress_bar need to create the Dialog::Progress here because in installCallback we are chrooted

    local *install::steps::installCallback = sub {
	my ($packages, $type, $id, $subtype, $_amount, $total_) = @_;
	if ($type eq 'user' && $subtype eq 'install') {
	    $total = $total_;
	} elsif ($type eq 'inst' && $subtype eq 'start') {
	    my $p = $packages->{depslist}[$id];
	    $wait_message->(N("Installing package %s", $p->name), $current, $total);
	    $current += $p->size;
	}
    };

    my $install_result;
    catch_cdie { $install_result = $o->install::steps::installPackages('interactive') }
      sub { installPackages__handle_error($o, $_[0]) };

    if ($install::pkgs::cancel_install) {
	$install::pkgs::cancel_install = 0;
	die "setstep choosePackages\n";
    }
    $install_result;
}

sub installPackages__handle_error {
    my ($o, $err_ref) = @_;

    log::l("catch_cdie: $$err_ref");
    my $time = time();
    my $go_on;
    if ($$err_ref =~ /^error ordering package list: (.*)/) {
	$go_on = $o->ask_yesorno('', [
	    N("There was an error ordering packages:"), $1, N("Go on anyway?") ], 1);
    } elsif ($$err_ref =~ /^error installing package list: (\S+)\s*(.*)/) {
	my ($pkg_name, $medium_name) = ($1, $2);
	my @choices = (
	    [ 'retry', N("Retry") ],
	    [ 'skip_one', N("Skip this package") ],
	    [ 'disable_media', N("Skip all packages from medium \"%s\"", $medium_name) ],
	    [ '', N("Go back to media and packages selection") ],
	);
	my $choice;
	$o->ask_from_({ messages => N("There was an error installing package %s.", $pkg_name) },
		      [ { val => \$choice, type => 'list', list => \@choices, format => sub { $_[0][1] } } ]);
	$go_on = $choice->[0];
    }
    if ($go_on) {
	#- add the elapsed time (otherwise the predicted time will be rubbish)
	$o->{install_start_time} += time() - $time;
	$go_on;
    } else {
	$o->{askmedia} = 1;
	$$err_ref = "already displayed";
	0;
    }
}


sub afterInstallPackages($) {
    my ($o) = @_;
    local $o->{pop_wait_messages} = 1;
    my $_w = $o->wait_message(N("Post-install configuration"), N("Post-install configuration"));
    $o->SUPER::afterInstallPackages;
}

sub updatemodules {
    my ($o, $dev, $rel_dir) = @_;

    $o->ask_okcancel('', N("Please ensure the Update Modules media is in drive %s", $dev), 1) or return;
    $o->SUPER::updatemodules($dev, $rel_dir);
}

#------------------------------------------------------------------------------
sub configureNetwork {
    my ($o) = @_;
	#- don't overwrite configuration in a network install
	if (!install::any::is_network_install($o)) {
	    require network::network;
	    network::network::easy_dhcp($o->{net}, $o->{modules_conf});
	}
	$o->SUPER::configureNetwork;
}

#------------------------------------------------------------------------------
sub installUpdates {
    my ($o) = @_;
    $o->{updates} ||= {};
    
    $o->hasNetwork or return;

    if (install::any::is_network_install($o) &&
	find { $_->{update} } install::media::allMediums($o->{packages})) {
	log::l("installUpdates: skipping since updates were already available during install");
	return;
    }

    $o->ask_yesorno_({ title => N("Updates"), messages => formatAlaTeX(
N("You now have the opportunity to download updated packages. These packages
have been updated after the distribution was released. They may
contain security or bug fixes.