summaryrefslogtreecommitdiffstats
path: root/drakpxelinux.pl
blob: 8951a6aeeddff194f74a780cb983e125f38c701f (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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
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
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
#!/usr/bin/perl
#
# Copyright (C) 2004-2005 by Mandriva aginies _ateuh_ mandriva.com
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# 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.

# Quick configuration of PXE menu parameters
# thx R1 for test and some debug
# svn.mandriva.com/svn/soft/drakpxelinux


# i18n: IMPORTANT: to get correct namespace (drakpxelinux instead of libDrakX)
BEGIN { unshift @::textdomains, 'drakpxelinux' }

use lib qw(/usr/lib/libDrakX);
use standalone;
use strict;
use common;
use services;
use network::network;
use network::pxe;
use network::tools;
use interactive;
# must come *after* definition of textdomains for proper initialisation
use ugtk3 qw(:ask :helpers :wrappers :create :dialogs);
use mygtk3 qw(gtknew);
use Gtk3::SimpleList;
use Gtk3::Helper;
use run_program;
use Data::Dumper;

our $model = create_model();
our $treeview = Gtk3::TreeView->new_with_model($model);

# ie of entry menu in PXE:
#label linux
#        KERNEL images/vmlinuz
#        APPEND initrd=images/all.rdz automatic=method:http,interface:eth0,network:dhcp,server:10.0.1.33,directory:/install/ ramdisk_size=64000 root=/dev/ram3 rw vga=788 display=:0

# default VAR
my $SYSLINUXPATH = '/usr/lib/syslinux/';
my $MEMDISK = $SYSLINUXPATH . '/memdisk';
my $XINETDDIR = "/etc/xinetd.d";
my $conf_mac_profiles_name = "/var/lib/tftpboot/X86PC/conf_mac_profiles";

my $net = {};
network::network::read_net_conf($net);

my $sys_wizard_pxe = "/etc/sysconfig/drak_pxe";
my ($interface) = cat_($sys_wizard_pxe) =~ /INTERFACE=(.*)/;
$interface ||= $net->{net_interface};
link_default_path();

my $help = "" .
N("PXE Label: the name to be displayed in the PXE menu (an ASCII word/number)") . "\n" .
N("Server: IP address of server, that contains the installation directory") . "\n" .
N("Kernel: memdisk or vmlinuz") . "\n" .
N("Initrd: network boot image (network.img) or all.rdz") . "\n" .
N("Interface: network interface used for the installation process") . "\n" .
N("Network: DHCP or an IP address") . "\n" .
N("Directory: full path to Mageia install server directory") . "\n" .
N("Installation method: NFS or HTTP") . "\n" .
N("Ramsize: ramsize parameter on boot image") . "\n" .
N("Display: export display to another computer (e.g.: 10.0.1.33:0)") . "\n" .
N("VGA: if you encounter any problem with VGA, please adjust") . "\n" .
"";


my %help = (
	    'initrd' => N("network boot image (network.img) or all.rdz"),
	    'kernel' => N("memdisk in case of network.img, or vmlinuz"),
	    'vga' => N("if you encounter any problem with VGA, please adjust"),
	    'interface' => N("network interface used for the installation process"),
	    'info' => N("Information displayed in PXE help (F1 key)"),
	    'network' => N("DHCP or an IP address"),
	    'directory' => N("full path to Mageia install server directory"),
	    'automatic' => N("installation method: choose NFS or HTTP"),
	    'ramsize' => N("ramsize parameter on boot image"),
	    'display' => N("export display on another computer (e.g.: 10.0.1.33:0)"),
	    'other' => "apic nolapic acpi=off initrd=/bin/shell",
	    'server' => N("IP address of server, that contains the installation directory"),
	    'labels' => N("lists all PXE entries, the default boot is the selected one"),
	    'wizardsrv' => N("launches a wizard to setup a PXE server"),
	    'editb' => N("edits the PXE entry selected with a dialog box"),
	    'removepxe' => N("removes the selected PXE entry"),
	    'apply' => N("apply change to configuration file"),
	    'addpxe' => N("launches a wizard to add a PXE entry "),
	    'helponline' => N("get help from online documentation"),
	    'auto_install' => "http://your_ip:3712/auto_<profil>_<label>.pl",
	   );

sub get_items {
    my @items = (
                 [ "/_File", undef, undef, undef, '<Branch>', ],
        #         [ "/_File/_Write conf", undef, \&write_conf, 1, '<StockItem>', 'gtk-execute' ],
                 [ "/_File/_Exit", undef, sub { ugtk3->exit }, 1, '<StockItem>', 'gtk-quit' ],

                 [ "/_PXE Server", undef, undef, undef, '<Branch>', ],
                 [ "/_PXE Server/_Restart", undef, \&restart_dialog, 1, '<StockItem>', 'gtk-execute' ],
		 [ "/_PXE Server/_Reconfigure", undef, sub {
		     eval { wizard_pxe_server() };
		     my $err = $@;
		     $::WizardWindow->destroy if defined $::WizardWindow;
		     undef $::WizardWindow;
		     if ($err && $err !~ /wizcancel/) {
		       err_dialog(N("Error"), N("The PXE server wizard has unexpectedly failed:")
				  . "\n\n" . $err);
		     }
		   }, 1, '<StockItem>', 'gtk-execute' ],

		 [ "/_Help/Help", undef, \&show_help, 1, '<StockItem>', 'gtk-help' ],
                 );
    return @items;
}

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

sub restart_dialog {
    my $cmd = "service pxe restart";
    my $w = $in->wait_message(N("PXE server"), N("Restarting PXE server..."));
    run_program::get_stdout($cmd) !~ /unknown|error/ or err_dialog(N("Error!"), N("Error Restarting PXE server")) and return;
    undef $w;
}

sub set_help_tip {
  my ($entry, $key) = @_;
  gtkset_tip($entry, formatAlaTeX($help{$key}));
}

if (!$::testing && !$in->do_pkgs->ensure_is_installed('pxe', $network::pxe::pxe_config_file)) {
    err_dialog(N("Error!"), N("missing %s\n\nPlease install the pxe package.", $network::pxe::pxe_config_file));
    $in->exit(-1);
}

save_config($network::pxe::pxelinux_config_file);

my @list_method = qw(nfs http ka dolly); push @list_method, "";
my @list_ram = qw(32000 48000 64000 96000 128000);
my @list_eth = qw(auto eth0 eth1 eth2); push @list_eth, "";

use constant COLUMN_LABEL => 0;
use constant COLUMN_INFO => 1;
use constant COLUMN_KERNEL => 2;
use constant COLUMN_INITRD => 3;
use constant COLUMN_METHOD => 4;
use constant COLUMN_INTERFACE => 5;
use constant COLUMN_NETWORK => 6;
use constant COLUMN_SERVER => 7;
use constant COLUMN_DIRECTORY => 8;
use constant COLUMN_RAMDISK_SIZE => 9;
use constant COLUMN_VGA => 10;
use constant COLUMN_DISPLAY => 11;
use constant COLUMN_OTHERS => 12;
use constant COLUMN_AUTO_INSTALL => 13;
use constant NUM_COLUMNS => 14;

my ($profile, $type);
foreach (@ARGV) {
    if (/^--profile=(\w+)$/) {
	$profile = $1;
    } elsif (/^--type=(\w+)$/) {
	$type = $1;
    }
}

my ($config_file, $help_file); # = $profile && $type ?
#  network::pxe::get_pxelinux_profile_path($profile, $type) :
#  ($network::pxe::pxelinux_config_file, $network::pxe::pxelinux_help_file);
my $pxelinux_conf;# = network::pxe::read_pxelinux_conf($config_file, $help_file);

sub link_default_path() {
  # need to quick fix pb of duplicate default (network::pxe need various adjustement).
  if (!-f "$network::pxe::pxelinux_client_root/pxelinux.cfg/profiles/boot/default") {
    mkdir_p("$network::pxe::pxelinux_client_root/pxelinux.cfg/profiles/boot/");
    system("ln -sf $network::pxe::pxelinux_config_file  $network::pxe::pxelinux_client_root/pxelinux.cfg/profiles/boot/default");
  }
}


sub update_pxelinux_conf_from_treeview {
  my ($pxelinux_conf, $treeview) = @_;
  my $profile = get_selected_profile();
  ($config_file, $help_file) = network::pxe::get_pxelinux_profile_path($profile, 'boot');
  my $model = $treeview->get_model;
  my $iter = $model->get_iter_first;
  splice @{$pxelinux_conf->{entries}};
  while ($iter) {
    my ($label, $info, $kernel, $initrd, $method, $interface, $network, $server, $directory, $ramdisk_size, $vga, $display, $others, $auto_install) = $model->get($iter, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
    my $entry = {
                 label => $label,
                 info => $info,
                 kernel => $kernel,
                 initrd => $initrd,
                 method => $method,
                 interface => $interface,
                 network => $network,
                 server => $server,
                 directory => $directory,
                 ramdisk_size => $ramdisk_size,
                 vga => $network::pxe::vga_resolution_to_bios{$vga},
                 display => $display,
                 others => $others,
		 auto_install => $auto_install,
                };
    if  ($entry->{label} eq "local") {
      $entry = {
		label => "local",
		localboot => "0",
	       };
      push @{$pxelinux_conf->{entries}}, $entry;
    } else {
      push @{$pxelinux_conf->{entries}}, $entry;
    }
    last if !$model->iter_next($iter);
  }
}



sub write_conf {
  my ($pxelinux_conf, $treeview) = @_;
  update_pxelinux_conf_from_treeview($pxelinux_conf, $treeview);
  if (basename($config_file) ne "local") {
    #print "write conf PXE\n";
    network::pxe::write_pxelinux_conf($pxelinux_conf, $config_file);
  }
}

sub set_pxelinux_entry_at_iter {
    my ($model, $iter, $entry) = @_;
    $model->set($iter,
		 COLUMN_LABEL, $entry->{label},
		 COLUMN_INFO, $entry->{info},
		 COLUMN_KERNEL, $entry->{kernel},
		 COLUMN_INITRD, $entry->{initrd},
		 COLUMN_METHOD, $entry->{method},
		 COLUMN_INTERFACE, $entry->{interface},
		 COLUMN_NETWORK, $entry->{network},
		 COLUMN_SERVER, $entry->{server},
		 COLUMN_DIRECTORY, $entry->{directory},
		 COLUMN_RAMDISK_SIZE, $entry->{ramdisk_size},
		 COLUMN_VGA, $network::pxe::vga_bios_to_resolution{$entry->{vga}},
		 COLUMN_DISPLAY, $entry->{display},
		 COLUMN_OTHERS, $entry->{others},
		COLUMN_AUTO_INSTALL, $entry->{auto_install},
	       );
}


sub create_model() {
#    my $model = Gtk3::ListStore->new(("Glib::String") x NUM_COLUMNS);
  my $model = Gtk3::ListStore->new("Glib::String", "Glib::String",  "Glib::String", "Glib::String", "Glib::String", "Glib::String", "Glib::String", "Glib::String", "Glib::String", "Glib::String", "Glib::String", "Glib::String", "Glib::String", "Glib::String");
#  set_pxelinux_entry_at_iter($model, $model->append, $_) foreach @{$pxelinux_conf->{entries}};
  set_pxelinux_entry_at_iter($model, $model->append, $_) foreach @{$pxelinux_conf->{entries}};
  return $model;
}


sub add_local_profil_entry {
  my $local_conf = $network::pxe::pxelinux_client_root . "/pxelinux.cfg/profiles/boot/local";
  if (!-f $local_conf) {
    output($local_conf, <<EOF);
PROMPT 10
DEFAULT local
TIMEOUT 50

label local
  LOCALBOOT 0
EOF
  }
}

# wizard to add an entry in PXE menu
sub wizard_add_entry {
  my ($_widget, $treeview, $pxelinux_conf, $profiles) = @_;
  my $model = $treeview->get_model;

  local $::isEmbedded = 0;
  undef $::WizardTable;
  undef $::WizardWindow;
  $::isWizard = 1;
  use wizards;
  my $WPXENAME = "Mageia";
  my $WINFO = "install Mageia";
  my $WALLRDZ = "/mnt/nfs/isolinux/alt0/all.rdz";
#  my $WALLRDZ = "/tmp/all.rdz";
  my $WVMLINUZ = "/mnt/nfs/isolinux/alt0/vmlinuz";
#  my $WVMLINUZ = "/tmp/vmlinuz";
  my $wiz = wizards->new({
	     name => N("Add a PXE entry"),
	     pages => {
		       welcome => {
				   name => N("Add an all.rdz boot image") . "\n" . N("To boot through the network, the networked computer needs a boot image. Morever we need to name this image, so each boot image is related to a name in the PXE menu. Thus, the user can choose which image he wants to boot through PXE.") . "\n\n" . N("For technical reasons, in case of multiple boot images, it's simpler to boot the networked computer through a kernel (vmlinuz), and to provide one file with all needed drivers (in our case all.rdz)."),
				   next => 'addimg',
				   no_back => 1,
				  },
		       addimg => {
				  name => N("When this wizard has finished, the all.rdz image and kernel vmlinuz will be copied into \n%s.\n\nThe PXE menu list will be updated with this new entry.", $network::pxe::pxelinux_images),
				  data => [
					   { label => N("PXE label:"), val => \$WPXENAME,
					     help => N("name displayed in PXE menu (please provide an ASCII word or a number, without spaces)") },
					   { label => N("PXE information:"), val => \$WINFO,
					     help => N("The PXE information is used to explain the role of the boot image,\ne.g.:\nMageia rescue disk\nMageia cauldron install via http") },
					   { label => N("Full path to all.rdz image source:"), type => 'file', val => \$WALLRDZ,
					     help => N("Provide the full path to all.rdz image location") },
					   { label => N("Full path to vmlinuz source:"), type => 'file', val => \$WVMLINUZ,
					     help => N("Provide the full path to vmlinuz kernel location") },
					  ],
				  complete => sub {
				    test_similar_label($WPXENAME, $pxelinux_conf) or return 'addimg';
				    if (($WPXENAME) !~ /^\w+$/) {
				      err_dialog(N("Error!"), N("PXE label should be an ASCII word/number without space. Please adjust")) and return 'addimg';
				    }
				    if (! -f $WALLRDZ) {
				      err_dialog(N("Error!"), N("Please enter a correct path to all.rdz")) and return 'addimg';
				    }
				    if (! -f $WVMLINUZ) {
				      err_dialog(N("Error!"), N("Please enter a correct path to vmlinuz")) and return 'addimg';
				    }
				  },
				  next => 'endadd',
				  post => sub {
				    my $w = $in->wait_message(N("add a PXE entry"), N("add a PXE entry in your PXE server configuration..."));
				    network::pxe::add_in_help($WPXENAME, $WINFO);
				    my $vmlinuzpxe = basename($WVMLINUZ) . "-$WPXENAME";
				    cp_af($WVMLINUZ, $network::pxe::pxelinux_images . "/$vmlinuzpxe");
				    cp_af($WALLRDZ, $network::pxe::pxelinux_images . "/$WPXENAME.rdz");
				    my $entry = {
						 label => $WPXENAME,
						 info => $WINFO,
						 kernel => "images/$vmlinuzpxe",
						 initrd => "images/$WPXENAME.rdz",
						 ramdisk_size => "128000",
						 vga => "788",
						 others => "root=/dev/ram3 rw",
						};
				    push @{$pxelinux_conf->{entries}}, $entry;
				    set_pxelinux_entry_at_iter($model, $model->append, $entry);
				    # set default boot for profile if none
				    if (!$pxelinux_conf->{default}) {
				      $pxelinux_conf->{default} = $WPXENAME;
				      $pxelinux_conf->{display} = 'messages';
				      $pxelinux_conf->{timeout} = '50';
				      $pxelinux_conf->{prompt} = '10';
#				      $pxelinux_conf->{f1} = '';
				    }
				    refresh_menu();
				    undef $w;
				    return;
				  },
				  no_back => 1,
				 },
		       endadd => {
				  name => N("Congratulations"),
				  data => [ { label => N("The wizard successfully added the PXE boot image.") } ],
				  no_back => 1,
				  end => 1,
				 },
		      }
  });
  $wiz->process($in);
  $::isWizard = 0;
  gtkset_mousecursor_normal();
}

# remove an entry in PXE menu
sub remove_item {
  my ($_widget, $treeview, $pxelinux_conf) = @_;
  $::isWizard = 0;
  my $model = $treeview->get_model;
  my $selection = $treeview->get_selection;
  my $iter = $selection->get_selected;
  if ($iter) {
      my $path = $model->get_path($iter);
      my $i = ($path->get_indices)[0];
      my $entry = $pxelinux_conf->{entries}[$i];

      $entry->{label} =~ /local/ and info_dialog(N("Local"), N("You can't remove local entry.")) and return 0;
      ask_okcancel("Info", "Remove $entry->{label} PXE entry ?") or return;
      network::pxe::remove_in_help($entry->{label});
      my $ke = $network::pxe::pxelinux_client_root . "/$entry->{kernel}";
      my $initrdf = $network::pxe::pxelinux_client_root . "/$entry->{initrd}";
      if (basename($entry->{kernel} ne "memdisk")) {
	print "kernel: $ke\n";
	print "initrd: $initrdf\n";
	#system("rm -vf $ke");
	#system("rm -vf $initrdf");
      } else {
	print "initrd: $initrdf\n";
	#system("rm -vf $initrdf");
      }
      $model->remove($iter);
      splice @{$pxelinux_conf->{entries}}, $i, 1;
      write_conf($pxelinux_conf, $treeview);
      refresh_menu();
    }

}

sub test_similar_label {
  my ($label, $pxelinux_conf) = @_;
  if (any { $_->{label} eq $label } @{$pxelinux_conf->{entries}}) {
    err_dialog(N("Error!"), N("Found a similar entry in PXE list labeled: %s.\nChoose another label please", $label)) and return 0;
  } else { return 1 }
}

sub clone_box_item {
  my ($_widget, $treeview, $pxelinux_conf) = @_;
  $::isWizard = 0;
  my $model = $treeview->get_model;
  my $iter = $treeview->get_selection->get_selected;
  if ($iter) {
    my $path = $model->get_path($iter);
    my $i = ($path->get_indices)[0];
    my $entry = $pxelinux_conf->{entries}[$i];
    my $w = ugtk3->new(N("Clone %s entry", $entry->{label}));
    my ($entry_box);
    $w->{window}->set_position('center');
    $w->{ok_clicked} = sub {
	my $new_entry = $entry_box->get_text;
	if ($new_entry !~ m/^\w+$/) { err_dialog(N("Error!"), N("PXE label should be an ASCII word/number without space. Please adjust")) and return }
	test_similar_label($new_entry, $pxelinux_conf) or return;
	my $newentry_data = $entry;
	$newentry_data->{label} = $new_entry;
	push @{$pxelinux_conf->{entries}}, $newentry_data;
	set_pxelinux_entry_at_iter($model, $model->append, $newentry_data);
	write_conf($pxelinux_conf, $treeview);
	Gtk3->main_quit;
      };
    gtkadd($w->{window},
	   gtknew('VBox', children_loose => [
					     $entry_box = gtknew('Entry', text => ''),
					     create_okcancel($w),
					    ])
	  );
    $w->main;
    refresh_menu();
  }
}

# dialog box to edit a PXE entry
sub edit_box_item {
  my ($_widget, $treeview, $pxelinux_conf) = @_;
  $::isWizard = 0;
  my $model = $treeview->get_model;
  my $selection = $treeview->get_selection;

  my $iter = $selection->get_selected;
  if ($iter) {
    my $path = $model->get_path($iter);
    my $i = ($path->get_indices)[0];
    my $entry = $pxelinux_conf->{entries}[$i];

    my $dialog = new Gtk3::Dialog();
    $dialog->set_modal(1);
    $dialog->set_resizable(0);

    $entry->{label} =~ /local/ and info_dialog(N("Local"), N("You can't modify local entry.")) and return 0;
    my $label = Gtk3::Label->new($entry->{label});
#    my $oldlabel = $label;

    my $info = gtknew('Entry', text => $entry->{info} || '');
#    $info->set_sensitive(0);
    set_help_tip($info, 'info');

    # create file dialog widget, with file or directory selection
    my $fdwidget = sub {
      my ($data, $test, $filetotest, $label, $profile) = @_;
      if ($filetotest eq "auto_install") {
	chdir($network::pxe::pxelinux_client_root . "/pxelinux.cfg/profiles/");
      } else { chdir($network::pxe::pxelinux_client_root);
	     }
      my $fd = gtknew('FileChooserDialog', title => N("Selection"), action => 'save', modal => 1);
      $fd->signal_connect("destroy", sub { $fd->hide });
      $fd->signal_connect(response => sub {
				       my (undef, $response) = @_;
				       if (member($response, qw(cancel delete_event))) {
				          $fd->hide;
				          return;
				       }
				       return if !member($response, qw(apply ok yes));
				       my $file = $fd->get_filename;
				       if ($test eq "dir") {
					 -d $file or err_dialog(N("Error!"), N("Should be a directory.")) and return;
				       } else {
					 -f $file or err_dialog(N("Error!"), N("Should be a file")) and return;
				       }
				       if ($filetotest eq "kernel") {
					 if (basename($file) ne "memdisk") {
					   run_program::get_stdout("file $file") =~ /boot sector/ or err_dialog(N("Error!"), N("Should be a boot sector file")) and return;
					   run_program::get_stdout("cp -avf $file " . $network::pxe::pxelinux_images . "/vmlinuz-$label");
					   $data->set_text("images/vmlinuz-$label");
					 } else { $data->set_text("memdisk") }
				       } elsif ($filetotest eq "initrd") {
					 if (basename($file) !~ /^\w+\.img$/) {
					   run_program::get_stdout("file $file") =~ /initrd/ or err_dialog(N("Error!"), N("Should be an initrd file")) and return;
					   system("cp -avf $file " . $network::pxe::pxelinux_images . "/$label.rdz");
					   $data->set_text("images/$label.rdz");
					 } else {
					   system("cp -avf $file " . $network::pxe::pxelinux_images . "/$label.img");
					   $data->set_text("images/$label.img");
					 }
				       } elsif ($filetotest eq "auto_install") {
					 run_program::get_stdout("file $file") =~ /perl/ or err_dialog(N("Error!"), N("Should be a perl script")) and return;
					 my $ip_address = network::tools::get_interface_ip_address($net, $interface);
					 my $auto_cfg = $network::pxe::pxelinux_client_root . "/pxelinux.cfg/profiles/auto_" . $profile . "_" . $label . ".pl";
					 cp_af($file, $auto_cfg);
					 substInFile {
					     s/^.*deploy_server.*\n//g;
					     $_ .= "\t'deploy_server' => \"$ip_address:3710\",\n" if /^\s*\$o\s*=\s*{$/;
					 } $auto_cfg;
					 $data->set_text("http://$ip_address:3712/auto_" . $profile . "_" . $label . ".pl");
				       }
					 $fd->hide;
				     }, $fd);
      return $fd;
    };


    my $kernel = Gtk3::Entry->new;
    $kernel->set_text($entry->{kernel});
    $kernel->set_sensitive(0);
    set_help_tip($kernel, 'kernel');

    my $file_dialogk = $fdwidget->($kernel, "", "kernel", $entry->{label});
    # button kernel
    my $buttonkernel = Gtk3::Button->new(N("Select kernel to boot"));
    $buttonkernel->signal_connect(clicked => sub { $file_dialogk->show });

    my $initrd = Gtk3::Entry->new;
    $initrd->set_sensitive(0);
    $initrd->set_text($entry->{initrd});
    set_help_tip($initrd, 'initrd');

    my $auto_install = gtknew('Entry', text => $entry->{auto_install} || '');
    set_help_tip($auto_install, 'auto_install');
    my $profile = get_selected_profile();
    my $profile_selection = $fdwidget->($auto_install, "", "auto_install", $entry->{label}, $profile);
    my $buttonprofil = Gtk3::Button->new("Select auto_install.pl");
    $buttonprofil->signal_connect(clicked => sub { $profile_selection->show });

    my $file_dialog = $fdwidget->($initrd, "", "initrd", $entry->{label});
    my $buttoninitrd = Gtk3::Button->new(N("Select associated initrd"));
    $buttoninitrd->signal_connect(clicked => sub { $file_dialog->show });

    # combo box to pop down automatic installation
    my $automatic = Gtk3::ComboBoxText->new;
    $automatic->set_popdown_strings(@list_method);
    $automatic->entry->set_text($entry->{method});
    set_help_tip($automatic, 'automatic');

    # combo box to pop down list of network interface
    my $interface = new Gtk3::ComboBoxText();
    $interface->set_popdown_strings(@list_eth);
    $interface->entry->set_text($entry->{interface});
    set_help_tip($interface, 'interface');

#    my $network = Gtk3::Entry->new;
#    $network->set_text($entry->{network});
#    set_help_tip($network, 'network');

    my $server = gtknew('Entry', text => $entry->{server} || '');
    set_help_tip($server, 'server');

    my $directory = gtknew('Entry', text => $entry->{directory} || '');
    set_help_tip($directory, 'directory');

    my $file_dialogd = $fdwidget->($directory, "dir");
    my $buttondir = Gtk3::Button->new(N("Select directory"));
    $buttondir->signal_connect(clicked => sub { $file_dialogd->show });

    my $ramdisk_size = new Gtk3::ComboBoxText();
    $ramdisk_size->set_popdown_strings(@list_ram);
    if ($entry->{ramdisk_size} eq "") { $entry->{ramdisk_size} = "128000" }
    $ramdisk_size->entry->set_text($entry->{ramdisk_size});
    set_help_tip($ramdisk_size, 'ramsize');

    my $vga = new Gtk3::ComboBoxText();
    $vga->set_popdown_strings(sort keys %network::pxe::vga_resolution_to_bios);
    $vga->entry->set_text($network::pxe::vga_bios_to_resolution{$entry->{vga}});
    set_help_tip($vga, 'vga');

    my $display = gtknew('Entry', text => $entry->{display} || '');
    set_help_tip($display, 'display');

    my $others = Gtk3::Entry->new;
    if ($entry->{others} eq "") { $entry->{others} = "root=/dev/ram3 rw" }
    $others->set_text($entry->{others});
    set_help_tip($others, 'others');

    my %size_groups = map { $_ => Gtk3::SizeGroup->new('horizontal') } qw(label widget button);
    my $label_and_widgets = sub {
      my ($label, $widget, $button) = @_;
      gtkpack_(Gtk3::HBox->new(0,5),
	       0, gtkadd_widget($size_groups{label}, $label),
	       1, gtkadd_widget($size_groups{widget}, $widget),
	       2, gtkadd_widget($size_groups{button}, $button),
	      );
    };

    # display IPADDRESS only if dhcp is not selected
    my $ipaddr = Gtk3::Entry->new;
    my $toggledhcp = Gtk3::CheckButton->new(N("DHCP or IP address"));
    if ($entry->{network} eq "dhcp") { $toggledhcp->set_active(1);
					   $ipaddr->set_sensitive(0);
				       } else {
					 $toggledhcp->set_active(0);
					 $ipaddr->set_sensitive(1);
					 $ipaddr->set_text($entry->{network} || '');
				       }

    $toggledhcp->signal_connect(clicked => sub {
				  my $s = $toggledhcp->get_active;
				  if ($s eq "1") {
				    $ipaddr->set_sensitive(0);
				  } else {
				    $ipaddr->set_sensitive(1);
				  }
				});

    # ok, lets create the dialog box :-)
    gtkpack_($dialog->get_child,
	     0, gtkadd(Gtk3::Frame->new(N("PXE entry")),
		       gtkpack_(gtkset_border_width(Gtk3::VBox->new, 5),
				0, $label_and_widgets->(N("Label"), $label, ""),
				0, $label_and_widgets->(N("Entry description"), $info, ""),
				0, Gtk3::VSeparator->new,
				0, $label_and_widgets->(N("Kernel image: ") . $network::pxe::pxelinux_client_root . "/", $kernel, $buttonkernel),
				0, $label_and_widgets->(N("Initrd image: ") . $network::pxe::pxelinux_client_root . "/", $initrd, $buttoninitrd),
			       ),
		      ),

	     0, gtkadd(Gtk3::Frame->new(N("Mageia installer options")),
		       gtkpack_(gtkset_border_width(Gtk3::VBox->new, 5),
				0, $label_and_widgets->(N("Ramdisk size"), $ramdisk_size, ""),
				0, $label_and_widgets->(N("Custom options"), $others, ""),
				0, $label_and_widgets->(N("Frame buffer resolution"), $vga, ""),
				0, $label_and_widgets->(N("Remote IP of X server"), $display, ""),
				0, gtkadd(Gtk3::Frame->new(N("Automatic Options")),
					  gtkpack_(gtkset_border_width(Gtk3::VBox->new, 5),
						   0, $label_and_widgets->(N("Installation method"), $automatic, ""),
						   0, $label_and_widgets->(N("Network interface"), $interface, ""),
						   0, gtkpack_(Gtk3::HBox->new(0,5),
							       0, gtkadd_widget($size_groups{label}, $toggledhcp),
							       1, gtkadd_widget($size_groups{widget}, $ipaddr),
							       2, gtkadd_widget($size_groups{button}, ""),
							      ),
						   0, $label_and_widgets->(N("Remote server name"), $server, ""),
						   0, $label_and_widgets->("auto_install", $auto_install, $buttonprofil),
						   0, $label_and_widgets->(N("Remote installation directory"), $directory, ""),
						  ),
					 ),
			       ),
		      ),
	     0, create_okcancel({
				 cancel_clicked => sub { $dialog->destroy },
				 ok_clicked => sub {
				   #ask_okcancel("are you sure you want to update all those values ?");
				   $entry->{label} = $label->get_text;
				   $entry->{info} = $info->get_text;
				   $entry->{kernel} = $kernel->get_text;
				   $entry->{initrd} = $initrd->get_text;
				   $entry->{method} = $automatic->entry->get_text;
				   $entry->{interface} = $interface->entry->get_text;
				   # check dhcp or ipaddress
                                   if ($toggledhcp->get_active) {
				     $entry->{network} = "dhcp";
				   } else {
				     $entry->{network} = $ipaddr->get_text;
				     if ($entry->{kernel} !~ /memdisk/) {
				       is_ip($entry->{network}) or err_dialog(N("Error!"), N("Please enter a valid IP address.")) and return;
				     }
				   }
				   $entry->{server} = $server->get_text;
				   $entry->{directory} = $directory->get_text;
				   $entry->{ramdisk_size} = $ramdisk_size->entry->get_text;
				   $entry->{vga} = $network::pxe::vga_resolution_to_bios{$vga->entry->get_text};
				   $entry->{display} = $display->get_text;
				   $entry->{others} = $others->get_text;
				   $entry->{auto_install} = $auto_install->get_text;

				   # update value in cells
				   set_pxelinux_entry_at_iter($model, $iter, $entry);
				   write_conf($pxelinux_conf, $treeview);
				   $dialog->destroy;
				   network::pxe::add_in_help($entry->{label}, $entry->{info});
				 },
				},
			       ),
	    );
    $dialog->show_all;
  }
}

sub show_help() { info_dialog("help",
			    gtkpack_(gtkset_border_width(Gtk3::VBox->new, 3),
				     0, $help,
				     0, gtksignal_connect(set_help_tip(Gtk3::Button->new(N("online PXE documentation")), 'helponline'),
							  clicked => sub { system("/usr/bin/www-browser http://people.mandriva.com/~aginies/doc/pxe/ &") }
							 ),
				    ),
			   );
	      }

sub check_pxe_conf() {
  my $ip_address = network::tools::get_interface_ip_address($net, $interface);
  if (! any { /default_address=$ip_address/ } cat_($network::pxe::pxe_config_file)) {
    # pxe.conf doesnt matche system, relaunch wizard_pxe_server
    err_dialog(N("Error!"), N("Your %s doesn't match your actual IP address configuration. Relaunching the PXE server wizard to readjust it.", $network::pxe::pxe_config_file)) and launch_pxe_server();
  }
}

# launch wizard to setup a PXE server
sub wizard_pxe_server() {
  local $::isEmbedded = 0;
  my $in = 'interactive'->vnew('su');
  undef $::WizardTable;
  undef $::WizardWindow;
  $::isWizard = 1;
  use wizards;
  my $wiz = wizards->new({
	     name => N("PXE Wizard"),
	     needed => { "tftp-server", "pxe", "dhcpd" },
	     pages => {
		       welcome => {
				   name => N("PXE wizard") . "\n\n" . N("Set a PXE server.") . "\n" . N("This wizard will help you to configure the PXE server, and PXE boot image management. PXE (Pre-boot eXecution Environment) is a protocol designed by Intel that allows computers to boot through the network. PXE is stored in the ROM of new generation network cards. When the computer boots up, the BIOS loads the PXE ROM in the memory and executes it. A menu is displayed, allowing the computer to boot an operating system loaded through the network."),
				   no_back => 1,
				   next => 'pxeserver',
				  },
		       pxeserver => {
				     name => N("Set PXE server") . "\n\n" . N("We need to use a special dhcpd.conf file with PXE parameter. To set up such a DHCP server, launch the DHCP wizard and check the box 'Enable PXE'. If you don't do that, PXE query will not be answered by this server.") . "\n" . N("Now the wizard will configure all needed default configuration files to allow computers to boot through the network."),
				     no_back => 1,
				     next => 'interface',
				    },
		       interface => {
				     name => N("PXE server Interface"),
				     data => [
					      { list => [ sort keys %{$net->{ifcfg}} ],  val => \$interface },
					     ],
				     no_back => 1,
				     next => 'summaryserver'
				    },
		       summaryserver => {
					 name => N("The wizard will now prepare all default files to set up your PXE server"),
					 pre => sub {
					   output($sys_wizard_pxe, "INTERFACE=$interface\n");
					 },
					 data => [
						  { label => N("TFTP directory:        %s", $network::pxe::tftp_root) },
						  { label => N("Boot image path:       %s", $network::pxe::pxelinux_images) },
						  { label => N("PXE config file:       %s", $network::pxe::pxe_config_file) },
						  { label => N("PXE help file:       %s",   $network::pxe::pxelinux_help_file) },
						 ],
					 post => \&do_it_pxe,
					 no_back => 1,
					 next => 'endserver',
					},
		       endserver => {
				     name => N("End of PXE server configuration"),
				     data => [ { label => N("The wizard successfully configured your PXE server. Now you can configure the PXE menu entry.") } ],
				     no_back => 1,
				     end => 1,
				    },
		      },
  });
  $wiz->process($in);
  gtkset_mousecursor_normal();
}

# save old config with date
sub save_config {
  my ($old) = @_;
  my $DATE = chomp_(`date +%d-%m-20%y`);
  if (-f $old) {
    print " - Backup of $old configuration\n";
    cp_af($old, $old . '.' . $DATE);
  }
}

# can adjust block size in tftp server (ita64)
sub tftp_blksize {
  # $o should be with W or not N
  my ($o) = @_;
  if ($o =~ /W/) {
    substInFile { s/server_args.*/server_args = -r blksize -s $network::pxe::tftp_root/ } "$XINETDDIR/tftp";
  } else {
    substInFile { s/server_args.*/server_args = -s $network::pxe::tftp_root/ } "$XINETDDIR/tftp";
  }
}

# enable tftp server in xinetd conf
sub enable_tftps() {
  substInFile { s/disable.*/disable = no/ } "$XINETDDIR/tftp";
}

sub memlinux_prep() {
  if (!-f ($network::pxe::pxelinux_client_root . "/memdisk")) {
    cp_af($MEMDISK, $network::pxe::pxelinux_client_root);
  }
}

# main procedure to setup PXE server
sub do_it_pxe() {
  return if $::testing;
  my $w = $in->wait_message(N("PXE server"), N("Configuring a PXE server on your system..."));
  output($network::pxe::pxelinux_client_root . "/drakwizard_pxe", <<EOF);
do not remove
use to check if drakwizard PXE set server
has been launch.
EOF

  mkdir_p($network::pxe::pxelinux_images);
  memlinux_prep();

  my $default_conf = network::pxe::read_pxelinux_conf($network::pxe::pxelinux_config_file, $network::pxe::pxelinux_help_file);

  #- restore default pxe settings
  put_in_hash($default_conf, {
      'prompt' => 1,
      'default' => 'local',
      'display' => 'messages',
      'timeout' => '50',
      'f1' => 'help.txt',
  });
  network::pxe::write_pxelinux_conf($default_conf, $network::pxe::pxelinux_config_file);

  save_config($network::pxe::pxelinux_help_file);
  network::pxe::write_default_pxe_help();

  save_config($network::pxe::pxelinux_message_file);
  network::pxe::write_default_pxe_messages($net);

  network::pxe::write_pxe_conf($net, $interface);

  enable_tftps();
  tftp_blksize('N');
  services::enable($_) foreach qw(xinetd pxe);
}

# add colum to model
# fixed :-)
sub add_columns {
  my $treeview = shift;
  my $model = $treeview->get_model;
  each_index {
    my $renderer = Gtk3::CellRendererText->new;
    $renderer->set(editable => 0);
    $renderer->set_data(column => $::i);
    $treeview->insert_column_with_attributes(-1, $_, $renderer, 'text' => $::i);
  } N("Label"), N("Entry description"), N("Kernel image"), N("Initrd image"), N("Installation method"), N("Network interface"), N("DHCP or IP address"), N("Remote server name"), N("Remote installation directory"), N("Ramdisk size"), N("Frame buffer resolution"), N("Remote IP of X server"), N("Custom options"), "Auto_install";
}


# drakdeploy code from blino
my $mac_regexp = '(?:[0-9a-f]{2}:){5}[0-9a-f]{2}';
my $profiles_conf = network::pxe::read_profiles();

sub create_systems_list() {
  my $systems = Gtk3::SimpleList->new(
				      N("MAC address") => 'text',
				      N("Installation profile") => 'text',
				      N("Boot profile") => 'text',
				      N("Computer Name") => 'text',
				     );

  foreach ($systems->get_columns) { $_->set_resizable(1) }
  $systems->set_headers_clickable(1);
  $systems->set_rules_hint(1);
  $systems->get_selection->set_mode('multiple');
  $systems->get_model->set_sort_column_id(0, 'ascending');
  foreach (0..2) {
    $systems->get_column($_)->signal_connect('clicked', \&sort_by_column, $systems->get_model);
    $systems->get_column($_)->set_sort_column_id($_ == 0 ? 1 : $_ + 2);
  }
  $systems->get_column(1)->get_cells->set_property('mode', 'inert');
  $systems->set_column_editable(3, 1);
  return $systems;
}

sub sort_by_column {
    my ($column, $model) = @_;
    my $col_id = $column->get_sort_column_id;
    my ($old_id, $old_order) = $model->get_sort_column_id;
    $model->set_sort_column_id($col_id, $old_id == $col_id && $old_order ne 'descending' ? 'ascending' : 'descending');
}

sub create_profiles_list() {
  my $profiles = Gtk3::SimpleList->new("Profile name" => 'text');
  $profiles->set_headers_visible(1);
  $profiles->get_selection->set_mode('browse');
  $profiles->get_selection->signal_connect(changed => sub {
					     my $pxelinux_conf = get_pxelinux_conf_from_profile();
					     refresh_menu();
					     update_treeview($pxelinux_conf);
					   });
  return $profiles;
}

my $profiles = create_profiles_list;
my $systems = create_systems_list;
my $log_text = gtknew('TextView');

sub get_selected_profile() {
  my $model_profiles =  $profiles->get_model;
  my $iter = $profiles->get_selection->get_selected;
  if ($iter) {
    my $profile = $model_profiles->get($iter, 0);
    return $profile;
  }
}

sub get_pxelinux_conf_from_profile() {
  my $model_profiles =  $profiles->get_model;
  my $iter = $profiles->get_selection->get_selected;
  if ($iter) {
    ($config_file, $help_file) = network::pxe::get_pxelinux_profile_path($model_profiles->get($iter, 0), 'boot');
    my $pxelinux_conf = profile_selected($model_profiles->get($iter, 0));
    return $pxelinux_conf;
  }
}

sub system_entry_set_profile2 {
  my ($entry, $profile) = @_;
  $entry->[2] = $profile || N("None");
}

sub system_entry_set_profile {
  my ($entry, $profile) = @_;
  $entry->[1] = $profile || N("None");
}

sub system_entry_set_name {
  my ($entry, $name) = @_;
  $entry->[3] = $name || "";
}

sub find_system_entry_for_mac_address {
    my ($mac_address) = @_;
    find { $_->[0] eq $mac_address } @{$systems->{data}};
}

sub get_name_from_mac {
  my ($mac) = @_;
  foreach (cat_($conf_mac_profiles_name)) {
    return $3 if m/$mac\|(\w+|)\|(\w+|)\|(.*|)/;
  }
}

sub get_profile2_from_mac {
  my ($mac) = @_;
  foreach (cat_($conf_mac_profiles_name)) {
    return $2 if m/$mac\|(\w+|)\|(\w+|)\|(.*|)/;
  }
}

sub update_systems_data_from_file {
  my ($mac , $entry);
  foreach $a (@{$systems->{data}}) {
    $mac = $a->[0];
    $entry = [ $mac ];
    my $profile2 = get_profile2_from_mac($mac);
    my $name = get_name_from_mac($mac);
    $profile2 and $a->[2] = $profile2;
    $name and  $a->[3] = $name;
  }
}


sub add_configured_mac_addresses() {
  my ($name);
  while (my ($mac_address, $conf) = each %{$profiles_conf->{per_mac}}) {
    my $entry = [ $mac_address ];
    system_entry_set_profile($entry, $conf->{profile});
    push @{$systems->{data}}, $entry;
    gtktext_append($log_text, "Detected new system: $mac_address\n");
  }
}

sub get_mac_addresses_from_dhcp_log() {
    my %addresses;
    foreach (cat_("/var/log/daemons/info")) {
	/dhcpd:\s+DHCP(?:DISCOVER|REQUEST).*\s+from\s+($mac_regexp)\b/ and $addresses{$1} = 1;
    }
    foreach (difference2([ keys %addresses ], [ map { $_->[0] } @{$systems->{data}} ])) {
      my $entry = [ $_ ];
      system_entry_set_profile($entry, '');
      push @{$systems->{data}}, $entry;
      gtktext_append($log_text, "Detected new system: $_\n");
    }
    1; #- run callback on next timeout
}

my ($profiles_combo, $install_button, $menu_combo);

sub refresh_profiles() {
    my @profiles = network::pxe::list_profiles($profiles_conf);
    mygtk3::gtkset($profiles_combo, list => [ '', @profiles ]);
    @{$profiles->{data}} = @profiles;
}

sub refresh_menu() {
  my $pxelinux_conf = get_pxelinux_conf_from_profile();
  my @menu = network::pxe::list_pxelinux_labels($pxelinux_conf);
  mygtk3::gtkset($menu_combo, list => [ '', @menu ]);
  my $defaultlabel = $pxelinux_conf->{default};
  my $c = 1;
  foreach (@menu) {
    if ($_ eq $defaultlabel) {
      $menu_combo->set_active($c);
     } else { $c++ }
  }
  $menu_combo->signal_connect(changed => sub {
				my $model_profiles =  $profiles->get_model;
				my $iter = $profiles->get_selection->get_selected;
				if ($iter) {
					($config_file, $help_file) = network::pxe::get_pxelinux_profile_path($model_profiles->get($iter, 0), 'boot');
					my $new_default = $menu_combo->get_active_text;
					substInFile {
					  s/DEFAULT.*/DEFAULT $new_default/;
					} $config_file;
				}
			      });
}

sub add_profile() {
    my $w = ugtk3->new(N("Add profile"));
    my ($entry);
    $w->{window}->set_position('center');
    $w->{ok_clicked} = sub {
	my $profile = $entry->get_text;
	network::pxe::profile_exists($profiles_conf, $profile) and err_dialog(N("Add profile"), N("The %s profile already exists!", $profile)), return;
	network::pxe::add_empty_profile($profiles_conf, $profile);
	refresh_profiles();
	Gtk3->main_quit;
    };
    gtkadd($w->{window},
	   gtknew('VBox', children_loose => [
	       $entry = gtknew('Entry', text => network::pxe::find_next_profile_name($profiles_conf, 'profile_name')),
	       create_okcancel($w),
	   ]));
    $w->main;
}

sub set_global_pxe_settings {
  my ($profiles_conf, $profile) = @_;
  put_in_hash($pxelinux_conf, {
			       'prompt' => 1,
			       'default' => '',
			       'display' => 'messages',
			       'timeout' => '50',
			       'f1' => 'help-$profile.txt',
			      });
}

sub write_profile_conf {
  my ($mac, $profile, $profile2, $name);
  output($conf_mac_profiles_name, "# auto generated by drakpxelinux\n");
  foreach $a (@{$systems->{data}}) {
    append_to_file($conf_mac_profiles_name, "$a->[0]|$a->[1]|$a->[2]|$a->[3]\n");
  }
}

sub profile_selected {
  my ($profile) = @_;
#  if ($profile eq 'default') {
#    ($config_file, $help_file) = ($network::pxe::pxelinux_config_file, $network::pxe::pxelinux_help_file);
#  } else {
    # force type = boot
    my $type = "boot";
    ($config_file, $help_file) = network::pxe::get_pxelinux_profile_path($profile, $type);
#    undef $pxelinux_conf;
#  }
  my $pxelinux_conf = network::pxe::read_pxelinux_conf($config_file, $help_file);
  return $pxelinux_conf;
}

sub update_treeview {
  my ($pxelinux_conf) = @_;
  $model->clear;
  set_pxelinux_entry_at_iter($model, $model->append, $_) foreach @{$pxelinux_conf->{entries}};
}

###############
# Main Program
###############
# check if first launch
if (!-f ($network::pxe::pxelinux_client_root . "/drakwizard_pxe")) {
  info_dialog(N("Please configure a PXE server"), N("It seems this is the first time you run this tool.\nA wizard will appear to configure your PXE server."));
  launch_pxe_server();
}
check_pxe_conf();

sub launch_pxe_server() {
  eval { wizard_pxe_server() };
  my $err = $@;
  $::WizardWindow->destroy if defined $::WizardWindow;
  undef $::WizardWindow;
  if ($err && $err !~ /wizcancel/) {
    err_dialog(N("Error"), N("The PXE server wizard has unexpectedly failed:") . "\n\n" . $err);
  }
}

# disable wizard
$::isWizard = 0;

my $w = ugtk3->new(N("Drakpxelinux"));
$treeview->set_rules_hint(1);
$treeview->get_selection->set_mode('single');
add_columns($treeview);

# labels that list pxe menu entry
$treeview->signal_connect(button_press_event => sub {
                            my (undef, $event) = @_;
                            my $model = $treeview->get_model;
                            my $selection = $treeview->get_selection;
                            my $iter = $selection->get_selected;
                            if ($iter) {
			      # get pxelinux_conf file
			      my $pxelinux_conf = get_pxelinux_conf_from_profile();
			      edit_box_item($model, $treeview, $pxelinux_conf) if $event->type eq '2button-press';
                            }
                          });

my @items = get_items();
my $menu = Gtk3::MenuBar->new;

my $okcancel = create_okcancel({
				cancel_clicked => sub { ugtk3->exit },
				ok_clicked => sub {
				  my $pxe_conf = get_pxelinux_conf_from_profile();
				  $pxe_conf and write_conf($pxe_conf, $treeview);
				  write_profile_conf();
				  ugtk3->exit },
			       },
			      );

# main interface
gtkpack($w->{window}, gtknew('VBox', spacing => 0, children => [
	0, $menu,
	if_(!$::isEmbedded, 0, Gtk3::Banner->new('IC-Dhost-48', N("Drakpxelinux manage your PXE server"))),
	if_($::isEmbedded, 0, Gtk3::Label->new("Here you can manage your PXE server.")),
	1, gtknew('Notebook', children => [
		      gtknew('Label', text => N("PXE configuration file")),
		      gtknew('VBox', spacing => 0, children => [
				  1, gtknew('HBox', spacing => 1, children => [
				       1, gtknew('ScrolledWindow', width => 500, height => 300, child => $treeview),
				       0, gtknew('VBox', children => [
					    0, gtknew('Label', text => N("Profiles list")),
					    1, gtknew('ScrolledWindow', child => $profiles),
					    0, gtknew('VButtonBox', layout => 'start', children_loose => [
							  gtksignal_connect(gtknew('Button', text => N("Add profile")), clicked => \&add_profile),
							  gtksignal_connect(gtknew('Button', text => N("Clone profile")), clicked => sub {
									      foreach ($profiles->get_selected_indices) {
										$profiles->{data}[$_][0] !~ /local/ ? network::pxe::clone_profile($profiles_conf, $profiles->{data}[$_][0]) : $in->ask_warn(N("Info"), N("No need to clone local profile."));
									      }
									      refresh_profiles();
									    }),
							  gtksignal_connect(gtknew('Button', text => N("Remove profile")), clicked => sub {
									      foreach ($profiles->get_selected_indices) {
										$profiles->{data}[$_][0] !~ /local/ ? network::pxe::remove_profile($profiles_conf, $profiles->{data}[$_][0]) : $in->ask_warn(N("Info"), N("Can't remove local profile."));
									      }
									      refresh_profiles();
									    }),
													 ]
						     ),
					    0, gtknew('VButtonBox', layout => 'start', children_loose => [
							  gtknew('Label', text => N("Default boot:")),
							  $menu_combo = gtknew('ComboBox'),
													 ]
						     ),
								     ]
						),
									   ]
					   ),
				     0, gtknew('HButtonBox', layout => 'start', children => [
					     0, gtksignal_connect(set_help_tip(Gtk3::Button->new(N("Add a PXE entry")), 'addpxe'), clicked => sub {
								    my $pxelinux_conf = get_pxelinux_conf_from_profile();
								    my $profile = get_selected_profile;
								    if ($profile eq "local") { $in->ask_warn(N("Info"), N("Local profile is special, and doesn't need a new entry.")) and return };
								    $pxelinux_conf and eval { wizard_add_entry($model, $treeview, $pxelinux_conf);
									   write_conf($pxelinux_conf, $treeview);
									 };
								    my $err = $@;
								    $::WizardWindow->destroy if defined $::WizardWindow;
								    undef $::WizardWindow;
								    if ($err && $err !~ /wizcancel/) {
								      err_dialog(N("Error"), N("The PXE entry wizard has unexpectedly failed:") . "\n\n" . $err);
								    }
								  }),
					     0, gtksignal_connect(set_help_tip(Gtk3::Button->new(N("Remove PXE entry")), 'removepxe'), clicked => sub { 
								    my $pxelinux_conf = get_pxelinux_conf_from_profile();
								    remove_item($model, $treeview, $pxelinux_conf);
								    #write_conf($pxelinux_conf, $treeview);
								  }),
					     0, gtksignal_connect(set_help_tip(Gtk3::Button->new(N("Edit PXE entry")), 'editb'), clicked => sub {
								    my $pxelinux_conf = get_pxelinux_conf_from_profile();
								    edit_box_item($model, $treeview, $pxelinux_conf);
								    #write_conf($pxelinux_conf, $treeview);
								  }),
					     0, gtksignal_connect(Gtk3::Button->new(N("Clone PXE entry")), clicked => sub {
								    my $pxelinux_conf = get_pxelinux_conf_from_profile();
								    clone_box_item($model, $treeview, $pxelinux_conf);
								  }),
											    ]),
							       ]),
		      gtknew('Label', text => N("Systems")),
		      gtknew('VBox', spacing => 1,
				     children => [
						  1, gtknew('ScrolledWindow', child => $systems),
						  0, gtknew('HBox',
							    children_loose => [
							       gtksignal_connect(gtknew('Button', text => N("Set installation profile")), clicked => sub {
										   my $profile = $profiles_combo->get_active_text;
										   my $to_install = exists $profiles_conf->{profiles}{install}{$profile};
										   foreach ($systems->get_selected_indices) {
										     my $entry = $systems->{data}[$_];
										     network::pxe::set_profile_for_mac_address($profile, $to_install, $entry->[0]);
										     system_entry_set_profile($entry, $profile);
										   }
										   write_profile_conf();
										 }),
							       gtksignal_connect(gtknew('Button', text => N("Set boot profile")), clicked => sub {
										   my $profile = $profiles_combo->get_active_text;
										   foreach ($systems->get_selected_indices) {
										     my $entry = $systems->{data}[$_];
										     system_entry_set_profile2($entry, $profile);
										   }
										   write_profile_conf();
										 }),
							       $profiles_combo = gtknew('ComboBox'),
									      ]),
						 ]),
		      gtknew('Label', text => N("Log")),
		      gtknew('VBox', spacing => 1, children_loose => [
				       gtknew('ScrolledWindow', width => 600, height => 400, child => $log_text),
									     ]),
				     ]),
	0, $okcancel,
							       ]),
       );

add_local_profil_entry();
add_configured_mac_addresses();
get_mac_addresses_from_dhcp_log();
update_systems_data_from_file();
$SIG{USR1} = sub {
  update_systems_data_from_file();
};
Glib::Timeout->add(60000, \&get_mac_addresses_from_dhcp_log);
refresh_profiles();
$w->show;

Gtk3->main;