source: devel/pb/bin/pb @ 1402

Last change on this file since 1402 was 1402, checked in by bruno, 7 years ago

r4487@cabanilles: bruno | 2012-02-01 16:21:48 +0100

  • Fix the -t option without param for pb
  • add a function to analyze busybox countent and create appropriate structure for pbmkbm
  • Property svn:executable set to *
File size: 131.0 KB
Line 
1#!/usr/bin/perl -w
2#
3# Project Builder main application
4#
5# $Id$
6#
7# Copyright B. Cornec 2007-2011
8# Provided under the GPL v2
9
10# Syntax: see at end
11
12use strict 'vars';
13
14# The modules mentioned here are required by pb when used both
15# locally or inside a VE/VM/RM
16# Additional required modules only used locally are called with a require
17# in their respective section
18use Getopt::Long qw(:config auto_abbrev no_ignore_case);
19use Data::Dumper;
20use English;
21use File::Basename;
22use File::Copy;
23use File::stat;
24use File::Temp qw(tempdir);
25use File::Find;
26use Time::localtime qw(localtime);
27use POSIX qw(strftime);
28use lib qw (lib);
29use ProjectBuilder::Version;
30use ProjectBuilder::Base;
31use ProjectBuilder::Display;
32use ProjectBuilder::Conf;
33use ProjectBuilder::Distribution;
34use ProjectBuilder::CMS;
35use ProjectBuilder::Env;
36use ProjectBuilder::Filter;
37use ProjectBuilder::Changelog;
38use ProjectBuilder::VE;
39
40# Global variables
41my %opts;                   # CLI Options
42my $action;                 # action to realize
43my $test = "FALSE";         # Not used
44my $pbforce = 0;            # Force VE/VM rebuild
45my $pbsnap = 0;             # Do not use snapshot mode for VM/VE by default
46my $option = "";            # Not used
47my @pkgs;                   # list of packages
48my $pbtag;                  # Global Tag variable
49my $pbver;                  # Global Version variable
50my $pbscript;               # Name of the script
51my %pbver;                  # per package
52my %pbtag;                  # per package
53my $pbrev;                  # Global REVISION variable
54my $pbaccount;              # Login to use to connect to the VM/RM
55my $pbtarget = undef;       # Target os-ver-arch you want to build for
56my $pbport;                 # Port to use to connect to the VM/RM
57my $newver;                 # New version to create
58my $iso = undef;            # ISO image for the VM to create
59
60my @date = pb_get_date();
61my $pbdate = strftime("%Y-%m-%d", @date);
62
63=pod
64
65=head1 NAME
66
67pb, aka project-builder.org - builds packages for your projects
68
69=head1 DESCRIPTION
70
71pb helps you build various packages directly from your project sources.
72Those sources could be handled by a CMS (Configuration Management System)
73such as Subversion, CVS, Git, Mercurial... or being a simple reference to a compressed tar file.
74It's based on a set of configuration files, a set of provided macros to help
75you keeping build files as generic as possible. For example, a single .spec
76file should be required to generate for all rpm based distributions, even
77if you could also have multiple .spec files if required.
78
79=head1 SYNOPSIS
80
81pb [-vhSq][-r pbroot][-p project][[-s script -a account -P port][-t [os-ver-arch]][-m os-ver-arch[,...]]][-g][-i iso] <action> [<pkg1> ...]
82
83pb [--verbose][--help][--man][--quiet][--snapshot][--revision pbroot][--project project][[--script script --account account --port port][--target [os-ver-arch]][--machine os-ver-arch[,...]]][--nographic][--iso iso][--rebuild] <action> [<pkg1> ...]
84
85=head1 OPTIONS
86
87=over 4
88
89=item B<-v|--verbose>
90
91Print a brief help message and exits.
92
93=item B<-q|--quiet>
94
95Do not print any output.
96
97=item B<-h|--help>
98
99Print a brief help message and exits.
100
101=item B<-S|--snapshot>
102
103Use the snapshot mode of VMs or VEs
104
105=item B<--man>
106
107Prints the manual page and exits.
108
109=item B<-t|--target os-ver-arch>
110
111Name of the target system you want to build for.
112All if none precised.
113
114=item B<-m|--machine os-ver-arch[,os-ver-arch,...]>
115
116Name of the Virtual Machines (VM), Virtual Environments (VE) or Remote Machines (RM)
117you want to build on (coma separated).
118All if none precised (or use the env variable PBV).
119
120=item B<-s|--script script>
121
122Name of the script you want to execute on the related VMs/VEs/RMs.
123
124=item B<-g|--nographic>
125
126Do not launch VMs in graphical mode.
127
128=item B<-i|--iso iso_image>
129
130Name of the ISO image of the distribution you want to install on the related VMs.
131
132=item B<-a|--account account>
133
134Name of the account to use to connect on the related VMs/RMs.
135
136=item B<-P|--port port_number>
137
138Port number to use to connect on the related VMs/RMs.";
139
140=item B<-p|--project project_name>
141
142Name of the project you're working on (or use the env variable PBPROJ)
143
144=item B<-r|--revision revision>
145
146Path Name of the project revision under the CMS (or use the env variable PBROOT)
147
148=item B<-V|--version new_version>
149
150New version of the project to create based on the current one.
151
152=item B<--rebuild>
153
154Only valid with the checkssh action, it alllows to automatically relaunch the build of the failed packages
155
156=back
157
158=head1 ARGUMENTS
159
160<action> can be:
161
162=over 4
163
164=item B<sbx2build>
165
166Create tar files for the project under your CMS.
167Current state of the exported content is taken.
168CMS supported are SVN, SVK, CVS, Git and Mercurial
169parameters are packages to build
170if not using default list
171
172=item B<cms2build>
173
174Create tar files for the project under your CMS.
175Current state of the CMS is taken.
176CMS supported are SVN, SVK, CVS, Git and Mercurial
177parameters are packages to build
178if not using default list
179
180=item B<build2pkg>
181
182Create packages for your running distribution
183
184=item B<cms2pkg>
185
186cms2build + build2pkg
187
188=item B<sbx2pkg>
189
190sbx2build + build2pkg
191
192=item B<build2ssh>
193
194Send the tar files to a SSH host
195
196=item B<sbx2ssh>
197
198sbx2build + build2ssh
199
200=item B<cms2ssh>
201
202cms2build + build2ssh
203
204=item B<pkg2ssh>
205
206Send the packages built to a SSH host
207
208=item B<build2vm>
209
210Create packages in VMs, launching them if needed
211and send those packages to a SSH host once built
212VM type supported are QEMU and KVM
213
214=item B<build2ve>
215
216Create packages in VEs, creating it if needed
217and send those packages to a SSH host once built
218
219=item B<build2rm>
220
221Create packages in RMs, which should pre-exist,
222and send those packages to a SSH host once built
223RM means Remote Machine, and could be a physical or Virtual one.
224This is one buildfarm integration for pb.
225
226=item B<sbx2vm>
227
228sbx2build + build2vm
229
230=item B<sbx2ve>
231
232sbx2build + build2ve
233
234=item B<sbx2rm>
235
236sbx2build + build2rm
237
238=item B<cms2vm>
239
240cms2build + build2vm
241
242=item B<cms2ve>
243
244cms2build + build2ve
245
246=item B<cms2rm>
247
248cms2build + build2rm
249
250=item B<launchvm>
251
252Launch one virtual machine
253
254=item B<launchve>
255
256Launch one virtual environment
257
258=item B<script2vm>
259
260Launch one virtual machine if needed
261and executes a script on it
262
263=item B<script2ve>
264
265Execute a script in a virtual environment
266
267=item B<script2rm>
268
269Execute a script on a remote machine
270
271=item B<newvm>
272
273Create a new virtual machine
274
275=item B<newve>
276
277Create a new virtual environment
278
279=item B<setupvm>
280
281Setup a virtual machine for pb usage
282
283=item B<setupve>
284
285Setup a virtual environment for pb usage
286
287=item B<setuprm>
288
289Setup a remote machine for pb usage
290
291=item B<sbx2setupvm>
292
293Setup a virtual machine for pb usage using the sandbox version of pb instead of the latest stable
294Reserved to dev team.
295
296=item B<sbx2setupve>
297
298Setup a virtual environment for pb usage using the sandbox version of pb instead of the latest stable
299Reserved to dev team.
300
301=item B<sbx2setuprm>
302
303Setup a remote machine for pb usage using the sandbox version of pb instead of the latest stable
304Reserved to dev team.
305
306=item B<snapvm>
307
308Snapshot a virtual machine for pb usage
309
310=item B<snapve>
311
312Snapshot a virtual environment for pb usage
313
314=item B<updatevm>
315
316Update the distribution in the virtual machine
317
318=item B<updateve>
319
320Update the distribution in the virtual environment
321
322=item B<updaterm>
323
324Update the distribution in the remote machine
325
326=item B<test2pkg>
327
328Test a package locally
329
330=item B<test2vm>
331
332Test a package in a virtual machine
333
334=item B<test2ve>
335
336Test a package in a virtual environment
337
338=item B<test2rm>
339
340Test a package in a remote machine
341
342=item B<checkssh>
343
344Check the delivery of the packages on the repository
345
346=item B<newver>
347
348Create a new version of the project derived
349from the current one
350
351=item B<newproj>
352
353Create a new project and a template set of
354configuration files under pbconf
355
356=item B<announce>
357
358Announce the availability of the project through various means
359
360=item B<sbx2webssh>
361
362Create tar files for the website under your CMS.
363Current state of the exported content is taken.
364Deliver the content to the target server using ssh from the exported dir.
365
366=item B<cms2webssh>
367
368Create tar files for the website from your CMS.
369Deliver the content to the target server using ssh from the DVCS.
370
371=item B<sbx2webpkg>
372
373Create tar files for the website under your CMS.
374Current state of the exported content is taken.
375
376=item B<cms2webpkg>
377
378Create tar files for the website under your CMS.
379
380=item B<clean>
381
382Purge the build and delivery directories related to the current project
383
384=back
385
386=item B<cleanssh>
387
388Purge the ssh server of its packages (only for testver and test packages)
389
390=back
391
392<pkgs> can be a list of packages, the keyword 'all' or nothing, in which case the default list of packages is taken (corresponding to the defpkgdir list of arguments in the configuration file).
393
394=head1 WEB SITES
395
396The main Web site of the project is available at L<http://www.project-builder.org/>. Bug reports should be filled using the trac instance of the project at L<http://trac.project-builder.org/>.
397
398=head1 USER MAILING LIST
399
400None exists for the moment.
401
402=head1 CONFIGURATION FILES
403
404Each pb user may have a configuration in F<$HOME/.pbrc>. The values in this file may overwrite any other configuration file value.
405
406Here is an example of such a configuration file:
407
408 #
409 # Define for each project the URL of its pbconf repository
410 # No default option allowed here as they need to be all different
411 #
412 # URL of the pbconf content
413 # This is the format of a classical URL with the extension of additional schema such as
414 # svn+ssh, cvs+ssh, ...
415 #
416 pbconfurl linuxcoe = cvs+ssh://:ext:bcornec@linuxcoe.cvs.sourceforge.net:/cvsroot/linuxcoe/pbconf
417
418 # This is normaly defined in the project's configuration file
419 # Url of the project
420 #
421 pburl linuxcoe = cvs+ssh://:ext:bcornec@linuxcoe.cvs.sourceforge.net:/cvsroot/linuxcoe
422 
423 # All these URLs needs to be defined here as the are the entry point
424 # for how to build packages for the project
425 #
426 pbconfurl pb = svn+ssh://svn.project-builder.org/mondo/svn/pb/pbconf
427 pbconfurl mondorescue = svn+ssh://svn.project-builder.org/mondo/svn/project-builder/mondorescue/pbconf
428 pbconfurl collectl = svn+ssh://bruno@svn.mondorescue.org/mondo/svn/project-builder/collectl/pbconf
429 pbconfurl netperf = svn+ssh://svn.mondorescue.org/mondo/svn/project-builder/netperf/pbconf
430 
431 # Under that dir will take place everything related to pb
432 # If you want to use VMs/chroot/..., then use $ENV{'HOME'} to make it portable
433 # to your VMs/chroot/...
434 # if not defined then /var/cache
435 pbdefdir default = $ENV{'HOME'}/project-builder
436 pbdefdir pb = $ENV{'HOME'}
437 pbdefdir linuxcoe = $ENV{'HOME'}/LinuxCOE/cvs
438 pbdefdir mondorescue = $ENV{'HOME'}/mondo/svn
439 
440 # pbconfdir points to the directory where the CMS content of the pbconfurl is checked out
441 # If not defined, pbconfdir is under pbdefdir/pbproj/pbconf
442 pbconfdir linuxcoe = $ENV{'HOME'}/LinuxCOE/cvs/pbconf
443 pbconfdir mondorescue = $ENV{'HOME'}/mondo/svn/pbconf
444 
445 # pbdir points to the directory where the CMS content of the pburl is checked out
446 # If not defined, pbdir is under pbdefdir/pbproj
447 # Only defined if we have access to the dev of the project
448 pbdir linuxcoe = $ENV{'HOME'}/LinuxCOE/cvs
449 pbdir mondorescue = $ENV{'HOME'}/mondo/svn
450 
451 # -daemonize doesn't work with qemu 0.8.2
452 vmopt default = -m 384
453
454=head1 AUTHORS
455
456The Project-Builder.org team L<http://trac.project-builder.org/> lead by Bruno Cornec L<mailto:bruno@project-builder.org>.
457
458=head1 COPYRIGHT
459
460Project-Builder.org is distributed under the GPL v2.0 license
461described in the file C<COPYING> included with the distribution.
462
463=cut
464
465# ---------------------------------------------------------------------------
466
467my ($projectbuilderver,$projectbuilderrev) = pb_version_init();
468my $appname = "pb";
469
470# Initialize the syntax string
471
472pb_syntax_init("$appname (aka project-builder.org) Version $projectbuilderver-$projectbuilderrev\n");
473
474GetOptions("help|?|h" => \$opts{'h'}, 
475        "man" => \$opts{'man'},
476        "verbose|v+" => \$opts{'v'},
477        "snapshot|S" => \$opts{'S'},
478        "quiet|q" => \$opts{'q'},
479        "log-files|l=s" => \$opts{'l'},
480        "force|f" => \$opts{'f'},
481        "account|a=s" => \$opts{'a'},
482        "revision|r=s" => \$opts{'r'},
483        "script|s=s" => \$opts{'s'},
484        "machines|mock|m=s" => \$opts{'m'},
485        "target|t:s" => \$opts{'t'},
486        "nographic|g" => \$opts{'g'},
487        "port|P=i" => \$opts{'P'},
488        "project|p=s" => \$opts{'p'},
489        "rebuild" => \$opts{'rebuild'},
490        "iso|i=s" => \$opts{'i'},
491        "version|V=s" => \$opts{'V'},
492) || pb_syntax(-1,0);
493
494if (defined $opts{'h'}) {
495    pb_syntax(0,1);
496}
497if (defined $opts{'man'}) {
498    pb_syntax(0,2);
499}
500if (defined $opts{'v'}) {
501    $pbdebug = $opts{'v'};
502}
503if (defined $opts{'f'}) {
504    $pbforce=1;
505}
506if (defined $opts{'q'}) {
507    $pbdebug=-1;
508}
509if (defined $opts{'S'}) {
510    $pbsnap=1;
511}
512if (defined $opts{'l'}) {
513    open(pbLOG,"> $opts{'l'}") || die "Unable to log to $opts{'l'}: $!";
514    $pbLOG = \*pbLOG;
515    $pbdebug = 0  if ($pbdebug == -1);
516    }
517pb_log_init($pbdebug, $pbLOG);
518pb_display_init("text","");
519
520# Handle root of the project if defined
521if (defined $opts{'r'}) {
522    $ENV{'PBROOTDIR'} = $opts{'r'};
523}
524# Handle virtual machines if any
525if (defined $opts{'m'}) {
526    $ENV{'PBV'} = $opts{'m'};
527}
528if (defined $opts{'s'}) {
529    $pbscript = $opts{'s'};
530}
531if (defined $opts{'a'}) {
532    $pbaccount = $opts{'a'};
533    die "option -a requires a -s script option" if (not defined $pbscript);
534}
535if (defined $opts{'P'}) {
536    $pbport = $opts{'P'};
537}
538if (defined $opts{'V'}) {
539    $newver = $opts{'V'};
540}
541if (defined $opts{'i'}) {
542    $iso = $opts{'i'};
543}
544if (defined $opts{'t'}) {
545    $pbtarget = $opts{'t'};
546}
547
548# Get Action
549$action = shift @ARGV;
550die pb_syntax(-1,1) if (not defined $action);
551
552my ($filteredfiles, $supfiles, $defpkgdir, $extpkgdir);
553my $pbinit = undef;
554$pbinit = 1 if ($action =~ /^newproj$/);
555
556# Handles project name if any
557# And get global params
558($filteredfiles, $supfiles, $defpkgdir, $extpkgdir) = pb_env_init($opts{'p'},$pbinit,$action);
559
560#
561# Check for command requirements
562#
563my ($req,$opt,$pbpara) = pb_conf_get_if("oscmd","oscmdopt","pbparallel");
564pb_check_requirements($req,$opt,$appname);
565
566#
567# Check if we can launch some actions in // with Parallel::ForkManager
568#
569my $pbparallel = $pbpara->{$appname} if (defined $pbpara);
570if (not defined $pbparallel) {
571    eval
572    {
573        require Sys::CPU;
574        Sys::CPU->import();
575    };
576    if ($@) {
577        # Sys::CPU not found, defaulting to 1
578        pb_log(1,"ADVISE: Install Sys::CPU to benefit from automatic parallelism optimization.\nOr use pbparallel in your pb.conf file\nOnly 1 process at a time for the moment\n");
579        $pbparallel = 1;
580    } else {
581        # Using the number of cores
582        $pbparallel = Sys::CPU::cpu_count();
583        pb_log(1,"Using parallel mode with $pbparallel processes\n");
584    }
585}
586
587eval
588{
589    require Parallel::ForkManager;
590    Parallel::ForkManager->import();
591};
592# Parallel::ForkManager not found so no // actions
593if ($@) {
594    $pbparallel = undef;
595    pb_log(1,"ADVISE: Install Parallel::ForkManager to benefit from automatic parallelism optimization.\nOnly 1 process at a time for the moment\n");
596}
597
598pb_log(0,"Project: $ENV{'PBPROJ'}\n");
599pb_log(0,"Action: $action\n");
600
601# Act depending on action
602if ($action =~ /^cms2build$/) {
603    pb_cms2build("CMS");
604} elsif ($action =~ /^sbx2build$/) {
605    pb_cms2build("SandBox");
606} elsif ($action =~ /^build2pkg$/) {
607    pb_build2pkg();
608} elsif ($action =~ /^cms2pkg$/) {
609    pb_cms2build("CMS");
610    pb_build2pkg();
611} elsif ($action =~ /^sbx2pkg$/) {
612    pb_cms2build("SandBox");
613    pb_build2pkg();
614} elsif ($action =~ /^build2ssh$/) {
615    pb_build2ssh();
616} elsif ($action =~ /^cms2ssh$/) {
617    pb_cms2build("CMS");
618    pb_build2ssh();
619} elsif ($action =~ /^sbx2ssh$/) {
620    pb_cms2build("SandBox");
621    pb_build2ssh();
622} elsif ($action =~ /^pkg2ssh$/) {
623    pb_pkg2ssh();
624} elsif ($action =~ /^build2rm$/) {
625    pb_build2v("rm","build");
626} elsif ($action =~ /^build2ve$/) {
627    pb_build2v("ve","build");
628} elsif ($action =~ /^build2vm$/) {
629    pb_build2v("vm","build");
630} elsif ($action =~ /^cms2rm$/) {
631    pb_cms2build("CMS");
632    pb_build2v("rm","build");
633} elsif ($action =~ /^cms2ve$/) {
634    pb_cms2build("CMS");
635    pb_build2v("ve","build");
636} elsif ($action =~ /^sbx2rm$/) {
637    pb_cms2build("SandBox");
638    pb_build2v("rm","build");
639} elsif ($action =~ /^sbx2ve$/) {
640    pb_cms2build("SandBox");
641    pb_build2v("ve","build");
642} elsif ($action =~ /^cms2vm$/) {
643    pb_cms2build("CMS");
644    pb_build2v("vm","build");
645} elsif ($action =~ /^sbx2vm$/) {
646    pb_cms2build("SandBox");
647    pb_build2v("vm","build");
648} elsif ($action =~ /^launchvm$/) {
649    pb_launchv("vm",$ENV{'PBV'},0);
650} elsif ($action =~ /^launchve$/) {
651    pb_launchv("ve",$ENV{'PBV'},0);
652} elsif ($action =~ /^script2vm$/) {
653    pb_script2v($pbscript,"vm");
654} elsif ($action =~ /^script2ve$/) {
655    pb_script2v($pbscript,"ve");
656} elsif ($action =~ /^script2rm$/) {
657    pb_script2v($pbscript,"rm");
658} elsif ($action =~ /^newver$/) {
659    pb_newver();
660} elsif ($action =~ /^newve$/) {
661    pb_launchv("ve",$ENV{'PBV'},1);
662} elsif ($action =~ /^newvm$/) {
663    pb_launchv("vm",$ENV{'PBV'},1);
664    pb_log(0, "Please ensure that sshd is running in your VM by default\n");
665    pb_log(0, "and that it allows remote root login (PermitRootLogin yes in /etc/ssh/sshd_config)\n");
666    pb_log(0, "Also ensure that network is up, firewalling correctly configured\n");
667    pb_log(0, "and perl, sudo, ntpdate and scp/ssh installed\n");
668    pb_log(0, "You should then be able to login with ssh -p VMPORT root\@localhost (if VM started with pb)\n");
669} elsif ($action =~ /^setuprm$/) {
670    pb_setup2v("rm");
671} elsif ($action =~ /^setupve$/) {
672    pb_setup2v("ve");
673} elsif ($action =~ /^setupvm$/) {
674    pb_setup2v("vm");
675} elsif ($action =~ /^sbx2setuprm$/) {
676    die "This feature is limited to the pb project" if ($ENV{'PBPROJ'} ne $appname);
677    pb_cms2build("SandBox");
678    pb_setup2v("rm","SandBox");
679} elsif ($action =~ /^sbx2setupve$/) {
680    die "This feature is limited to the pb project" if ($ENV{'PBPROJ'} ne $appname);
681    pb_cms2build("SandBox");
682    pb_setup2v("ve","SandBox");
683} elsif ($action =~ /^sbx2setupvm$/) {
684    die "This feature is limited to the pb project" if ($ENV{'PBPROJ'} ne $appname);
685    pb_cms2build("SandBox");
686    pb_setup2v("vm","SandBox");
687} elsif ($action =~ /^updaterm$/) {
688    pb_update2v("rm");
689} elsif ($action =~ /^updateve$/) {
690    pb_update2v("ve");
691} elsif ($action =~ /^updatevm$/) {
692    pb_update2v("vm");
693} elsif ($action =~ /^snapve$/) {
694    pb_snap2v("ve");
695} elsif ($action =~ /^snapvm$/) {
696    pb_snap2v("vm");
697} elsif ($action =~ /^test2pkg$/) {
698    pb_test2pkg();
699} elsif ($action =~ /^test2rm$/) {
700    pb_build2v("rm","test");
701} elsif ($action =~ /^test2ve$/) {
702    pb_build2v("ve","test");
703} elsif ($action =~ /^test2vm$/) {
704    pb_build2v("vm","test");
705} elsif ($action =~ /^newproj$/) {
706    # Nothing to do - already done in pb_env_init
707} elsif ($action =~ /^clean$/) {
708    pb_clean();
709} elsif ($action =~ /^announce$/) {
710    # For announce only. Require avoids the systematic load of these modules
711    require DBI;
712    require DBD::SQLite;
713
714    pb_announce("Announce");
715} elsif ($action =~ /^cleanssh$/) {
716    pb_announce("Clean");
717} elsif ($action =~ /^checkssh$/) {
718    pb_announce("Check");
719} elsif ($action =~ /^sbx2webpkg$/) {
720    require DBI;
721    require DBD::SQLite;
722
723    pb_cms2build("SandBox","Web");
724} elsif ($action =~ /^sbx2webssh$/) {
725    require DBI;
726    require DBD::SQLite;
727
728    pb_cms2build("SandBox","Web");
729    pb_send2target("Web");
730} elsif ($action =~ /^cms2webpkg$/) {
731    require DBI;
732    require DBD::SQLite;
733
734    pb_cms2build("CMS","Web");
735} elsif ($action =~ /^cms2webssh$/) {
736    require DBI;
737    require DBD::SQLite;
738
739    pb_cms2build("CMS","Web");
740    pb_send2target("Web");
741} else {
742    pb_log(0,"\'$action\' is not available\n");
743    pb_syntax(-2,1);
744}
745
746sub pb_cms2build {
747
748    my $param = shift || undef;
749    my $web = shift || undef;
750
751    my $pkg;
752    my @pkgs;
753    my $webdir;
754
755    my %pkgs;
756    my $pb;             # Structure to store conf info
757
758    die "pb_cms2build requires a parameter: SandBox or CMS" if (not defined $param);
759
760    # If Website, then pkg is only the website
761    if (defined $web) {
762        ($webdir) = pb_conf_get("webdir");
763        pb_log(2,"webdir: ".Dumper($webdir)."\n");
764        $pkgs[0] = $webdir->{$ENV{'PBPROJ'}};
765        $extpkgdir = $webdir;
766        pb_log(0,"Package: $pkgs[0]\n");
767    } else {
768        $pkg = pb_cms_get_pkg($defpkgdir,$extpkgdir);
769        @pkgs = @$pkg;
770    }
771
772    my ($scheme, $uri) = pb_cms_init($pbinit,$param);
773
774    # We need 2 lines here
775    my ($pkgv, $pkgt, $testver) = pb_conf_get_if("pkgver","pkgtag","testver");
776
777    # declare packager and repo for filtering
778    my ($tmp1, $tmp2) = pb_conf_get("pbpackager","pbrepo");
779    $ENV{'PBPACKAGER'} = $tmp1->{$ENV{'PBPROJ'}};
780    $ENV{'PBREPO'} = $tmp2->{$ENV{'PBPROJ'}};
781    my ($delivery) = pb_conf_get_if("delivery");
782    $delivery->{$ENV{'PBPROJ'}} = "" if (not defined $delivery->{$ENV{'PBPROJ'}});
783
784    foreach my $pbpkg (@pkgs) {
785        $ENV{'PBPKG'} = $pbpkg;
786
787        if ((defined $pkgv) && (defined $pkgv->{$pbpkg})) {
788            $pbver = $pkgv->{$pbpkg};
789        } else {
790            $pbver = $ENV{'PBPROJVER'};
791        }
792        # If it's a test version, then tag == 0.date
793        if ((defined $testver) && (defined $testver->{$ENV{'PBPROJ'}}) && ($testver->{$ENV{'PBPROJ'}} =~ /true/i)) {
794            $pbtag = "0.".strftime("%Y%m%d%H%M%S", @date);
795            $ENV{'PBPROJTAG'} = $pbtag;
796        } elsif ((defined $pkgt) && (defined $pkgt->{$pbpkg})) {
797            $pbtag = $pkgt->{$pbpkg};
798        } else {
799            $pbtag = $ENV{'PBPROJTAG'};
800        }
801
802        $pbrev = $ENV{'PBREVISION'};
803        pb_log(0,"\n");
804        pb_log(0,"Management of $pbpkg $pbver-$pbtag (rev $pbrev)\n");
805        die "Unable to get env var PBDESTDIR" if (not defined $ENV{'PBDESTDIR'});
806
807        my $dest = "$ENV{'PBDESTDIR'}/$pbpkg-$pbver";
808        # Create the structure if needed
809        pb_mkdir_p($dest);
810        # Clean up dest if necessary. The export will recreate it
811        pb_rm_rf($dest) if (-d $dest);
812
813        # Export CMS tree for the concerned package to dest
814        # And generate some additional files
815        $OUTPUT_AUTOFLUSH=1;
816
817        # computes in which dir we have to work
818        my $dir = $defpkgdir->{$pbpkg};
819        $dir = $extpkgdir->{$pbpkg} if (not defined $dir);
820        $dir = $webdir->{$ENV{'PBPROJ'}} if (defined $web);
821        die "Variable \$dir not defined. Please report to dev team with log of a verbose run and this info ".Dumper($webdir) if (not defined $dir);
822        pb_log(2,"def:".Dumper($defpkgdir)."ext: ".Dumper($extpkgdir)."dir: $dir\n");
823
824        # Exporting content from CMS
825        my $sourcedir = undef;
826        my $sourceuri = $uri;
827        if ($param eq "SandBox") {
828            # Point to the local instance
829            $sourcedir = "$ENV{'PBDIR'}/$dir";
830        } else {
831            # Get it from a subdir of the URI with same version as localy but different root
832            # Only if using a real CMS
833            my ($scheme, $account, $host, $port, $path) = pb_get_uri($uri);
834            if (($scheme !~ /^file/) && ($scheme !~ /^(ht|f)tp/)) {
835                $sourceuri = "$ENV{'PBDIR'}/$dir"; 
836                $sourceuri =~ s|^$ENV{'PBPROJDIR'}/|$uri/|;
837            }
838        }
839        my $preserve = pb_cms_export($sourceuri,$sourcedir,$dest);
840
841        # Generated fake content for test versions to speed up stuff
842        my $chglog;
843
844        # Get project info on authors and log file
845        # TODO: Make it CMS aware
846        $chglog = "$ENV{'PBROOTDIR'}/$pbpkg/pbcl";
847        $chglog = "$ENV{'PBROOTDIR'}/pbcl" if (! -f $chglog);
848        $chglog = undef if (! -f $chglog);
849
850        # TODO: Make it CMS aware
851        my $authors = "$ENV{'PBROOTDIR'}/$pbpkg/pbauthors";
852        $authors = "$ENV{'PBROOTDIR'}/pbauthors" if (! -f $authors);
853        $authors = "/dev/null" if (! -f $authors);
854
855        # Extract cms log history and store it
856        if ((defined $chglog) && (! -f "$dest/NEWS")) {
857            pb_log(2,"Generating NEWS file from $chglog\n");
858            copy($chglog,"$dest/NEWS") || die "Unable to create $dest/NEWS";
859        }
860        pb_cms_log($scheme,"$ENV{'PBDIR'}/$dir",$dest,$chglog,$authors,$testver);
861
862        my %build;
863        # We want to at least build for the underlying distro
864        # except if a target was given, in which case we only build for it
865        # if -t was passed without target then build for the native distro.
866        my $pbos = pb_distro_get_context($pbtarget);
867        my $tmpl = pb_get_distros($pbos,$pbtarget);
868
869        # Setup $pb structure to allow filtering later on, on files using that structure
870        $pb->{'tag'} = $pbtag;
871        $pb->{'rev'} = $pbrev;
872        $pb->{'ver'} = $pbver;
873        $pb->{'pkg'} = $pbpkg;
874        $pb->{'suf'} = $pbos->{'suffix'};
875        $pb->{'realpkg'} = $pbpkg;
876        $pb->{'date'} = $pbdate;
877        $pb->{'defpkgdir'} = $defpkgdir;
878        $pb->{'extpkgdir'} = $extpkgdir;
879        $pb->{'chglog'} = $chglog;
880        $pb->{'packager'} = $ENV{'PBPACKAGER'};
881        $pb->{'proj'} = $ENV{'PBPROJ'};
882        $pb->{'repo'} = "$ENV{'PBREPO'}/$delivery->{$ENV{'PBPROJ'}}";
883        $pb->{'patches'} = ();
884        $pb->{'sources'} = ();
885   
886        my $tmpd = "$ENV{'PBTMP'}/cms.$$";
887        pb_mkdir_p($tmpd) if (defined $pbparallel);
888
889        # Get only all.pbf filter at this stage for pbinit
890        my $ptr = pb_get_filters($pbpkg);
891
892        # Do not do that for website
893        if (not defined $web) {
894            my %virt;
895            # De-duplicate similar VM/VE/RM
896            foreach my $d (split(/,/,$tmpl)) {
897                # skip ill-formatted vms (name-ver-arch)
898                next if ($d !~ /-/);
899                $virt{$d} = $d;
900            }
901
902            # Try to use // processing here
903            my $pm = new Parallel::ForkManager($pbparallel) if (defined $pbparallel);
904
905            pb_log(0,"Preparing delivery ...\n");
906            foreach my $v (keys %virt) {
907                $pm->start and next if (defined $pbparallel);
908
909                # Distro context
910                my $pbos = pb_distro_get_context($v);
911   
912                $pb->{'pbos'} = $pbos;
913                $pb->{'suf'} = $pbos->{'suffix'};
914                pb_log(3,"DEBUG: pb: ".Dumper($pb)."\n");
915
916                # Get all filters to apply
917                $ptr = pb_get_filters($pbpkg,$pbos);
918   
919                pb_log(2,"DEBUG Filtering PBDATE => $pbdate, PBTAG => $pbtag, PBVER => $pbver\n");
920   
921                # We need to compute the real name of the package
922                my $pbrealpkg = pb_cms_get_real_pkg($pbpkg,$pbos->{'type'});
923                $pb->{'realpkg'} = $pbrealpkg;
924                pb_log(1,"Virtual package $pbpkg has a real package name of $pbrealpkg on $pbos->{'name'}-$pbos->{'version'}\n") if ($pbrealpkg ne $pbpkg);
925   
926                # Filter build files from the less precise up to the most with overloading
927                # Filter all files found, keeping the name, and generating in dest
928   
929                # Find all build files first relatively to PBROOTDIR
930                # Find also all specific files referenced in the .pb conf file
931                my %bfiles = ();
932                my %pkgfiles = ();
933                # Used in Filter.pm by pb_filter_file
934
935                $build{$v} = "no";
936                if (-d "$ENV{'PBROOTDIR'}/$pbpkg/$pbos->{'os'}") {
937                    pb_list_bfiles("$ENV{'PBROOTDIR'}/$pbpkg/$pbos->{'os'}",$pbpkg,\%bfiles,\%pkgfiles,$supfiles);
938                    $build{$v} = "yes";
939                } 
940                if (-d "$ENV{'PBROOTDIR'}/$pbpkg/$pbos->{'type'}") {
941                    pb_list_bfiles("$ENV{'PBROOTDIR'}/$pbpkg/$pbos->{'type'}",$pbpkg,\%bfiles,\%pkgfiles,$supfiles);
942                    $build{$v} = "yes";
943                } 
944                if (-d "$ENV{'PBROOTDIR'}/$pbpkg/$pbos->{'family'}") {
945                    pb_list_bfiles("$ENV{'PBROOTDIR'}/$pbpkg/$pbos->{'family'}",$pbpkg,\%bfiles,\%pkgfiles,$supfiles);
946                    $build{$v} = "yes";
947                } 
948                if (-d "$ENV{'PBROOTDIR'}/$pbpkg/$pbos->{'name'}") {
949                    pb_list_bfiles("$ENV{'PBROOTDIR'}/$pbpkg/$pbos->{'name'}",$pbpkg,\%bfiles,\%pkgfiles,$supfiles);
950                    $build{$v} = "yes";
951                } 
952                if (-d "$ENV{'PBROOTDIR'}/$pbpkg/$pbos->{'name'}-$pbos->{'version'}") {
953                    pb_list_bfiles("$ENV{'PBROOTDIR'}/$pbpkg/$pbos->{'name'}-$pbos->{'version'}",$pbpkg,\%bfiles,\%pkgfiles,$supfiles);
954                    $build{$v} = "yes";
955                } 
956                if (-d "$ENV{'PBROOTDIR'}/$pbpkg/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}") {
957                    pb_list_bfiles("$ENV{'PBROOTDIR'}/$pbpkg/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}",$pbpkg,\%bfiles,\%pkgfiles,$supfiles);
958                    $build{$v} = "yes";
959                }
960                pb_log(2,"DEBUG($v) bfiles: ".Dumper(\%bfiles)."\n");
961   
962                if ($build{$v} ne "no") {
963                    # Apply now all the filters on all the files concerned
964                    # destination dir depends on the type of file
965                    # For patch support
966                    # TODO: Make it CMS aware
967                    $pb->{'patches'} = pb_list_sfiles("$ENV{'PBROOTDIR'}/$pbpkg/pbpatch", $pb->{'patches'}, $pbos, "$ENV{'PBROOTDIR'}/$pbpkg/pbextpatch");
968                    pb_log(2,"DEBUG($v) patches: ".Dumper($pb->{'patches'})."\n");
969                    # TODO: Make it CMS aware
970                    $pb->{'sources'} = pb_list_sfiles("$ENV{'PBROOTDIR'}/$pbpkg/pbsrc", $pb->{'sources'}, $pbos, "$ENV{'PBROOTDIR'}/$pbpkg/pbextsrc");
971                    pb_log(2,"DEBUG($v) sources: ".Dumper($pb->{'sources'})."\n");
972   
973                    if (defined $pb->{'patches'}->{$v}) {
974                        # Filter potential patches (local + remote)
975                        pb_mkdir_p("$dest/pbconf/$v/pbpatch");
976                        # If Debian based distribution, then prepare what will be done at build time
977                        my ($patchcmd,$patchopt);
978                        if ($pbos->{'type'} eq "deb") {
979                            ($patchcmd,$patchopt) = pb_distro_get_param($pbos,pb_conf_get_if("ospatchcmd","ospatchopt"));
980                            open(SCRIPT,"> $dest/pbconf/$v/pbpatch/pbapplypatch") || die "Unable to create $dest/pbconf/$v/pbpatch/pbapplypatch";
981                            print SCRIPT "#!/bin/bash\n";
982                            print SCRIPT "set -x\n" if ($pbdebug gt 1);
983                        }
984                        foreach my $pf (split(/,/,$pb->{'patches'}->{$v})) {
985                            my $pp = basename($pf);
986                            pb_cms_export($pf,undef,"$dest/pbconf/$v/pbpatch");
987                            pb_filter_file_inplace($ptr,"$dest/pbconf/$v/pbpatch/$pp",$pb);
988                            pb_system("gzip -9f $dest/pbconf/$v/pbpatch/$pp","","quiet");
989                            if ($pbos->{'type'} eq "deb") {
990                                # If Debian based distribution, then prepare what will be done at build time
991                                # by applying the patches that will be available under the debian/patches dir
992                                print SCRIPT "$patchcmd $patchopt \< debian/patches/$pp\n";
993                            }
994                        }
995                        if ($pbos->{'type'} eq "deb") {
996                            close(SCRIPT);
997                            chmod 0755,"$dest/pbconf/$v/pbpatch/pbapplypatch";
998                        }
999                        #pb_system("cat $dest/pbconf/$v/pbpatch/pbapplypatch","APPLY","verbose");
1000                    }
1001                    if (defined $pb->{'sources'}->{$v}) {
1002                        pb_mkdir_p("$dest/pbconf/$v/pbsrc");
1003                        foreach my $pf (split(/,/,$pb->{'sources'}->{$v})) {
1004                            my $pp = basename($pf);
1005                            pb_cms_export($pf,undef,"$dest/pbconf/$v/pbsrc");
1006                            pb_filter_file_inplace($ptr,"$dest/pbconf/$v/pbsrc/$pp",$pb);
1007                        }
1008                    }
1009                    # Filter build files at the end, as they depend on patches and sources
1010                    foreach my $f (keys %bfiles) {
1011                        pb_filter_file("$ENV{'PBROOTDIR'}/$bfiles{$f}",$ptr,"$dest/pbconf/$v/$f",$pb);
1012                    }
1013                    foreach my $f (keys %pkgfiles) {
1014                        pb_filter_file("$ENV{'PBROOTDIR'}/$pkgfiles{$f}",$ptr,"$dest/pbconf/$v/$f",$pb);
1015                    }
1016                }
1017
1018                if (defined $pbparallel) {
1019                    # Communicate results back to parent
1020                    my $str = "";
1021                    $str .= "build $v = $build{$v}\n" if (defined $build{$v});
1022                    $str .= "patches $v = $pb->{'patches'}->{$v}\n" if (defined $pb->{'patches'}->{$v});
1023                    $str .= "sources $v = $pb->{'sources'}->{$v}\n" if (defined $pb->{'sources'}->{$v});
1024                    pb_set_content("$tmpd/$$","$str");
1025                    $pm->finish;
1026                }
1027            }
1028            # In the parent, we need to get the result from the children
1029            $pm->wait_all_children if (defined $pbparallel);
1030            my $made = "";
1031            my %h = ();
1032            my %tmp;
1033            my %tmp2;
1034            my $pt;
1035            my $k;
1036
1037            foreach $k (<$tmpd/*>) {
1038                $made .= pb_get_content($k);
1039            }
1040            pb_rm_rf($tmpd);
1041            pb_log(3,"MADE:\n$made");
1042
1043            # Rebuild local hashes
1044            foreach $k (split(/\n/,$made)) {
1045                if ($k =~ /^\s*([A-z0-9-_]+)\s+([[A-z0-9-_.]+)\s*=\s*(.+)$/) {
1046                    $h{$1}->{$2}=$3;
1047                }
1048            }
1049            pb_log(2,"HASH: ".Dumper(%h));
1050
1051            # Patches
1052            pb_log(0,"Delivered and compressed patches ");
1053            $pt = $h{'patches'};
1054            foreach $k (keys %$pt) {
1055                foreach my $v1 (split(/,/,$pt->{$k})) {
1056                    $tmp{$v1} = "";
1057                }
1058            }
1059            if (keys %tmp) {
1060                foreach $k (keys %tmp) {
1061                    pb_log(0,"$k ");
1062                }
1063            } else {
1064                pb_log(0,"N/A");
1065            }
1066            pb_log(0,"\n");
1067
1068            # Sources
1069            pb_log(0,"Delivered additional sources ");
1070            $pt = $h{'sources'};
1071            foreach $k (keys %$pt) {
1072                foreach my $v1 (split(/,/,$pt->{$k})) {
1073                    $tmp2{$v1} = "";
1074                }
1075            }
1076            if (keys %tmp2) {
1077                foreach $k (keys %tmp2) {
1078                    pb_log(0,"$k ");
1079                }
1080            } else {
1081                pb_log(0,"N/A");
1082            }
1083            pb_log(0,"\n");
1084
1085            # Build files
1086            my @found;
1087            my @notfound;
1088            $pt = $h{'build'};
1089            foreach my $b (keys %$pt) {
1090                push @found,$b if ($pt->{$b} =~ /yes/);
1091                push @notfound,$b if ($pt->{$b} =~ /no/);
1092            }
1093            pb_log(0,"Build files have been generated for ... ".join(',',sort(@found))."\n") if (@found);
1094            pb_log(0,"No Build files found for ".join(',',sort(@notfound))."\n") if (@notfound);
1095
1096        } else {
1097            # Instead call News generation
1098            pb_web_news2html($dest);
1099            # And create an empty pbconf
1100            pb_mkdir_p("$dest/pbconf");
1101            # And prepare the pbscript to execute remotely
1102            open(SCRIPT,"> $ENV{'PBTMP'}/pbscript") || die "Unable to create $ENV{'PBTMP'}/pbscript";
1103            print SCRIPT "#!/bin/bash\n";
1104            print SCRIPT "#set -x\n";
1105            print SCRIPT "echo ... Extracting Website content\n";
1106            print SCRIPT "find . -type f | grep -Ev '^./$pbpkg-$pbver.tar.gz|^./pbscript' | xargs rm -f non-existent\n";
1107            print SCRIPT "find * -type d -depth | xargs rmdir 2> /dev/null \n";
1108            print SCRIPT "tar xfz $pbpkg-$pbver.tar.gz\n";
1109            print SCRIPT "mv $pbpkg-$pbver/* .\n";
1110            print SCRIPT "rm -f $pbpkg-$pbver.tar.gz\n";
1111            print SCRIPT "rmdir $pbpkg-$pbver\n";
1112            close(SCRIPT);
1113            chmod 0755,"$ENV{'PBTMP'}/pbscript";
1114        }
1115
1116        # Apply filters to the non-build files
1117        my $liste ="";
1118        if (defined $filteredfiles->{$pbpkg}) {
1119            foreach my $f (split(/,/,$filteredfiles->{$pbpkg})) {
1120                pb_filter_file_inplace($ptr,"$dest/$f",$pb);
1121                $liste = "$f $liste";
1122            }
1123        }
1124        pb_log(2,"Files ".$liste."have been filtered\n");
1125
1126        # TODO: Make it CMS aware
1127        # Execute the pbinit script if any
1128        if (-x "$ENV{'PBROOTDIR'}/$pbpkg/pbinit") {
1129            pb_filter_file("$ENV{'PBROOTDIR'}/$pbpkg/pbinit",$ptr,"$ENV{'PBTMP'}/pbinit",$pb);
1130            chmod 0755,"$ENV{'PBTMP'}/pbinit";
1131            pb_system("cd $dest ; $ENV{'PBTMP'}/pbinit","Executing init script from $ENV{'PBROOTDIR'}/$pbpkg/pbinit under $dest","verbose");
1132        }
1133
1134        # Do we have additional script to run to prepare the environement for the project ?
1135        # Then include it in the pbconf delivery
1136        foreach my $pbvf (<$ENV{'PBROOTDIR'}/pbv*.pre>,<$ENV{'PBROOTDIR'}/pbv*.post>, <$ENV{'PBROOTDIR'}/pbtest*>) {
1137            if (-x "$pbvf") {
1138                my $target = "$ENV{'PBDESTDIR'}/".basename($pbvf);
1139                pb_filter_file("$pbvf",$ptr,$target,$pb);
1140                chmod 0755,"$target";
1141            }
1142        }
1143
1144        # Prepare the dest directory for archive
1145        chdir "$ENV{'PBDESTDIR'}" || die "Unable to change dir to $ENV{'PBDESTDIR'}";
1146        if (defined $preserve) {
1147            # In that case we want to preserve the original tar file for checksum purposes
1148            # The one created is btw equivalent in that case to this one
1149            # Maybe check basename of both to be sure they are the same ?
1150            pb_log(0,"Preserving original tar file ");
1151            move("$preserve","$pbpkg-$pbver.tar.gz");
1152        } else {
1153            # Possibility to look at PBSRC to guess more the filename
1154            pb_system("tar cfz $pbpkg-$pbver.tar.gz --exclude=$pbpkg-$pbver/pbconf $pbpkg-$pbver","Creating $pbpkg tar files compressed");
1155        }
1156        pb_log(0,"Under $ENV{'PBDESTDIR'}/$pbpkg-$pbver.tar.gz\n");
1157        pb_system("tar cfz $pbpkg-$pbver.pbconf.tar.gz $pbpkg-$pbver/pbconf","Creating pbconf tar files compressed");
1158        pb_log(0,"Under $ENV{'PBDESTDIR'}/$pbpkg-$pbver.pbconf.tar.gz\n");
1159
1160        # Keep track of version-tag per pkg
1161        $pkgs{$pbpkg} = "$pbver-$pbtag";
1162
1163        # Final cleanup
1164        pb_rm_rf($dest) if (-d $dest);
1165    }
1166
1167    # Keep track of per package version
1168    pb_log(2,"DEBUG pkgs: ".Dumper(%pkgs)."\n");
1169    open(PKG,"> $ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.pb") || die "Unable to create $ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.pb";
1170    foreach my $pbpkg (keys %pkgs) {
1171        print PKG "pbpkg $pbpkg = $pkgs{$pbpkg}\n";
1172    }
1173    close(PKG);
1174
1175    # Keep track of what is generated by default
1176    # We need to store the dir and info on version-tag
1177    # Base our content on the existing .pb file
1178    copy("$ENV{'PBROOTDIR'}/$ENV{'PBPROJ'}.pb","$ENV{'PBDESTDIR'}/pbrc");
1179    open(LAST,">> $ENV{'PBDESTDIR'}/pbrc") || die "Unable to create $ENV{'PBDESTDIR'}/pbrc";
1180    print LAST "pbroot $ENV{'PBPROJ'} = $ENV{'PBROOTDIR'}\n";
1181    print LAST "projver $ENV{'PBPROJ'} = $ENV{'PBPROJVER'}\n";
1182    print LAST "projtag $ENV{'PBPROJ'} = $ENV{'PBPROJTAG'}\n";
1183    print LAST "pbpackager $ENV{'PBPROJ'} = $ENV{'PBPACKAGER'}\n";
1184    close(LAST);
1185}
1186
1187sub pb_test2pkg {
1188    # Get the running distro to test on
1189    my $pbos = pb_distro_get_context();
1190
1191    # Get list of packages to test
1192    # Get content saved in cms2build
1193    my $ptr = pb_get_pkg();
1194    @pkgs = @$ptr;
1195
1196    # Additional potential repo
1197    pb_distro_setuprepo($pbos);
1198    foreach my $pbpkg (@pkgs) {
1199        # We need to install the package to test, and deps brought with it
1200        pb_distro_installdeps(undef,$pbos,$pbpkg);
1201        pb_system("$ENV{'PBDESTDIR'}/pbtest","Launching test for $pbpkg","verbose");
1202    }
1203}
1204
1205sub pb_build2pkg {
1206
1207    # Get the running distro to build on
1208    my $pbos = pb_distro_get_context();
1209
1210    # If needed we may add repository to the build env
1211    pb_distro_setuprepo($pbos);
1212
1213    # Get list of packages to build
1214    my $ptr = pb_get_pkg();
1215    @pkgs = @$ptr;
1216
1217    # Get content saved in cms2build
1218    my ($pkg) = pb_conf_read("$ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.pb","pbpkg");
1219    $pkg = { } if (not defined $pkg);
1220
1221    pb_mkdir_p("$ENV{'PBBUILDDIR'}") if (! -d "$ENV{'PBBUILDDIR'}");
1222    chdir "$ENV{'PBBUILDDIR'}" || die "Unable to chdir to $ENV{'PBBUILDDIR'}";
1223    my $made = ""; # pkgs made during build
1224    my $pm;
1225    $pm = new Parallel::ForkManager($pbparallel) if (defined $pbparallel);
1226
1227    # We need to communicate info back from the children if parallel so prepare a dir for that
1228    my $tmpd = "$ENV{'PBTMP'}/build.$$";
1229    pb_mkdir_p($tmpd) if (defined $pbparallel);
1230
1231    foreach my $pbpkg (@pkgs) {
1232        $pm->start and next if (defined $pbparallel);
1233
1234        my $vertag = $pkg->{$pbpkg};
1235        # get the version of the current package - maybe different
1236        ($pbver,$pbtag) = split(/-/,$vertag);
1237
1238        my $src="$ENV{'PBDESTDIR'}/$pbpkg-$pbver.tar.gz";
1239        my $src2="$ENV{'PBDESTDIR'}/$pbpkg-$pbver.pbconf.tar.gz";
1240        pb_log(2,"Source file: $src\n");
1241        pb_log(2,"Pbconf file: $src2\n");
1242
1243        pb_log(2,"Working directory: $ENV{'PBBUILDDIR'}\n");
1244        if ($pbos->{'type'} eq "rpm") {
1245            foreach my $d ('RPMS','SRPMS','SPECS','SOURCES','BUILD') {
1246                if (! -d "$ENV{'PBBUILDDIR'}/$d") {
1247                    pb_mkdir_p("$ENV{'PBBUILDDIR'}/$d");
1248                }
1249            }
1250
1251            # Remove in case a previous link/file was there
1252            unlink "$ENV{'PBBUILDDIR'}/SOURCES/".basename($src);
1253            symlink "$src","$ENV{'PBBUILDDIR'}/SOURCES/".basename($src) || die "Unable to symlink $src in $ENV{'PBBUILDDIR'}/SOURCES";
1254            # We need to first extract the spec file
1255            my @specfile = pb_extract_build_files($src2,"$pbpkg-$pbver/pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/","$ENV{'PBBUILDDIR'}/SPECS","spec");
1256
1257            # We need to handle potential patches to upstream sources
1258            pb_extract_build_files($src2,"$pbpkg-$pbver/pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/pbpatch/","$ENV{'PBBUILDDIR'}/SOURCES","patch");
1259
1260            # We need to handle potential additional sources to upstream sources
1261            pb_extract_build_files($src2,"$pbpkg-$pbver/pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/pbsrc/","$ENV{'PBBUILDDIR'}/SOURCES","src");
1262
1263            pb_log(2,"specfile: ".Dumper(\@specfile)."\n");
1264            # set LANGUAGE to check for correct log messages
1265            $ENV{'LANGUAGE'}="C";
1266            # Older Redhat use _target_platform in %configure incorrectly
1267            my $specialdef = "";
1268            if (($pbos->{'name'} eq "redhat") || (($pbos->{'name'} eq "rhel") && ($pbos->{'version'} eq "2.1"))) {
1269                $specialdef = "--define \'_target_platform \"\"\'";
1270            }
1271
1272            foreach my $f (@specfile) {
1273                if ($f =~ /\.spec$/) {
1274                    # This could cause an issue in // mode
1275                    pb_distro_installdeps($f,$pbos);
1276                    pb_system("rpmbuild $specialdef --define \"packager $ENV{'PBPACKAGER'}\" --define \"_topdir $ENV{'PBBUILDDIR'}\" -ba $f","Building package with $f under $ENV{'PBBUILDDIR'}","verbose");
1277                    last;
1278                }
1279            }
1280            # Get the name of the generated packages
1281            open(LOG,"$ENV{'PBTMP'}/system.$$.log") || die "Unable to open $ENV{'PBTMP'}/system.$$.log";
1282            while (<LOG>) {
1283                chomp($_);
1284                next if ($_ !~ /^Wrote:/);
1285                s|.*/([S]*RPMS.*)|$1|;
1286                $made .=" $_";
1287            }
1288            close(LOG);
1289
1290        } elsif ($pbos->{'type'} eq "deb") {
1291            pb_system("tar xfz $src","Extracting sources");
1292            pb_system("tar xfz $src2","Extracting pbconf");
1293
1294            chdir "$pbpkg-$pbver" || die "Unable to chdir to $pbpkg-$pbver";
1295            pb_rm_rf("debian");
1296            symlink "pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}","debian" || die "Unable to symlink to pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}";
1297            chmod 0755,"debian/rules";
1298
1299            # We need to handle potential patches to upstream sources
1300            pb_mkdir_p("debian/patches");
1301            my @f = pb_extract_build_files($src2,"$pbpkg-$pbver/pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/pbpatch/","debian/patches","patch");
1302
1303            # By default we use format 1.0 - Cf man dpkg-source
1304            my $debsrcfmt = "1.0";
1305            my $debsrcfile = "debian/source/format";
1306            if (-f $debsrcfile) {
1307                $debsrcfmt = pb_get_content($debsrcfile);
1308            }
1309               
1310            if ($debsrcfmt =~ /^3.*quilt/) {
1311                # If we use quilt to manage patches, we then setup the env correctly
1312                # as per http://pkg-perl.alioth.debian.org/howto/quilt.html
1313                # Generate Debian patch series for quilt
1314                open(SERIE,"> debian/patches/series") || die "Unable to write in debian/patches/series";
1315                $ENV{'QUILT_PATCHES'}="debian/patches";
1316            } else {
1317                # If we use dpatch to manage patches, we then setup the 00list file as well
1318                open(SERIE,"> debian/patches/00list") || die "Unable to write in debian/patches/00list";
1319            }
1320            foreach my $f (sort @f) {
1321                # Skip the script made to apply the patches to the Debian tree
1322                next if ($f =~ /pbapplypatch/);
1323                # We also need to uncompress them
1324                pb_system("gzip -d $f","","quiet");
1325                $f =~ s/\.gz$//;
1326                print SERIE "$f\n";
1327            }
1328            close(SERIE);
1329            if ($debsrcfmt =~ /^1.*/) {
1330                # In that case we need to apply the patches ourselves locally
1331                pb_system("cat debian/patches/pbapplypatch","APPLY","verbose");
1332                pb_system("debian/patches/pbapplypatch","Applying patches to $pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'} tree");
1333            }
1334            if (@f) {
1335                # We have patches, so modify the name of files to be Debian compliant
1336                move("../$src","../$pbpkg-$pbver.orig.tar.gz");
1337            }
1338
1339            # We need to handle potential additional sources to upstream sources
1340            #pb_extract_build_files($src2,"$pbpkg-$pbver/pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/pbsrc/","$ENV{'PBBUILDDIR'}/debian","src");
1341
1342            pb_distro_installdeps("debian/control",$pbos);
1343            pb_system("dpkg-buildpackage -us -uc -rfakeroot","Building package","verbose");
1344            # Get the name of the generated packages
1345            open(LOG,"$ENV{'PBTMP'}/system.$$.log") || die "Unable to open $ENV{'PBTMP'}/system.$$.log";
1346            while (<LOG>) {
1347                chomp();
1348                my $tmp = $_;
1349                next if ($tmp !~ /^dpkg-deb.*:/);
1350                $tmp =~ s|.*\.\./(.*)_(.*).deb.*|$1|;
1351                $made="$made $tmp.dsc $tmp.tar.gz $tmp"."_*.deb $tmp"."_*.changes";
1352            }
1353            close(LOG);
1354            chdir ".." || die "Unable to chdir to parent dir";
1355            pb_system("rm -rf $pbpkg-$pbver", "Cleanup");
1356        } elsif ($pbos->{'type'} eq "ebuild") {
1357            my @ebuildfile;
1358            # For gentoo we need to take pb as subsystem name
1359            # We put every apps here under sys-apps. hope it's correct
1360            # We use pb's home dir in order to have a single OVERLAY line
1361            my $tmpe = "$ENV{'HOME'}/portage/pb/sys-apps/$pbpkg";
1362            pb_mkdir_p($tmpe) if (! -d "$tmpe");
1363            pb_mkdir_p("$ENV{'HOME'}/portage/distfiles") if (! -d "$ENV{'HOME'}/portage/distfiles");
1364
1365            # We need to first extract the ebuild file
1366            @ebuildfile = pb_extract_build_files($src2,"$pbpkg-$pbver/pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/","$tmpe","ebuild");
1367
1368            # Prepare the build env for gentoo
1369            my $found = 0;
1370            my $pbbd = $ENV{'HOME'};
1371            $pbbd =~ s|/|\\/|g;
1372            if (-r "/etc/make.conf") {
1373                open(MAKE,"/etc/make.conf");
1374                while (<MAKE>) {
1375                    $found = 1 if (/$pbbd\/portage/);
1376                }
1377                close(MAKE);
1378            }
1379            if ($found == 0) {
1380                pb_system("sudo sh -c 'echo PORTDIR_OVERLAY=\"$ENV{'HOME'}/portage\" >> /etc/make.conf'");
1381            }
1382            #$found = 0;
1383            #if (-r "/etc/portage/package.keywords") {
1384            #open(KEYW,"/etc/portage/package.keywords");
1385            #while (<KEYW>) {
1386            #$found = 1 if (/portage\/pb/);
1387            #}
1388            #close(KEYW);
1389            #}
1390            #if ($found == 0) {
1391            #pb_system("sudo sh -c \"echo portage/pb >> /etc/portage/package.keywords\"");
1392            #}
1393
1394            # Build
1395            foreach my $f (@ebuildfile) {
1396                if ($f =~ /\.ebuild$/) {
1397                    pb_distro_installdeps($f,$pbos);
1398                    move($f,"$tmpe/$pbpkg-$pbver.ebuild");
1399                    pb_system("cd $tmpe ; ebuild $pbpkg-$pbver.ebuild clean ; ebuild $pbpkg-$pbver.ebuild digest ; ebuild $pbpkg-$pbver.ebuild package","verbose");
1400                    # Now move it where pb expects it
1401                    pb_mkdir_p("$ENV{'PBBUILDDIR'}/portage/pb/sys-apps/$pbpkg");
1402                    if ($pbtag =~ /^0\./) {
1403                        # This is a test version
1404                        my $ntag = $pbtag;
1405                        $ntag =~ s/^0\.//;
1406                        move("$tmpe/$pbpkg-$pbver.ebuild","$ENV{'PBBUILDDIR'}/portage/pb/sys-apps/$pbpkg/$pbpkg-$pbver"."_p$ntag.ebuild");
1407                        $made="$made portage/pb/sys-apps/$pbpkg/$pbpkg-$pbver"."_p$ntag.ebuild";
1408                    } else {
1409                        move("$tmpe/$pbpkg-$pbver.ebuild","$ENV{'PBBUILDDIR'}/portage/pb/sys-apps/$pbpkg/$pbpkg-$pbver-r$pbtag.ebuild");
1410                        $made="$made portage/pb/sys-apps/$pbpkg/$pbpkg-$pbver-r$pbtag.ebuild";
1411                    }
1412                }
1413            }
1414
1415        } elsif ($pbos->{'type'} eq "tgz") {
1416            # Slackware family
1417            $made="$made $pbpkg/$pbpkg-$pbver-*-$pbtag.tgz";
1418
1419            pb_system("tar xfz $src","Extracting sources");
1420            pb_system("tar xfz $src2","Extracting pbconf");
1421            chdir "$pbpkg-$pbver" || die "Unable to chdir to $pbpkg-$pbver";
1422            symlink "pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}","install" || die "Unable to symlink to pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}";
1423            if (-x "install/pbslack") {
1424                pb_distro_installdeps("./install/pbslack",$pbos);
1425                pb_system("./install/pbslack","Building software");
1426                pb_system("sudo /sbin/makepkg -p -l y -c y $pbpkg","Packaging $pbpkg","verbose");
1427            }
1428            chdir ".." || die "Unable to chdir to parent dir";
1429            pb_system("rm -rf $pbpkg-$pbver", "Cleanup");
1430        } elsif ($pbos->{'type'} eq "pkg") {
1431            # Solaris
1432            $made="$made $pbpkg-$pbver-$pbtag.pkg.gz";
1433            my $pkgdestdir="$ENV{'PBBUILDDIR'}/install";
1434
1435            # Will host resulting packages
1436            pb_mkdir_p("$pbos->{'type'}");
1437            pb_mkdir_p("$pkgdestdir/delivery");
1438            pb_system("tar xfz $src","Extracting sources under $ENV{'PBBUILDDIR'}");
1439            pb_system("tar xfz $src2","Extracting pbconf under $ENV{'PBBUILDDIR'}");
1440            # We need to handle potential patches to upstream sources
1441            pb_extract_build_files($src2,"$pbpkg-$pbver/pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/pbpatch/","$ENV{'PBBUILDDIR'}","patch");
1442
1443            # We need to handle potential additional sources to upstream sources
1444            pb_extract_build_files($src2,"$pbpkg-$pbver/pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/pbsrc/","$ENV{'PBBUILDDIR'}","src");
1445
1446            chdir "$pbpkg-$pbver" || die "Unable to chdir to $pbpkg-$pbver";
1447            if (-f "pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/pbbuild") {
1448                chmod 0755,"pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/pbbuild";
1449                # pkginfo file is mandatory
1450                die "Unable to find pkginfo file in pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}" if (! -f "pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/pkginfo");
1451                # Build
1452                pb_system("pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/pbbuild $pkgdestdir/delivery","Building software and installing under $pkgdestdir/delivery");
1453                # Copy complementary files
1454                if (-f "pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/prototype") {
1455                    copy("pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/prototype", $pkgdestdir) 
1456                } else {
1457                    # No prototype provided, calculating it
1458                    open(PROTO,"> $pkgdestdir/prototype") || die "Unable to create prototype file";
1459                    print PROTO "i pkginfo\n";
1460                    print PROTO "i depend\n" if (-f "pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/depend");
1461                    $ENV{'PBSOLDESTDIR'} = "$pkgdestdir/delivery";
1462                    find(\&create_solaris_prototype, "$pkgdestdir/delivery");
1463                }
1464                copy("pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/depend", $pkgdestdir) if (-f "pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/depend");
1465                copy("pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/pkginfo", $pkgdestdir);
1466                pb_system("cd $pkgdestdir/delivery ; pkgmk -o -f ../prototype -r $pkgdestdir/delivery -d $ENV{'PBBUILDDIR'}/$pbos->{'type'}","Packaging $pbpkg","verbose");
1467                pb_system("cd $ENV{'PBBUILDDIR'}/$pbos->{'type'} ;  echo \"\" | pkgtrans -o -n -s $ENV{'PBBUILDDIR'}/$pbos->{'type'} $ENV{'PBBUILDDIR'}/$pbpkg-$pbver-$pbtag.pkg all","Transforming $pbpkg","verbose");
1468                pb_system("cd $ENV{'PBBUILDDIR'} ;  gzip -9f $pbpkg-$pbver-$pbtag.pkg","Compressing $pbpkg-$pbver-$pbtag.pkg","verbose");
1469            } else {
1470                pb_log(0,"No pbconf/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}/pbbuild file found for $pbpkg-$pbver in \n");
1471            }
1472            chdir ".." || die "Unable to chdir to parent dir";
1473            pb_system("rm -rf $pbpkg-$pbver $ENV{'PBBUILDDIR'}/$pbos->{'type'} $pkgdestdir", "Cleanup");
1474        } elsif ($pbos->{'type'} eq "hpux") {
1475            # HP-UX
1476            pb_system("tar xfz $src","Extracting sources");
1477            pb_system("tar xfz $src2","Extracting pbconf");
1478
1479            chdir "$pbpkg-$pbver" || die "Unable to chdir to $pbpkg-$pbver";
1480            pb_system("buildpackage ","Building package","verbose");
1481            # Get the name of the generated packages
1482            open(LOG,"$ENV{'PBTMP'}/system.$$.log") || die "Unable to open $ENV{'PBTMP'}/system.$$.log";
1483            while (<LOG>) {
1484                chomp();
1485                my $tmp = $_;
1486                next if ($tmp !~ /^SD BUILD.*:/);
1487                $tmp =~ s|.*../(.*)_(.*).sd.*|$1|;
1488                $made = "$made $tmp"."_*.sd";
1489            }
1490            close(LOG);
1491            $made="$made $pbpkg-$pbver-$pbtag.sd";
1492
1493            chdir ".." || die "Unable to chdir to parent dir";
1494            pb_system("rm -rf $pbpkg-$pbver", "Cleanup");
1495        } else {
1496            die "Unknown OS type format $pbos->{'type'}";
1497        }
1498        if (defined $pbparallel) {
1499            # Communicate results back to parent
1500            pb_set_content("$tmpd/$$",$made);
1501            $pm->finish;
1502        }
1503    }
1504    if (defined $pbparallel) {
1505        # In the parent, we need to get the result from the children
1506        $pm->wait_all_children;
1507        foreach my $f (<$tmpd/*>) {
1508            $made .= " ".pb_get_content($f);
1509        }
1510        pb_rm_rf($tmpd);
1511    }
1512
1513    # Sign packages
1514    pb_sign_pkgs($pbos,$made);
1515
1516    # Find the appropriate check cmd/opts
1517    my ($chkcmd,$chkopt) = pb_distro_get_param($pbos,pb_conf_get_if("oschkcmd","oschkopt"));
1518
1519    # Packages check if needed
1520    if ($pbos->{'type'} eq "rpm") {
1521        if ((defined  $chkcmd) && (-x $chkcmd)) {
1522            my $cmd = "$chkcmd";
1523            $cmd .= " $chkopt" if (defined $chkopt);
1524            $cmd .= " $made";
1525            pb_system("$cmd","Checking validity of rpms with $chkcmd","verbose");
1526        }
1527        my $rpms ="";
1528        my $srpms ="";
1529        foreach my $f (split(/ /,$made)) {
1530            $rpms .= "$ENV{'PBBUILDDIR'}/$f " if ($f =~ /^RPMS\//);
1531            $srpms .= "$ENV{'PBBUILDDIR'}/$f " if ($f =~ /^SRPMS\//);
1532        }
1533        pb_log(0,"SRPM packages generated: $srpms\n");
1534        pb_log(0,"RPM packages generated: $rpms\n");
1535    } elsif ($pbos->{'type'} eq "deb") {
1536        my $made2 = "";
1537        foreach my $f (split(/ /,$made)) {
1538            $made2 .= "$f " if ($f =~ /\.deb$/);
1539        }
1540        if (-x $chkcmd) {
1541            pb_system("$chkcmd $chkopt $made2","Checking validity of debs with $chkcmd","verbose");
1542        }
1543        pb_log(0,"deb packages generated: $made2\n");
1544    } else {
1545        pb_log(0,"No check done for $pbos->{'type'} yet\n");
1546        pb_log(0,"Packages generated: $made\n");
1547    }
1548
1549    # Keep track of what is generated so that we can get them back from VMs/RMs
1550    open(KEEP,"> $ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}-$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}") || die "Unable to create $ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}-$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}";
1551    print KEEP "$made\n";
1552    close(KEEP);
1553}
1554
1555sub create_solaris_prototype {
1556
1557    my $uidgid = "bin bin";
1558    my $pkgdestdir = $ENV{'PBSOLDESTDIR'};
1559
1560    return if ($_ =~ /^$pkgdestdir$/);
1561    if (-d $_) {
1562        my $n = $File::Find::name;
1563        $n =~ s~$pkgdestdir/~~;
1564        print PROTO "d none $n 0755 $uidgid\n";
1565    } elsif (-x $_) {
1566        my $n = $File::Find::name;
1567        $n =~ s~$pkgdestdir/~~;
1568        print PROTO "f none $n 0755 $uidgid\n";
1569    } elsif (-f $_) {
1570        my $n = $File::Find::name;
1571        $n =~ s~$pkgdestdir/~~;
1572        print PROTO "f none $n 0644 $uidgid\n";
1573    }
1574}
1575
1576sub pb_build2ssh {
1577    pb_send2target("Sources");
1578    pb_send2target("CPAN");
1579}
1580
1581sub pb_pkg2ssh {
1582    pb_send2target("Packages");
1583}
1584
1585# By default deliver to the the public site hosting the
1586# ftp structure (or whatever) or a VM/VE/RM
1587sub pb_send2target {
1588
1589    my $cmt = shift;
1590    my $v = shift || undef;
1591    my $vmexist = shift || 0;           # 0 is FALSE
1592    my $vmpid = shift || 0;             # 0 is FALSE
1593    my $snapme = shift || 0;            # 0 is FALSE
1594
1595    pb_log(2,"DEBUG: pb_send2target($cmt,".Dumper($v).",$vmexist,$vmpid)\n");
1596    my $host = "sshhost";
1597    my $login = "sshlogin";
1598    my $dir = "sshdir";
1599    my $port = "sshport";
1600    my $conf = "sshconf";
1601    my $tmout = undef;
1602    my $path = undef;
1603    if ($cmt =~ /^VM/) {
1604        $login = "vmlogin";
1605        $dir = "pbdefdir";
1606        # Specific VM
1607        $tmout = "vmtmout";
1608        $path = "vmpath";
1609        $host = "vmhost";
1610        $port = "vmport";
1611    } elsif ($cmt =~ /^RM/) {
1612        $login = "rmlogin";
1613        $dir = "pbdefdir";
1614        # Specific RM
1615        $tmout = "rmtmout";
1616        $path = "rmpath";
1617        $host = "rmhost";
1618        $port = "rmport";
1619    } elsif ($cmt =~ /^VE/) {
1620        $login = "velogin";
1621        $dir = "pbdefdir";
1622        # Specific VE
1623        $path = "vepath";
1624        $conf = "rbsconf";
1625    } elsif ($cmt eq "Web") {
1626        $host = "websshhost";
1627        $login = "websshlogin";
1628        $dir = "websshdir";
1629        $port = "websshport";
1630    } elsif ($cmt eq "CPAN") {
1631        $host = "cpanpause";
1632        $login = "";
1633        $dir = "cpandir";
1634        $port = "";
1635    }
1636    my $cmd = "";
1637    my $src = "";
1638    my $cpanpkg = 0;
1639    my $pbos;
1640
1641    if ($cmt ne "Announce") {
1642        # Get list of packages to build
1643        my $ptr = pb_get_pkg();
1644        @pkgs = @$ptr;
1645
1646        # Get the running distro to consider
1647        $pbos = pb_distro_get_context($v);
1648
1649        # Get content saved in cms2build
1650        my ($pkg) = pb_conf_read("$ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.pb","pbpkg");
1651        $pkg = { } if (not defined $pkg);
1652
1653        pb_mkdir_p("$ENV{'PBBUILDDIR'}") if (! -d "$ENV{'PBBUILDDIR'}");
1654        chdir "$ENV{'PBBUILDDIR'}" || die "Unable to chdir to $ENV{'PBBUILDDIR'}";
1655        foreach my $pbpkg (@pkgs) {
1656            my $vertag = $pkg->{$pbpkg};
1657            # get the version of the current package - maybe different
1658            ($pbver,$pbtag) = split(/-/,$vertag);
1659
1660            if (($cmt eq "Sources") || ($cmt =~ /(V[EM]|RM)build/)) {
1661                $src = "$src $ENV{'PBDESTDIR'}/$pbpkg-$pbver.tar.gz $ENV{'PBDESTDIR'}/$pbpkg-$pbver.pbconf.tar.gz";
1662                if ($cmd eq "") {
1663                    $cmd = "ln -sf $pbpkg-$pbver.tar.gz $pbpkg-latest.tar.gz";
1664                } else {
1665                    $cmd = "$cmd ; ln -sf $pbpkg-$pbver.tar.gz $pbpkg-latest.tar.gz";
1666                }
1667            } elsif ($cmt eq "Web") {
1668                $src = "$src $ENV{'PBDESTDIR'}/$pbpkg-$pbver.tar.gz"
1669            }
1670
1671            # Do we have one perl package
1672            my @nametype = pb_conf_get_if("namingtype");
1673            my $type = $nametype[0]->{$pbpkg};
1674            if ((defined $type) && ($type eq "perl")) {
1675                $cpanpkg = 1;
1676            }
1677        }
1678        # Adds conf file for availability of conf elements
1679        pb_conf_add("$ENV{'PBROOTDIR'}/$ENV{'PBPROJ'}.pb");
1680    }
1681    my ($rbsconf,$testver,$delivery) = pb_conf_get_if($conf,"testver","delivery");
1682    if ($cmt =~ /CPAN/) {
1683        # Do not deliver on Pause if this is a test version
1684        return if (not defined $testver);
1685        return if ($testver =~ /true/);
1686        # Do not deliver on Pause if this is not a perl package
1687        return if ($cpanpkg == 0);
1688    }
1689
1690    if ($cmt =~ /(V[EM]|RM)build/) {
1691        $src="$src $ENV{'PBROOTDIR'}/$ENV{'PBPROJ'}.pb $ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.pb $ENV{'PBETC'} $ENV{'PBDESTDIR'}/pbrc $ENV{'PBDESTDIR'}/pbscript.$$";
1692    } elsif ($cmt =~ /(V[EM]|RM)Script/) {
1693        $src="$src $ENV{'PBDESTDIR'}/pbscript.$$";
1694    } elsif ($cmt =~ /(V[EM]|RM)test/) {
1695        $src="$src $ENV{'PBROOTDIR'}/$ENV{'PBPROJ'}.pb $ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.pb $ENV{'PBETC'} $ENV{'PBDESTDIR'}/pbrc $ENV{'PBDESTDIR'}/pbscript.$$ $ENV{'PBDESTDIR'}/pbtest";
1696    } elsif (($cmt eq "Announce") || ($cmt eq "Web") || ($cmt eq "CPAN")) {
1697        $src="$src $ENV{'PBTMP'}/pbscript";
1698    } elsif ($cmt eq "Packages") {
1699        # Get package list from file made during build2pkg
1700        open(KEEP,"$ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}-$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}") || die "Unable to read $ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}-$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}";
1701        $src = <KEEP>;
1702        chomp($src);
1703        close(KEEP);
1704        $src = "$src $ENV{'PBBUILDDIR'}/pbscript.$$";
1705    }
1706    if (($cmt eq "Sources") || ($cmt eq "Packages") || ($cmt eq "CPAN")) {
1707        my ($pbpackager) = pb_conf_get("pbpackager");
1708        $ENV{'PBPACKAGER'} = $pbpackager->{$ENV{'PBPROJ'}};
1709        pb_log(0,"Exporting public key for $ENV{'PBPACKAGER'}\n");
1710        # Using pb_system is not working due to redirection below
1711        system("gpg --export -a \'$ENV{'PBPACKAGER'}\' > $ENV{'PBDESTDIR'}/$ENV{'PBPROJ'}.pubkey");
1712        chmod 0644,"$ENV{'PBDESTDIR'}/$ENV{'PBPROJ'}.pubkey";
1713        $src = "$src $ENV{'PBDESTDIR'}/$ENV{'PBPROJ'}.pubkey";
1714    }
1715    # Remove potential leading spaces (cause problem with basename)
1716    $src =~ s/^ *//;
1717    my $basesrc = "";
1718    foreach my $i (split(/ +/,$src)) {
1719        $basesrc .= " ".basename($i);
1720    }
1721
1722    pb_log(0,"Sources handled ($cmt): $src\n");
1723    pb_log(2,"values: ".Dumper(($host,$login,$dir,$port,$tmout,$path,$conf))."\n");
1724    my ($sshhost,$sshlogin,$sshdir,$sshport) = pb_conf_get($host,$login,$dir,$port);
1725    # Not mandatory...
1726    $delivery->{$ENV{'PBPROJ'}} = "" if (not defined $delivery->{$ENV{'PBPROJ'}});
1727    my ($vtmout,$vepath);
1728    # ...Except those in virtual context
1729    if ($cmt =~ /^VE/) {
1730        ($vepath) = pb_conf_get($path);
1731    }
1732    if ($cmt =~ /^(V|R)M/) {
1733        $vtmout = pb_distro_get_param($pbos,pb_conf_get_if($tmout));
1734    }
1735    my $remhost = $sshhost->{$ENV{'PBPROJ'}};
1736    my $remdir = $sshdir->{$ENV{'PBPROJ'}};
1737    if ($cmt =~ /^V[EM]|RM/) {
1738        # In that case our real host is in the xxhost with the OS as key, not project as above
1739        $remhost = pb_distro_get_param($pbos,$sshhost);
1740    }
1741    pb_log(2,"ssh: ".Dumper(($remhost,$sshlogin,$remdir,$sshport,$vepath,$rbsconf))."\n");
1742    pb_log(2,"ssh: ".Dumper($vtmout)."\n") if (defined $vtmout);
1743
1744    my $mac;
1745    if ($cmt !~ /^VE/) {
1746        $mac = "$sshlogin->{$ENV{'PBPROJ'}}\@$remhost";
1747        # Overwrite account value if passed as parameter
1748        $mac = "$pbaccount\@$remhost" if (defined $pbaccount);
1749        pb_log(2, "DEBUG: pbaccount: $pbaccount => mac: $mac\n") if (defined $pbaccount);
1750    } else {
1751        # VE
1752        # Overwrite account value if passed as parameter (typically for setup2v)
1753        $mac = $sshlogin->{$ENV{'PBPROJ'}};
1754        $mac = $pbaccount if (defined $pbaccount);
1755    }
1756
1757    my $tdir;
1758    my $bdir;
1759    if (($cmt eq "Sources") || ($cmt =~ /(V[EM]|RM)Script/)) {
1760        $tdir = "$remdir/$delivery->{$ENV{'PBPROJ'}}/src";
1761    } elsif ($cmt eq "CPAN") {
1762        $tdir = "$remdir";
1763    } elsif ($cmt =~ /(V[EM]|RM)(build|test)/) {
1764        $tdir = $remdir."/$ENV{'PBPROJ'}/delivery";
1765        $bdir = $remdir."/$ENV{'PBPROJ'}/build";
1766        # Remove a potential $ENV{'HOME'} as bdir should be relative to pb's home
1767        $bdir =~ s|\$ENV.+\}/||;
1768    } elsif ($cmt eq "Announce") {
1769        $tdir = "$remdir/$delivery->{$ENV{'PBPROJ'}}";
1770    } elsif ($cmt eq "Web") {
1771        $tdir = "$remdir/$delivery->{$ENV{'PBPROJ'}}";
1772    } elsif ($cmt eq "Packages") {
1773        if (($pbos->{'type'} eq "rpm") || ($pbos->{'type'} eq "pkg") || ($pbos->{'type'} eq "hpux") || ($pbos->{'type'} eq "tgz")) {
1774            # put packages under an arch subdir
1775            $tdir = "$remdir/$delivery->{$ENV{'PBPROJ'}}/$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}";
1776        } elsif (($pbos->{'type'} eq "deb") || ($pbos->{'type'} eq "ebuild")) {
1777            # No need for an arch subdir
1778            $tdir = "$remdir/$delivery->{$ENV{'PBPROJ'}}/$pbos->{'name'}/$pbos->{'version'}";
1779        } else {
1780            die "Please teach the dev team where to deliver ($pbos->{'type'} type of packages\n";
1781        }
1782
1783        my $repodir = $tdir;
1784        $repodir =~ s|^$remdir/||;
1785
1786        my ($pbrepo) = pb_conf_get("pbrepo");
1787
1788        # Repository management
1789        open(PBS,"> $ENV{'PBBUILDDIR'}/pbscript.$$") || die "Unable to create $ENV{'PBBUILDDIR'}/pbscript.$$";
1790        if ($pbos->{'type'} eq "rpm") {
1791            my $pbsha = pb_distro_get_param($pbos,pb_conf_get("ossha"));
1792            # Also make a pbscript to generate yum/urpmi bases
1793            print PBS << "EOF";
1794#!/bin/bash
1795# Prepare a script to ease yum setup
1796EOF
1797            print PBS "set -x\n" if ($pbdebug gt 1);
1798            print PBS << "EOF";
1799cat > $ENV{'PBPROJ'}.repo << EOT
1800[$ENV{'PBPROJ'}]
1801name=$pbos->{'name'} $pbos->{'version'} $pbos->{'arch'} - $ENV{'PBPROJ'} Vanilla Packages
1802baseurl=$pbrepo->{$ENV{'PBPROJ'}}/$repodir
1803enabled=1
1804gpgcheck=1
1805gpgkey=$pbrepo->{$ENV{'PBPROJ'}}/$repodir/$ENV{'PBPROJ'}.pubkey
1806EOT
1807chmod 644 $ENV{'PBPROJ'}.repo
1808
1809# Clean up old repo content
1810rm -rf headers/ repodata/
1811# Create yum repo
1812if [ -x /usr/bin/yum-arch ]; then
1813    yum-arch .
1814fi
1815# Create repodata
1816createrepo -s $pbsha .
1817# Link to the key
1818ln -sf $ENV{'PBPROJ'}.pubkey repodata/repomd.xml.key
1819# sign the repomd (at least useful for SLES - which requires a local key)
1820# gpg -a --detach-sign repodata/repomd.xml
1821# SLES also looks for media.1/info.txt
1822EOF
1823            if ($pbos->{'family'} eq "md") {
1824                # For Mandriva add urpmi management
1825                print PBS << "EOF";
1826# Prepare a script to ease urpmi setup
1827cat > $ENV{'PBPROJ'}.addmedia << EOT
1828urpmi.addmedia $ENV{'PBPROJ'} $pbrepo->{$ENV{'PBPROJ'}}/$repodir with media_info/hdlist.cz
1829EOT
1830chmod 755 $ENV{'PBPROJ'}.addmedia
1831
1832# Clean up old repo content
1833rm -f hdlist.cz synthesis.hdlist.cz
1834# Create urpmi repo
1835genhdlist2 --clean .
1836if [ \$\? -ne 0 ]; then
1837    genhdlist .
1838fi
1839EOF
1840            }
1841            if ($pbos->{'name'} eq "fedora") {
1842                # Extract the spec file to please Fedora maintainers :-(
1843                print PBS << "EOF";
1844for p in $basesrc; do
1845    echo \$p | grep -q 'src.rpm'
1846    if [ \$\? -eq 0 ]; then
1847        rpm2cpio \$p | cpio -ivdum --quiet '*.spec'
1848    fi
1849done
1850EOF
1851            }
1852            if ($pbos->{'family'} eq "novell") {
1853                # Add ymp scripts for one-click install on SuSE
1854                print PBS << "EOF";
1855# Prepare a script to ease SuSE one-click install
1856# Cf: http://de.opensuse.org/1-Klick-Installation/ISV
1857#
1858cat > $ENV{'PBPROJ'}.ymp << EOT
1859<?xml version="1.0" encoding="utf-8"?>
1860<!-- vim: set sw=2 ts=2 ai et: -->
1861<metapackage xmlns:os="http://opensuse.org/Standards/One_Click_Install" xmlns="http://opensuse.org/Standards/One_Click_Install">
1862    <group><!-- The group of software, typically one for project-builder.org -->
1863        <name>$ENV{'PBPROJ'} Bundle</name> <!-- Name of the software group -->
1864        <summary>Software bundle for the $ENV{'PBPROJ'} project</summary> <!--This message is shown to the user and should describe the whole bundle -->
1865        <description>This is the summary of the $ENV{'PBPROJ'} Project
1866             
1867            Details are available on a per package basis below
1868
1869        </description><!--This is also shown to the user -->
1870        <remainSubscribed>false</remainSubscribed> <!-- Don't know what it mean -->
1871        <repositories><!-- List of needed repositories -->
1872            <repository>
1873                <name>$ENV{'PBPROJ'} Repository</name> <!-- Name of the repository  -->
1874                <summary>This repository contains the $ENV{'PBPROJ'} project packages.</summary> <!-- Summary of the repository -->
1875                <description>This repository contains the $ENV{'PBPROJ'} project packages.</description><!-- This description is shown to the user -->
1876                <url>$pbrepo->{$ENV{'PBPROJ'}}/$repodir</url><!--URL of repository, which is added -->
1877            </repository>
1878        </repositories>
1879        <software><!-- A List of packages, which should be added through the one-click-installation -->
1880EOT
1881for p in $basesrc; do
1882    sum=`rpm -q --qf '%{SUMMARY}' \$p`
1883    name=`rpm -q --qf '%{NAME}' \$p`
1884    desc=`rpm -q --qf '%{description}' \$p`
1885    cat >> $ENV{'PBPROJ'}.ymp << EOT
1886            <item>
1887                <name>\$name</name><!-- Name of the package, is shown to the user and used to identify the package at the repository -->
1888                <summary>\$sum</summary> <!-- Summary of the package -->
1889                <description>\$desc</description> <!-- Description, is shown to the user -->
1890            </item>
1891EOT
1892done
1893cat >> $ENV{'PBPROJ'}.ymp << EOT
1894        </software>
1895    </group>
1896</metapackage>
1897EOT
1898chmod 644 $ENV{'PBPROJ'}.ymp
1899EOF
1900            }
1901        } elsif ($pbos->{'type'} eq "deb") {
1902            # Also make a pbscript to generate apt bases
1903            # Cf: http://www.debian.org/doc/manuals/repository-howto/repository-howto.fr.html
1904            # This dirname removes ver
1905            my $debarch = $pbos->{'arch'};
1906            $debarch = "amd64" if ($pbos->{'arch'} eq "x86_64");
1907            my $rpd = dirname("$pbrepo->{$ENV{'PBPROJ'}}/$repodir");
1908            # Remove extra . in path to fix #522
1909            $rpd =~ s|/./|/|g;
1910            print PBS << "EOF";
1911#!/bin/bash
1912# Prepare a script to ease apt setup
1913cat > $ENV{'PBPROJ'}.sources.list << EOT
1914deb $rpd $pbos->{'version'} contrib
1915deb-src $rpd $pbos->{'version'} contrib
1916EOT
1917chmod 644 $ENV{'PBPROJ'}.sources.list
1918
1919# Up two levels to deal with the dist dir cross versions
1920cd ..
1921mkdir -p dists/$pbos->{'version'}/contrib/binary-$debarch dists/$pbos->{'version'}/contrib/source
1922
1923# Prepare a script to create apt info file
1924# Reuse twice after
1925TMPD=`mktemp -d /tmp/pb.XXXXXXXXXX` || exit 1
1926mkdir -p \$TMPD
1927cat > \$TMPD/Release << EOT
1928Archive: unstable
1929Component: contrib
1930Origin: $ENV{'PBPROJ'}
1931Label: $ENV{'PBPROJ'} dev repository $pbrepo->{$ENV{'PBPROJ'}}
1932EOT
1933
1934echo "Creating Packages metadata ($pbos->{'arch'} aka $debarch)"
1935dpkg-scanpackages -a$debarch $pbos->{'version'} /dev/null | gzip -c9 > dists/$pbos->{'version'}/contrib/binary-$debarch/Packages.gz
1936dpkg-scanpackages -a$debarch $pbos->{'version'} /dev/null | bzip2 -c9 > dists/$pbos->{'version'}/contrib/binary-$debarch/Packages.bz2
1937echo "Creating Contents metadata"
1938apt-ftparchive contents $pbos->{'version'} | gzip -c9 > dists/$pbos->{'version'}/Contents.gz
1939echo "Creating Release metadata ($pbos->{'arch'} aka $debarch)"
1940cat \$TMPD/Release > dists/$pbos->{'version'}/contrib/binary-$debarch/Release
1941echo "Architecture: $debarch" >> dists/$pbos->{'version'}/contrib/binary-$debarch/Release
1942echo "Creating Source metadata"
1943dpkg-scansources $pbos->{'version'} /dev/null | gzip -c9 > dists/$pbos->{'version'}/contrib/source/Sources.gz
1944cat \$TMPD/Release > dists/$pbos->{'version'}/contrib/source/Release
1945echo "Architecture: Source" >> dists/$pbos->{'version'}/contrib/source/Release
1946echo "Creating Release metadata"
1947# Signing that file would be useful but uneasy as gpg keys are not there
1948# Cf: http://wiki.debian.org/SecureApt
1949# Same as for repomd
1950apt-ftparchive release dists/$pbos->{'version'} > dists/$pbos->{'version'}/Release
1951rm -rf \$TMPD
1952EOF
1953        } elsif ($pbos->{'type'} eq "ebuild") {
1954            # make a pbscript to generate links to latest version
1955            print PBS << "EOF";
1956#!/bin/bash
1957# Prepare a script to create correct links
1958for p in $src; do
1959    echo \$p | grep -q '.ebuild'
1960    if [ \$\? -eq 0 ]; then
1961        j=`basename \$p`
1962        pp=`echo \$j | cut -d'-' -f1`
1963        ln -sf \$j \$pp.ebuild
1964    fi
1965done
1966EOF
1967        }
1968        close(PBS);
1969        chmod 0755,"$ENV{'PBBUILDDIR'}/pbscript.$$";
1970    } else {
1971        return;
1972    }
1973
1974    # Useless for VE
1975    my $nport = pb_get_port($sshport,$pbos,$cmt) if ($cmt !~ /^VE/);
1976
1977    # Remove a potential $ENV{'HOME'} as tdir should be relative to pb's home
1978    $tdir =~ s|\$ENV.+\}/||;
1979
1980    my $tm = "";
1981    if ($cmt =~ /^(V|R)M/) {
1982        $tm = "sleep $vtmout" if (defined $vtmout);
1983    }
1984
1985    # ssh communication if not VE or CPAN
1986    # should use a hash instead...
1987    my ($shcmd,$cpcmd,$cptarget,$cp2target);
1988    if ($cmt =~ /^VE/) {
1989        my $tp = $vepath->{$ENV{'PBPROJ'}};
1990        my $tpdir = "$tp/$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}";
1991        my ($ptr) = pb_conf_get("vetype");
1992        my $vetype = $ptr->{$ENV{'PBPROJ'}};
1993        if ($vetype eq "chroot") {
1994            $shcmd = "sudo /usr/sbin/chroot $tpdir /bin/su - $mac -c ";
1995        } elsif ($vetype eq "schroot") {
1996            $shcmd = "schroot $tp -u $mac -- ";
1997        }
1998        $cpcmd = "sudo /bin/cp -r ";
1999        # We need to get the home dir of the target account to deliver in the right place
2000        open(PASS,"$tpdir/etc/passwd") || die "Unable to open $tpdir/etc/passwd";
2001        my $homedir = "";
2002        while (<PASS>) {
2003            my ($c1,$c2,$c3,$c4,$c5,$c6,$c7) = split(/:/);
2004            $homedir = $c6 if ($c1 =~ /^$mac$/);
2005            pb_log(3,"Homedir: $homedir - account: $c6\n");
2006        }
2007        close(PASS);
2008        $cptarget = "$tpdir/$homedir/$tdir";
2009        if ($cmt eq "VEbuild") {
2010            $cp2target = "$tpdir/$homedir/$bdir";
2011        }
2012        pb_log(2,"On VE using $cptarget as target dir to copy to\n");
2013    } elsif ($cmt =~ /^CPAN/) {
2014        my $ftpput = pb_check_req("ncftpput",1);
2015        my $ftpget = pb_check_req("wget",1);
2016        my ($cpanuser,$cpanpasswd) = pb_conf_get("cpanuser","cpanpasswd");
2017        my ($cpansubdir) = pb_conf_get_if("cpansubdir");
2018        $shcmd = "$ftpget --post-data \'HIDDENNAME=".$cpanuser;
2019        $shcmd .= "&user=".$cpanuser;
2020        $shcmd .= "&password=".$cpanpasswd;
2021        $shcmd .= "&SUBMIT_pause99_add_uri_upload=\"Upload the checked files\"";
2022        $shcmd .= "&pause99_add_uri_subdirtext=".$cpansubdir if (defined $cpansubdir);
2023        foreach my $s (split(/ /,$src)) {
2024            $shcmd .= "&pause99_add_uri_upload=".basename($s);
2025        }
2026        $shcmd .= "'";
2027        $cpcmd = "$ftpput $host $dir";
2028        $cptarget = "CPAN";
2029    } else {
2030        my $keyfile = pb_ssh_get(0);
2031        my $sshcmd = pb_check_req("ssh",1);
2032        my $scpcmd = pb_check_req("scp",1);
2033        $shcmd = "$sshcmd -i $keyfile -q -o UserKnownHostsFile=/dev/null -p $nport $mac";
2034        $cpcmd = "$scpcmd -i $keyfile -p -o UserKnownHostsFile=/dev/null -P $nport";
2035        $cptarget = "$mac:$tdir";
2036        if ($cmt =~ /^(V|R)Mbuild/) {
2037            $cp2target = "$mac:$bdir";
2038        }
2039    }
2040   
2041    my $logres = "";
2042    # Do not touch when just announcing
2043    if (($cmt ne "Announce") && ($cmt ne "CPAN")) {
2044        pb_system("$shcmd \"mkdir -p $tdir ; cd $tdir ; echo \'for i in $basesrc; do if [ -f \$i ]; then rm -f \$i; fi; done\ ; $cmd' | bash\"","Preparing $tdir on $cptarget");
2045    } else {
2046        $logres = "> ";
2047    }
2048    pb_system("cd $ENV{'PBBUILDDIR'} ; $cpcmd $src $cptarget 2> /dev/null","$cmt delivery in $cptarget");
2049
2050    # For VE we need to change the owner manually
2051    if ($cmt =~ /^VE/) {
2052        pb_system("$shcmd \"sudo chown -R $mac $tdir\"","Adapt owner in $tdir to $mac");
2053    }
2054
2055    # Use the right script name depending on context
2056    my $pbscript;
2057    if (($cmt =~ /^(V[EM]|RM)/) || ($cmt =~ /Packages/)){
2058        $pbscript = "pbscript.$$";
2059    } else {
2060        $pbscript = "pbscript";
2061    }
2062
2063    # It's already ready for CPAN
2064    my $shcmdbase = $shcmd;
2065    if ($cmt !~ /^CPAN/) {
2066        $shcmd .= " \"echo \'cd $tdir ; if [ -x $pbscript ]; then ./$pbscript; fi ; rm -f ./$pbscript\' | bash\"";
2067    }
2068    my $cmdverb = "verbose";
2069    if (($cmt eq "Announce") || ($cmt eq "CPAN")) {
2070        $cmdverb = undef;
2071    }
2072    pb_system("$shcmd","Executing pbscript on $cptarget if needed",$cmdverb);
2073    if ($cmt =~ /^(V[EM]|RM)build/) {
2074        # Get back info on pkg produced, compute their name and get them from the VM/RM
2075        pb_system("$cpcmd $cp2target/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}-$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'} $ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.$$ 2> /dev/null","Get package names in $cp2target");
2076        # For VE we need to change the owner manually
2077        if ($cmt eq "VEbuild") {
2078            pb_system("sudo chown $UID $ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.$$","Adapt owner in $tdir to $UID");
2079        }
2080        if (not -f "$ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.$$") {
2081            pb_log(0,"Problem with VM/RM $v on $ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.$$");
2082        } else {
2083            open(KEEP,"$ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.$$") || die "Unable to read $ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.$$";
2084            my $src = <KEEP>;
2085            chomp($src);
2086            close(KEEP);
2087            unlink("$ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.$$");
2088
2089            $src =~ s/^ *//;
2090            pb_mkdir_p("$ENV{'PBBUILDDIR'}/$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}");
2091            # Change pgben to make the next send2target happy
2092            my $made = "";
2093   
2094            # For VM/RM we don't want shell expansion to hapen locally but remotely
2095            my $delim = '\'';
2096            if ($cmt =~ /^VEbuild/) {
2097                # For VE we need to support shell expansion locally
2098                $delim = "";
2099            }   
2100
2101            open(KEEP,"> $ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}-$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}") || die "Unable to write $ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}-$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}";
2102            foreach my $p (split(/ +/,$src)) {
2103                my $j = basename($p);
2104                pb_system("$cpcmd $cp2target/$delim$p$delim $ENV{'PBBUILDDIR'}/$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'} 2> /dev/null","Recovery of package $j in $ENV{'PBBUILDDIR'}/$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}");
2105                $made="$made $pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}/$j"; # if (($pbos->{'type'} ne "rpm") || ($j !~ /.src.rpm$/));
2106            }
2107            print KEEP "$made\n";
2108            close(KEEP);
2109            pb_system("$shcmdbase \"rm -rf $tdir $bdir\"","$cmt cleanup");
2110
2111            # Sign packages locally
2112            pb_sign_pkgs($pbos,$made);
2113
2114            # We want to send them to the ssh account so overwrite what has been done before
2115            undef $pbaccount;
2116            pb_log(2,"Before sending pkgs, vmexist: $vmexist, vmpid: $vmpid\n");
2117            pb_send2target("Packages",$pbos->{'name'}."-".$pbos->{'version'}."-".$pbos->{'arch'},$vmexist,$vmpid);
2118            pb_rm_rf("$ENV{'PBBUILDDIR'}/$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}");
2119        }
2120    }
2121    unlink("$ENV{'PBDESTDIR'}/pbscript.$$") if (($cmt =~ /^(V[ME]|RM)/) || ($cmt =~ /Packages/));
2122
2123    pb_log(2,"Before halt, vmexist: $vmexist, vmpid: $vmpid\n");
2124    if ((! $vmexist) && ($cmt =~ /^VM/)) {
2125        # If in setupvm then takes a snapshot just before halting
2126        if ($snapme != 0) {
2127            my ($vmmonport,$vmtype) = pb_conf_get("vmmonport","vmtype");
2128            # For monitoring control
2129            if ((($vmtype->{$ENV{'PBPROJ'}}) eq "kvm") || (($vmtype->{$ENV{'PBPROJ'}}) eq "qemu")) {
2130                eval
2131                {
2132                require Net::Telnet;
2133                Net::Telnet->import();
2134                };
2135                if ($@) {
2136                    # Net::Telnet not found
2137                    pb_log(1,"ADVISE: Install Net::Telnet to benefit from monitoring control and snapshot feature.\nWARNING: No snapshot created");
2138                } else {
2139                    my $t = new Net::Telnet (Timeout => 120, Host => "localhost", Port => $vmmonport->{$ENV{'PBPROJ'}}) || die "Unable to dialog on the monitor";
2140                    # move to monitor mode
2141                    my @lines = $t->cmd("c");
2142                    # Create a snapshot named pb
2143                    @lines = $t->cmd("savevm pb");
2144                    # Write the new status in the VM
2145                    @lines = $t->cmd("commit all");
2146                    # End
2147                    @lines = $t->cmd("quit");
2148                }
2149            }
2150        }
2151        my $hoption = "-p";
2152        my $hpath = pb_distro_get_param($pbos,pb_conf_get("ospathcmd-halt"));
2153        # Solaris doesn't support -p of halt
2154        if ($pbos->{'type'} eq "pkg") {
2155            $hoption = "" ;
2156        }
2157        pb_system("$shcmdbase \"sudo $hpath $hoption \"; $tm ; echo \'if [ -d /proc/$vmpid ]; then kill -9 $vmpid; fi \' | bash ; sleep 10","VM $v halt (pid $vmpid)");
2158    }
2159    if (($cmt =~ /^VE/) && ($snapme != 0)) {
2160        my $tpdir = "$vepath->{$ENV{'PBPROJ'}}/$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}";
2161        pb_system("sudo tar cz -C $tpdir -f $vepath->{$ENV{'PBPROJ'}}/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}.tar.gz .","Creating a snapshot of $tpdir");
2162    }
2163}
2164
2165sub pb_script2v {
2166    my $pbscript=shift;
2167    my $vtype=shift;
2168    my $pbforce=shift || 0; # Force stop of VM. Default not.
2169    my $vm1=shift || undef; # Only that VM/VE/RM to treat. Default all.
2170    my $snapme=shift || 0;  # Do we have to create a snapshot. Default not.
2171    my $vm;
2172    my $all;
2173
2174    pb_log(2,"DEBUG: pb_script2v($pbscript,$vtype,$pbforce,".Dumper($vm1).",$snapme)\n");
2175    # Prepare the script to be executed on the VM/VE/RM
2176    # in $ENV{'PBDESTDIR'}/pbscript.$$
2177    if ((defined $pbscript ) && ($pbscript ne "$ENV{'PBDESTDIR'}/pbscript.$$")) {
2178        copy($pbscript,"$ENV{'PBDESTDIR'}/pbscript.$$") || die "Unable to create $ENV{'PBDESTDIR'}/pbscript.$$";
2179        chmod 0755,"$ENV{'PBDESTDIR'}/pbscript.$$";
2180    }
2181
2182    if (not defined $vm1) {
2183        ($vm,$all) = pb_get2v($vtype);
2184    } else {
2185        @$vm = ($vm1);
2186    }
2187    my ($vmexist,$vmpid) = (undef,undef);
2188
2189    foreach my $v (@$vm) {
2190        # Launch VM/VE
2191        ($vmexist,$vmpid) = pb_launchv($vtype,$v,0,$snapme,$pbsnap);
2192
2193        if ($vtype eq "vm") {
2194            pb_log(2,"DEBUG: After pb_launchv, vmexist: $vmexist, vmpid: $vmpid\n");
2195
2196            # Skip that VM/RM if something went wrong
2197            next if (($vmpid == 0) && ($vmexist == 0));
2198
2199            # If force stopping the VM then reset vmexist
2200            if ($pbforce == 1) {
2201                $vmpid = $vmexist;
2202                $vmexist = 0;
2203            }
2204        } else {
2205            #VE
2206            $vmexist = 0;
2207            $vmpid = 0;
2208        }
2209
2210        # Gather all required files to send them to the VM/VE/RM
2211        # and launch the build through pbscript
2212        pb_log(2,"DEBUG: Before send2target, vmexist: $vmexist, vmpid: $vmpid\n");
2213        pb_send2target(uc($vtype)."Script","$v",$vmexist,$vmpid,$snapme);
2214
2215    }
2216}
2217
2218sub pb_launchv {
2219    my $vtype = shift;
2220    my $v = shift;
2221    my $create = shift || 0;        # By default do not create a VM/VE/RM
2222    my $snapme = shift || 0;        # By default do not snap a VM/VE/RM
2223    my $usesnap = shift || 1;       # By default study the usage of the snapshot feature of VM/VE/RM   
2224
2225    # If creation or snapshot creation mode, no snapshot usable
2226    if (($create == 1) || ($snapme == 1)) {
2227        $usesnap = 0;
2228    }
2229
2230    pb_log(2,"DEBUG: pb_launchv($vtype,$v,$create,$snapme,$usesnap)\n");
2231    die "No VM/VE/RM defined, unable to launch" if (not defined $v);
2232    # Keep only the first VM in case many were given
2233    $v =~ s/,.*//;
2234
2235    my $pbos = pb_distro_get_context($v);
2236   
2237    # Launch the VMs/VEs
2238    if ($vtype eq "vm") {
2239        die "-i iso parameter needed" if (((not defined $iso) || ($iso eq "")) && ($create != 0));
2240
2241        # TODO: vmmonport should be optional
2242        my ($ptr,$ptr2,$vmpath,$vmport,$vms,$vmmonport) = pb_conf_get("vmtype","vmcmd","vmpath","vmport","vmsize","vmmonport");
2243        my ($vmopt,$vmmm,$vmtmout,$vmsnap,$vmbuildtm) = pb_conf_get_if("vmopt","vmmem","vmtmout","vmsnap","vmbuildtm");
2244        my $vmsize = pb_distro_get_param($pbos,$vms);
2245
2246        my $vmtype = $ptr->{$ENV{'PBPROJ'}};
2247        my $vmcmd = $ptr2->{$ENV{'PBPROJ'}};
2248
2249        if (defined $opts{'g'}) {
2250            if (($vmtype eq "kvm") || ($vmtype eq "qemu")) {
2251                $ENV{'PBVMOPT'} = "--nographic";
2252            }
2253        }
2254        if (not defined $ENV{'PBVMOPT'}) {
2255            $ENV{'PBVMOPT'} = "";
2256        }
2257        # Save the current status for later restoration
2258        $ENV{'PBOLDVMOPT'} = $ENV{'PBVMOPT'};
2259        # Set a default timeout of 2 minutes
2260        if (not defined $ENV{'PBVMTMOUT'}) {
2261            $ENV{'PBVMTMOUT'} = "120";
2262        }
2263        if (defined $vmopt->{$v}) {
2264            $ENV{'PBVMOPT'} .= " $vmopt->{$v}" if ($ENV{'PBVMOPT'} !~ / $vmopt->{$v}/);
2265        } elsif (defined $vmopt->{$ENV{'PBPROJ'}}) {
2266            $ENV{'PBVMOPT'} .= " $vmopt->{$ENV{'PBPROJ'}}" if ($ENV{'PBVMOPT'} !~ / $vmopt->{$ENV{'PBPROJ'}}/);
2267        }
2268
2269        # How much memory to allocate for VMs
2270        my $vmmem = pb_distro_get_param($pbos,$vmmm);
2271        if (defined $vmmem) {
2272            $ENV{'PBVMOPT'} .= " -m $vmmem";
2273        }
2274
2275        # Are we allowed to use snapshot feature
2276        if ($usesnap == 1) {
2277            if ((defined $vmsnap->{$v}) && ($vmsnap->{$v} =~ /true/i)) {
2278                $ENV{'PBVMOPT'} .= " -snapshot";
2279            } elsif ((defined $vmsnap->{$ENV{'PBPROJ'}}) && ($vmsnap->{$ENV{'PBPROJ'}} =~ /true/i)) {
2280                $ENV{'PBVMOPT'} .= " -snapshot";
2281            } elsif ($pbsnap eq 1) {
2282                $ENV{'PBVMOPT'} .= " -snapshot";
2283            }
2284        } 
2285        if ($snapme != 0) {
2286            if (($vmtype eq "kvm") || ($vmtype eq "qemu")) {
2287                # Configure the monitoring to automate the creation of the 'pb' snapshot
2288                $ENV{'PBVMOPT'} .= " -serial mon:telnet::$vmmonport->{$ENV{'PBPROJ'}},server,nowait";
2289                # In that case no snapshot call needed
2290                $ENV{'PBVMOPT'} =~ s/ -snapshot//;
2291            }
2292        }
2293        if (defined $vmtmout->{$v}) {
2294            $ENV{'PBVMTMOUT'} = $vmtmout->{$v};
2295        } elsif (defined $vmtmout->{$ENV{'PBPROJ'}}) {
2296            $ENV{'PBVMTMOUT'} = $vmtmout->{$ENV{'PBPROJ'}};
2297        }
2298        my $nport = pb_get_port($vmport,$pbos,$vtype);
2299   
2300        my $cmd;
2301        my $vmm;        # has to be used for pb_check_ps
2302        if (($vmtype eq "qemu") || ($vmtype eq "kvm")) {
2303            $vmm = "$vmpath->{$ENV{'PBPROJ'}}/$v.qemu";
2304            if (($create != 0) || (defined $iso)) {
2305                $ENV{'PBVMOPT'} .= " -cdrom $iso -boot d";
2306            }
2307            # Always redirect the network and always try to use a 'pb' snapshot
2308            #$cmd = "$vmcmd $ENV{'PBVMOPT'} -net user,hostfwd=tcp:$nport:10.0.2.15:22 -loadvm pb $vmm"
2309            $cmd = "$vmcmd $ENV{'PBVMOPT'} -redir tcp:$nport:10.0.2.15:22 $vmm"
2310        } elsif ($vmtype eq "xen") {
2311        } elsif ($vmtype eq "vmware") {
2312        } else {
2313            die "VM of type $vmtype not supported. Report to the dev team";
2314        }
2315        # Restore the ENV VAR Value
2316        $ENV{'PBVMOPT'} = $ENV{'PBOLDVMOPT'};
2317
2318        my ($tmpcmd,$void) = split(/ +/,$cmd);
2319        my $vmexist = pb_check_ps($tmpcmd,$vmm);
2320        my $vmpid = 0;
2321        if (! $vmexist) {
2322            if ($create != 0) {
2323                die("Found an existing Virtual machine $vmm. Won't overwrite") if (-r $vmm);
2324                if (($vmtype eq "qemu") || ($vmtype eq "xen") || ($vmtype eq "kvm")) {
2325                    my $command = pb_check_req("qemu-img",0);
2326                    pb_system("$command create -f qcow2 $vmm $vmsize","Creating the QEMU VM");
2327                } elsif ($vmtype eq "vmware") {
2328                } else {
2329                }
2330            }
2331            if (! -f "$vmm") {
2332                pb_log(0,"Unable to find VM $vmm\n");
2333            } else {
2334                # Is the SSH port free? if not kill the existing process using it after a build timeout period
2335                my $vmssh = pb_check_ps($tmpcmd,"tcp:$nport:10.0.2.15:22");
2336                if ($vmssh) {
2337                    my $buildtm = $ENV{'PBVMTMOUT'};
2338                    if (defined $vmbuildtm->{$v}) {
2339                        $buildtm = $vmbuildtm->{$v};
2340                    } elsif (defined $vmbuildtm->{$ENV{'PBPROJ'}}) {
2341                        $buildtm = $vmbuildtm->{$ENV{'PBPROJ'}};
2342                    }
2343
2344                    sleep $buildtm;
2345                    pb_log(0,"WARNING: Killing the process ($vmssh) using port $nport (previous failed VM ?)\n");
2346                    kill 15,$vmssh;
2347                    # Let it time to exit
2348                    sleep 5;
2349                }
2350                pb_system("$cmd &","Launching the VM $vmm");
2351                # Using system allows to kill it externaly if needed
2352                pb_system("sleep $ENV{'PBVMTMOUT'}","Waiting $ENV{'PBVMTMOUT'} s for VM $v to come up");
2353                $vmpid = pb_check_ps($tmpcmd,$vmm);
2354                pb_log(0,"VM $vmm launched (pid $vmpid)\n");
2355            }
2356        } else {
2357            pb_log(0,"Found an existing VM $vmm (pid $vmexist)\n");
2358        }
2359        pb_log(2,"DEBUG: pb_launchv returns ($vmexist,$vmpid)\n");
2360        return($vmexist,$vmpid);
2361    } elsif ($vtype eq "ve") {
2362        # Force the creation of the VE and no snapshot usable
2363        pb_ve_launch($v,$create,$usesnap);
2364    } else {
2365        # RM here
2366        # Get distro context
2367        my $pbos = pb_distro_get_context($v);
2368
2369        # Get RM context
2370        my ($ptr,$rmpath) = pb_conf_get("rmtype","rmpath");
2371
2372        # Nothing more to do for RM. No real launch
2373        # For the moment we support the RM is already running
2374        # For ProLiant may be able to power them on if needed later on as an example.
2375    }
2376}
2377
2378# Return string for date synchro
2379sub pb_date2v {
2380
2381my $vtype = shift;
2382my $pbos = shift;
2383
2384my ($ntp) = pb_conf_get_if($vtype."ntp");
2385my $vntp = $ntp->{$ENV{'PBPROJ'}} if (defined $ntp);
2386my $ntpline = undef;
2387
2388if (defined $vntp) {
2389    # ntp command depends on pbos
2390    my $vntpcmd = pb_distro_get_param($pbos,pb_conf_get($vtype."ntpcmd"));
2391    $ntpline = "sudo $vntpcmd $vntp";
2392}
2393# Force new date to be in the future compared to the date
2394# of the host by adding 1 minute
2395my @date=pb_get_date();
2396$date[1]++;
2397my $upddate = strftime("%m%d%H%M%Y", @date);
2398my $dateline = "sudo /bin/date $upddate";
2399if (defined $ntpline) {
2400    return($ntpline);
2401} else {
2402    return($dateline);
2403}
2404}
2405
2406sub pb_build2v {
2407
2408my $vtype = shift;
2409my $action = shift || "build";
2410
2411my ($v,$all) = pb_get2v($vtype);
2412
2413# Send tar files when we do a global generation
2414pb_build2ssh() if (($all == 1) && ($action eq "build"));
2415
2416# Adapt // mode to memory size
2417$pbparallel = pb_set_parallel($vtype);
2418
2419my ($vmexist,$vmpid) = (undef,undef);
2420my $pm;
2421if (defined $pbparallel) {
2422    $pm = new Parallel::ForkManager($pbparallel);
2423
2424    # Set which port the VM/RM will use to communicate
2425    $pm->run_on_start(\&pb_set_port);
2426}
2427
2428my $counter = 0;
2429foreach my $v (@$v) {
2430    $counter++;
2431    # Modulo 2 * pbparallel (to avoid synchronization problems)
2432    $counter = 1 if ((defined $pbparallel) && ($counter > 2 * $pbparallel));
2433    $pm->start($counter) and next if (defined $pbparallel);
2434    # Prepare the script to be executed on the VM/VE/RM
2435    # in $ENV{'PBDESTDIR'}/pbscript.$$
2436    open(SCRIPT,"> $ENV{'PBDESTDIR'}/pbscript.$$") || die "Unable to create $ENV{'PBDESTDIR'}/pbscript.$$";
2437    print SCRIPT "#!/bin/bash\n";
2438
2439    # Transmit the verbosity level to the virtual env/mach.
2440    my $verbose = "";
2441    my $i = 0;                          # minimal debug level
2442    while ($i lt $pbdebug) {
2443        $verbose .= "-v ";
2444        $i++;
2445    }
2446    # Activate script verbosity if at least 2 for pbdebug
2447    print SCRIPT "set -x\n" if ($i gt 1);
2448    # Quiet if asked to be so on the original system
2449    $verbose = "-q" if ($pbdebug eq -1);
2450
2451    print SCRIPT "echo ... Execution needed\n";
2452    print SCRIPT "# This is in directory delivery\n";
2453    print SCRIPT "# Setup the variables required for building\n";
2454    print SCRIPT "export PBPROJ=$ENV{'PBPROJ'}\n";
2455
2456    if ($action eq "build") {
2457        print SCRIPT "# Preparation for pb\n";
2458        print SCRIPT "mv .pbrc \$HOME\n";
2459        print SCRIPT "cd ..\n";
2460    }
2461
2462    # VE needs a good /proc
2463    if ($vtype eq "ve") {
2464        print SCRIPT "sudo /bin/mount -t proc /proc /proc\n";
2465    }
2466
2467    # Get distro context
2468    my $pbos = pb_distro_get_context($v);
2469   
2470    my $ntpline = pb_date2v($vtype,$pbos);
2471    print SCRIPT "# Time sync\n";
2472    print SCRIPT "echo 'setting up date with '";
2473    print SCRIPT "echo $ntpline\n";
2474    print SCRIPT "$ntpline\n";
2475    # Use potential local proxy declaration in case we need it to download repo, pkgs, ...
2476    if (defined $ENV{'http_proxy'}) {
2477        print SCRIPT "export http_proxy=\"$ENV{'http_proxy'}\"\n";
2478    }
2479
2480    if (defined $ENV{'ftp_proxy'}) {
2481        print SCRIPT "export ftp_proxy=\"$ENV{'ftp_proxy'}\"\n";
2482    }
2483
2484    # Get list of packages to build/test and get some ENV vars as well
2485    my $ptr = pb_get_pkg();
2486    @pkgs = @$ptr;
2487    my $p = join(' ',@pkgs) if (@pkgs);
2488    print SCRIPT "export PBPROJVER=$ENV{'PBPROJVER'}\n";
2489    print SCRIPT "export PBPROJTAG=$ENV{'PBPROJTAG'}\n";
2490    print SCRIPT "export PBPACKAGER=\"$ENV{'PBPACKAGER'}\"\n";
2491
2492    # We may need to do some other tasks before building. Read a script here to finish setup
2493    if (-x "$ENV{'PBDESTDIR'}/pb$vtype".".pre") {
2494        print SCRIPT "# Special pre-instructions to be launched\n";
2495        print SCRIPT pb_get_content("$ENV{'PBDESTDIR'}/pb$vtype".".pre");
2496    }
2497
2498    if (-x "$ENV{'PBDESTDIR'}/pb$vtype"."$action.pre") {
2499        print SCRIPT "# Special pre-$action instructions to be launched\n";
2500        print SCRIPT pb_get_content("$ENV{'PBDESTDIR'}/pb$vtype"."$action.pre");
2501    }
2502
2503    print SCRIPT "# $action\n";
2504    print SCRIPT "echo $action"."ing packages on $vtype...\n";
2505
2506    if (($action eq "test") && (! -x "$ENV{'PBDESTDIR'}/pbtest")) {
2507            die "No test script ($ENV{'PBDESTDIR'}/pbtest) found when in test mode. Aborting ...";
2508    }
2509    print SCRIPT "pb $verbose -p $ENV{'PBPROJ'} $action"."2pkg $p\n";
2510
2511    if ($vtype eq "ve") {
2512        print SCRIPT "sudo /bin/umount /proc\n";
2513    }
2514
2515    # We may need to do some other tasks after building. Read a script here to exit properly
2516    if (-x "$ENV{'PBDESTDIR'}/pb$vtype"."$action.post") {
2517        print SCRIPT "# Special post-$action instructions to be launched\n";
2518        print SCRIPT pb_get_content("$ENV{'PBDESTDIR'}/pb$vtype"."$action.post");
2519    }
2520
2521    if (-x "$ENV{'PBDESTDIR'}/pb$vtype".".post") {
2522        print SCRIPT "# Special post-instructions to be launched\n";
2523        print SCRIPT pb_get_content("$ENV{'PBDESTDIR'}/pb$vtype".".post");
2524    }
2525
2526    close(SCRIPT);
2527    chmod 0755,"$ENV{'PBDESTDIR'}/pbscript.$$";
2528   
2529    # Launch the VM/VE/RM
2530    ($vmexist,$vmpid) = pb_launchv($vtype,$v,0);
2531
2532
2533    if ($vtype eq "vm") {
2534        # Skip that VM if something went wrong
2535        if (($vmpid == 0) && ($vmexist == 0)) {
2536            $pm->finish if (defined $pbparallel);
2537            next;
2538        }
2539    } else {
2540        # VE/RM
2541        $vmexist = 0;
2542        $vmpid = 0;
2543    }
2544    # Gather all required files to send them to the VM/VE
2545    # and launch the build through pbscript
2546    pb_log(2,"Calling send2target $vtype,$v,$vmexist,$vmpid\n");
2547    pb_send2target(uc($vtype).$action,"$v",$vmexist,$vmpid);
2548    $pm->finish if (defined $pbparallel);
2549}
2550$pm->wait_all_children if (defined $pbparallel);
2551}
2552
2553
2554sub pb_clean {
2555
2556    my $sleep=10;
2557    die "Unable to get env var PBDESTDIR" if (not defined $ENV{'PBDESTDIR'});
2558    die "Unable to get env var PBBUILDDIR" if (not defined $ENV{'PBBUILDDIR'});
2559    pb_log(0,"We will now wait $sleep s before removing both directories\n$ENV{'PBDESTDIR'} and $ENV{'PBBUILDDIR'}.\nPlease break me if this is wrong\n");
2560    sleep $sleep;
2561    pb_rm_rf($ENV{'PBDESTDIR'});
2562    pb_rm_rf($ENV{'PBBUILDDIR'});
2563}
2564
2565sub pb_newver {
2566
2567    die "-V Version parameter needed" if ((not defined $newver) || ($newver eq ""));
2568
2569    # Need this call for PBDIR
2570    my ($scheme2,$uri) = pb_cms_init($pbinit);
2571
2572    my ($pbconf,$pburl) = pb_conf_get("pbconfurl","pburl");
2573    $uri = $pbconf->{$ENV{'PBPROJ'}};
2574    my ($scheme, $account, $host, $port, $path) = pb_get_uri($uri);
2575
2576    # Checking CMS repositories status
2577    ($scheme2, $account, $host, $port, $path) = pb_get_uri($pburl->{$ENV{'PBPROJ'}});
2578
2579    if ($scheme !~ /^svn/) {
2580        die "Only SVN is supported at the moment";
2581    }
2582
2583    my $res = pb_cms_isdiff($scheme,$ENV{'PBROOTDIR'});
2584    die "ERROR: No differences accepted in CMS for $ENV{'PBROOTDIR'} before creating a new version" if ($res != 0);
2585
2586    $res = pb_cms_isdiff($scheme2,$ENV{'PBDIR'});
2587    die "ERROR: No differences accepted in CMS for $ENV{'PBDIR'} before creating a new version" if ($res != 0);
2588
2589    # Tree identical between PBCONFDIR and PBROOTDIR. The delta is what
2590    # we want to get for the root of the new URL
2591
2592    my $oldver = $ENV{'PBROOTDIR'};
2593    $oldver =~ s|^$ENV{'PBCONFDIR'}||;
2594
2595    pb_log(2, "PBCONFDIR: $ENV{'PBCONFDIR'}\nPBROOTDIR: $ENV{'PBROOTDIR'}\n");
2596
2597    my $newurl = "$uri/$newver";
2598    # Should probably use projver in the old file
2599    my $oldvertxt= basename($oldver);
2600    my $newvertxt = basename($newver);
2601
2602    # Duplicate and extract project-builder part
2603    pb_log(2,"Copying $uri/$oldver to $newurl\n");
2604    pb_cms_copy($scheme,"$uri/$oldver",$newurl);
2605    pb_log(2,"Checkout $newurl to $ENV{'PBCONFDIR'}/$newver\n");
2606    pb_cms_up($scheme,"$ENV{'PBCONFDIR'}");
2607
2608    # Duplicate and extract project
2609    my $newurl2 = "$pburl->{$ENV{'PBPROJ'}}/$newver";
2610
2611    pb_log(2,"Copying $pburl->{$ENV{'PBPROJ'}}/$oldver to $newurl2\n");
2612    pb_cms_copy($scheme2,"$pburl->{$ENV{'PBPROJ'}}/$oldver",$newurl2);
2613
2614    my $tmp = $ENV{'PBDIR'};
2615    $tmp =~ s|$oldver$||;
2616    pb_log(2,"Checkout $newurl2 to $tmp/$newver\n");
2617    pb_cms_up($scheme2,"$tmp");
2618
2619    # Update the .pb file
2620    open(FILE,"$ENV{'PBCONFDIR'}/$newver/$ENV{'PBPROJ'}.pb") || die "Unable to open $ENV{'PBCONFDIR'}/$newver/$ENV{'PBPROJ'}.pb";
2621    open(OUT,"> $ENV{'PBCONFDIR'}/$newver/$ENV{'PBPROJ'}.pb.new") || die "Unable to write to $ENV{'PBCONFDIR'}/$newver/$ENV{'PBPROJ'}.pb.new";
2622    while(<FILE>) {
2623        if (/^projver\s+$ENV{'PBPROJ'}\s*=\s*$oldvertxt/) {
2624            s/^projver\s+$ENV{'PBPROJ'}\s*=\s*$oldvertxt/projver $ENV{'PBPROJ'} = $newvertxt/;
2625            pb_log(0,"Changing projver from $oldvertxt to $newvertxt in $ENV{'PBCONFDIR'}/$newver/$ENV{'PBPROJ'}.pb\n");
2626        }
2627        if (/^testver/) {
2628            s/^testver/#testver/;
2629            pb_log(0,"Commenting testver in $ENV{'PBCONFDIR'}/$newver/$ENV{'PBPROJ'}.pb\n") if (/^testver/);
2630        }
2631        if (/^delivery/) {
2632            pb_log(0,"Please check delivery (".chomp($_).") in $ENV{'PBCONFDIR'}/$newver/$ENV{'PBPROJ'}.pb\n");
2633        }
2634        print OUT $_;
2635    }
2636    close(FILE);
2637    close(OUT);
2638    rename("$ENV{'PBCONFDIR'}/$newver/$ENV{'PBPROJ'}.pb.new","$ENV{'PBCONFDIR'}/$newver/$ENV{'PBPROJ'}.pb");
2639
2640    # Checking pbcl files
2641    foreach my $f (<$ENV{'PBROOTDIR'}/*/pbcl>) {
2642        # Compute new pbcl file
2643        my $f2 = $f;
2644        $f2 =~ s|$ENV{'PBROOTDIR'}|$ENV{'PBCONFDIR'}/$newver/|;
2645        open(PBCL,$f) || die "Unable to open $f";
2646        my $foundnew = 0;
2647        while (<PBCL>) {
2648            $foundnew = 1 if (/^$newvertxt \(/);
2649        }
2650        close(PBCL);
2651        open(OUT,"> $f2") || die "Unable to write to $f2: $!";
2652        open(PBCL,$f) || die "Unable to open $f";
2653        while (<PBCL>) {
2654            print OUT "$_" if (not /^$oldvertxt \(/);
2655            if ((/^$oldvertxt \(/) && ($foundnew == 0)) {
2656                print OUT "$newvertxt ($pbdate)\n";
2657                print OUT "- TBD\n";
2658                print OUT "\n";
2659                pb_log(0,"WARNING: version $newvertxt not found in $f so added to $f2...\n") if ($foundnew == 0);
2660            }
2661        }
2662        close(OUT);
2663        close(PBCL);
2664    }
2665
2666    pb_log(2,"Checkin $ENV{'PBCONFDIR'}/$newver\n");
2667    pb_cms_checkin($scheme,"$ENV{'PBCONFDIR'}/$newver",undef);
2668}
2669
2670#
2671# Return the list of VMs/VEs/RMs we are working on
2672# $all is a flag to know if we return all of them
2673# or only some (if all we publish also tar files in addition to pkgs
2674#
2675sub pb_get2v {
2676
2677my $vtype = shift;
2678my @v;
2679my $all = 0;
2680my $pbv = 'PBV';
2681my $vlist = $vtype."list";
2682
2683# Get VM/VE list
2684if ((not defined $ENV{$pbv}) || ($ENV{$pbv} =~ /^all$/)) {
2685    my ($ptr) = pb_conf_get($vlist);
2686    $ENV{$pbv} = $ptr->{$ENV{'PBPROJ'}};
2687    $all = 1;
2688}
2689pb_log(2,"$vtype: $ENV{$pbv}\n");
2690@v = split(/,/,$ENV{$pbv});
2691return(\@v,$all);
2692}
2693
2694# Function to create a potentialy missing pb account on the VM/VE/RM, and adds it to sudo
2695# Needs to use root account to connect to the VM/VE/RM
2696# pb will take your local public SSH key to access
2697# the pb account in the VM/VE/RM later on if needed
2698sub pb_setup2v {
2699
2700my $vtype = shift;
2701my $sbx = shift || undef;
2702
2703my ($vm,$all) = pb_get2v($vtype);
2704
2705# Script generated
2706my $pbscript = "$ENV{'PBDESTDIR'}/setupv";
2707
2708# Adapt // mode to memory size
2709$pbparallel = pb_set_parallel($vtype);
2710
2711my $pm;
2712if (defined $pbparallel) {
2713    $pm = new Parallel::ForkManager($pbparallel);
2714
2715    # Set which port the VM/RM will use to communicate
2716    $pm->run_on_start(\&pb_set_port);
2717}
2718
2719my $counter = 0;
2720foreach my $v (@$vm) {
2721    $counter++;
2722    # Modulo pbparallel
2723    $counter = 1 if ((defined $pbparallel) && ($counter > $pbparallel));
2724    $pm->start($counter) and next if (defined $pbparallel);
2725
2726    # Get distro context
2727    my $pbos = pb_distro_get_context($v);
2728   
2729    # Deal with date sync.
2730    my $ntpline = pb_date2v($vtype,$pbos);
2731
2732    # Name of the account to deal with for VM/VE/RM
2733    # Do not use the one passed potentially with -a
2734    my ($pbac) = pb_conf_get($vtype."login");
2735    my ($key,$zero0,$zero1,$zero2);
2736    my ($vmexist,$vmpid);
2737
2738    # Prepare the script to be executed on the VM/VE/RM
2739    # in $ENV{'PBDESTDIR'}/setupv
2740    open(SCRIPT,"> $pbscript") || die "Unable to create $pbscript";
2741   
2742    print SCRIPT << 'EOF';
2743#!/usr/bin/perl -w
2744
2745use strict;
2746use File::Copy;
2747
2748# We should not need in this script more functions than what is provided
2749# by Base, Conf and Distribution to avoid problems at exec time.
2750# They are appended at the end.
2751
2752# Define mandatory global vars
2753our $pbdebug;
2754our $pbLOG;
2755our $pbsynmsg = "pbscript";
2756our $pbdisplaytype = "text";
2757our $pblocale = "";
2758pb_log_init($pbdebug, $pbLOG);
2759pb_temp_init();
2760
2761EOF
2762
2763    # Launch the VM/VE/RM - Usage of snapshot disabled
2764    ($vmexist,$vmpid) = pb_launchv($vtype,$v,0,0,0);
2765
2766    my $keyfile;
2767    my $nport;
2768    my $vmhost;
2769
2770    # Prepare the key to be used and transfered remotely
2771    $keyfile = pb_ssh_get(1);
2772       
2773    if ($vtype =~ /(v|r)m/) {
2774        my ($vmport);
2775        ($vmhost,$vmport) = pb_conf_get($vtype."host",$vtype."port");
2776        $nport = pb_get_port($vmport,$pbos,$vtype);
2777   
2778        # Skip that VM/RM if something went wrong
2779        next if (($vmpid == 0) && ($vmexist == 0));
2780   
2781        # Store the pub key part in a variable
2782        open(FILE,"$keyfile.pub") || die "Unable to open $keyfile.pub";
2783        ($zero0,$zero1,$zero2) = split(/ /,<FILE>);
2784        close(FILE);
2785
2786        $key = "\Q$zero1";
2787
2788        # We call true to avoid problems if SELinux is not activated, but chcon is present and returns in that case 1
2789        pb_system("cat $keyfile.pub | ssh -q -o UserKnownHostsFile=/dev/null -p $nport -i $keyfile root\@$vmhost->{$ENV{'PBPROJ'}} \"mkdir -p .ssh ; chmod 700 .ssh ; cat >> .ssh/authorized_keys ; chmod 600 .ssh/authorized_keys ; if [ -x /usr/bin/chcon ]; then /usr/bin/chcon -Rt home_ssh_t .ssh 2> /dev/null; /bin/true; fi\"","Copying local keys to $vtype. This may require the root password");
2790        # once this is done, we can do what we need on the VM/RM remotely
2791    } elsif ($vtype eq "ve") {
2792        print SCRIPT << "EOF";
2793# For VE we need a good null dev
2794pb_system("rm -f /dev/null; mknod /dev/null c 1 3; chmod 777 /dev/null");
2795EOF
2796        print SCRIPT << "EOF";
2797# For VE we first need to mount some FS
2798pb_system("mount -t proc /proc /proc");
2799
2800EOF
2801    }
2802
2803    if ($vtype =~ /(v|r)m/) {
2804        print SCRIPT << 'EOF';
2805# Removes duplicate in .ssh/authorized_keys of our key if needed
2806#
2807my $file1="$ENV{'HOME'}/.ssh/authorized_keys";
2808open(PBFILE,$file1) || die "Unable to open $file1";
2809open(PBOUT,"> $file1.new") || die "Unable to open $file1.new";
2810my $count = 0;
2811while (<PBFILE>) {
2812
2813EOF
2814        print SCRIPT << "EOF";
2815    if (/ $key /) {
2816        \$count++;
2817    }
2818print PBOUT \$_ if ((\$count <= 1) || (\$_ !~ / $key /));
2819}
2820close(PBFILE);
2821close(PBOUT);
2822rename("\$file1.new",\$file1);
2823chmod 0600,\$file1;
2824
2825EOF
2826    }
2827    print SCRIPT << 'EOF';
2828
2829# Adds $pbac->{$ENV{'PBPROJ'}} as an account if needed
2830#
2831my $file="/etc/passwd";
2832open(PBFILE,$file) || die "Unable to open $file";
2833my $found = 0;
2834while (<PBFILE>) {
2835EOF
2836    print SCRIPT << "EOF";
2837    \$found = 1 if (/^$pbac->{$ENV{'PBPROJ'}}:/);
2838EOF
2839
2840# TODO: use an external parameter
2841my $home = "/home";
2842# Solaris doesn't like that we use /home
2843$home = "/export/home" if ($pbos->{'type'} eq "pkg");
2844
2845    print SCRIPT << "EOF";
2846}
2847close(PBFILE);
2848
2849if ( \$found == 0 ) {
2850    if ( ! -d "$home" ) {
2851        pb_mkdir_p("$home");
2852    }
2853EOF
2854    # TODO: Level of portability of these cmds ? Critical now for RM
2855    # TODO: Check existence before adding to avoid errors
2856    print SCRIPT << "EOF";
2857pb_system("/usr/sbin/groupadd $pbac->{$ENV{'PBPROJ'}}","Adding group $pbac->{$ENV{'PBPROJ'}}");
2858pb_system("/usr/sbin/useradd -g $pbac->{$ENV{'PBPROJ'}} -m -d $home/$pbac->{$ENV{'PBPROJ'}} $pbac->{$ENV{'PBPROJ'}}","Adding user $pbac->{$ENV{'PBPROJ'}} (group $pbac->{$ENV{'PBPROJ'}} - home $home/$pbac->{$ENV{'PBPROJ'}})");
2859}
2860EOF
2861
2862    # Copy the content of our local conf file to the VM/VE/RM
2863    my $content = pb_get_content(pb_distro_conffile());
2864    print SCRIPT << "EOF";
2865    #
2866    # Create a temporary local conf file for distribution support
2867    # This is created here before its use later. Its place is hardcoded, so no choice for the path
2868    #
2869    my \$tempconf = pb_distro_conffile();
2870    pb_mkdir_p(dirname(\$tempconf));
2871    open(CONF,"> \$tempconf") || die "Unable to create \$tempconf";
2872    print CONF q{$content};
2873    close(CONF);
2874EOF
2875
2876    if ($vtype =~ /(v|r)m/) {
2877        print SCRIPT << "EOF";
2878# allow ssh entry to build
2879#
2880mkdir "$home/$pbac->{$ENV{'PBPROJ'}}/.ssh",0700;
2881# Allow those accessing root to access the build account
2882copy("\$ENV{'HOME'}/.ssh/authorized_keys","$home/$pbac->{$ENV{'PBPROJ'}}/.ssh/authorized_keys");
2883chmod 0600,".ssh/authorized_keys";
2884pb_system("chown -R $pbac->{$ENV{'PBPROJ'}}:$pbac->{$ENV{'PBPROJ'}} $home/$pbac->{$ENV{'PBPROJ'}}","Finish setting up the account env for $pbac->{$ENV{'PBPROJ'}}");
2885
2886EOF
2887}
2888    print SCRIPT << 'EOF';
2889# No passwd for build account only keys
2890$file="/etc/shadow";
2891if (-f $file) {
2892    open(PBFILE,$file) || die "Unable to open $file";
2893    open(PBOUT,"> $file.new") || die "Unable to open $file.new";
2894    while (<PBFILE>) {
2895EOF
2896    print SCRIPT << "EOF";
2897        s/^$pbac->{$ENV{'PBPROJ'}}:\!\!:/$pbac->{$ENV{'PBPROJ'}}:*:/;
2898        s/^$pbac->{$ENV{'PBPROJ'}}:\!:/$pbac->{$ENV{'PBPROJ'}}:*:/; #SLES 9 e.g.
2899        s/^$pbac->{$ENV{'PBPROJ'}}:\\*LK\\*:/$pbac->{$ENV{'PBPROJ'}}:NP:/;  #Solaris e.g.
2900EOF
2901        print SCRIPT << 'EOF';
2902        print PBOUT $_;
2903    }
2904    close(PBFILE);
2905    close(PBOUT);
2906    rename("$file.new",$file);
2907    chmod 0640,$file;
2908    }
2909
2910# Keep the VM in text mode
2911$file="/etc/inittab";
2912if (-f $file) {
2913    open(PBFILE,$file) || die "Unable to open $file";
2914    open(PBOUT,"> $file.new") || die "Unable to open $file.new";
2915    while (<PBFILE>) {
2916        s/^(..):5:initdefault:$/$1:3:initdefault:/;
2917        print PBOUT $_;
2918    }
2919    close(PBFILE);
2920    close(PBOUT);
2921    rename("$file.new",$file);
2922    chmod 0640,$file;
2923}
2924
2925# pb has to be added to portage group on gentoo
2926
2927# We need to have that pb_distro_get_context function
2928# Get it from Project-Builder::Distribution
2929# And we now need the conf file required for this to work created above
2930
2931my $pbos = pb_distro_get_context(); 
2932print "distro tuple: ".Dumper($pbos)."\n";
2933
2934# Adapt sudoers
2935# sudo is not default on Solaris and needs to be installed first
2936# from http://www.sunfreeware.com/programlistsparc10.html#sudo
2937if ($pbos->{'type'} eq "pkg") {
2938    $file="/usr/local/etc/sudoers";
2939} else {
2940    $file="/etc/sudoers";
2941}
2942open(PBFILE,$file) || die "Unable to open $file";
2943open(PBOUT,"> $file.new") || die "Unable to open $file.new";
2944while (<PBFILE>) {
2945EOF
2946    # Skip what will be generated
2947    print SCRIPT << "EOF";
2948    next if (/^$pbac->{$ENV{'PBPROJ'}}\\s+/);
2949    next if (/^Defaults:$pbac->{$ENV{'PBPROJ'}}\\s+/);
2950    next if (/^Defaults:root \!requiretty/);
2951EOF
2952    print SCRIPT << 'EOF';
2953    s/Defaults[ \t]+requiretty//;
2954    print PBOUT $_;
2955}
2956close(PBFILE);
2957EOF
2958    print SCRIPT << "EOF";
2959# Some distro force requiretty at compile time, so disable here
2960print PBOUT "Defaults:$pbac->{$ENV{'PBPROJ'}} !requiretty\n";
2961print PBOUT "Defaults:root !requiretty\n";
2962# Keep proxy configuration while using sudo
2963print PBOUT "Defaults:$pbac->{$ENV{'PBPROJ'}}    env_keep += \\\"http_proxy ftp_proxy\\\"\n";
2964EOF
2965    # Try to restrict security to what is really needed
2966    if ($vtype =~ /^vm/) {
2967        my $hpath = pb_distro_get_param($pbos,pb_conf_get("ospathcmd-halt"));
2968        my @sudocmds = pb_get_sudocmds($pbos,$ntpline,"sudo $hpath");
2969        print SCRIPT << "EOF";
2970# This is needed in order to be able on VM to halt the machine from the $pbac->{$ENV{'PBPROJ'}} account at least
2971# Build account $pbac->{$ENV{'PBPROJ'}} in VM also needs to setup date and install deps.
2972# Nothing else should be needed
2973EOF
2974        foreach my $c (@sudocmds) {
2975            print SCRIPT "print PBOUT \"$pbac->{$ENV{'PBPROJ'}}   ALL = NOPASSWD: $c\n\";";
2976        }
2977    } elsif ($vtype =~ /^rm/) {
2978        my @sudocmds = pb_get_sudocmds($pbos,$ntpline);
2979        print SCRIPT << "EOF";
2980# Build account $pbac->{$ENV{'PBPROJ'}} in RM only needs to setup date and install deps if needed each time
2981EOF
2982        foreach my $c (@sudocmds) {
2983            print SCRIPT "print PBOUT \"$pbac->{$ENV{'PBPROJ'}}   ALL = NOPASSWD: $c\n\";";
2984        }
2985    } else {
2986        print SCRIPT << "EOF";
2987# Build account $pbac->{$ENV{'PBPROJ'}} for VE needs to do a lot in the host (and chroot), so allow without restriction for now
2988print PBOUT "$pbac->{$ENV{'PBPROJ'}}   ALL=(ALL) NOPASSWD:ALL\n";
2989EOF
2990}
2991    print SCRIPT << 'EOF';
2992close(PBOUT);
2993rename("$file.new",$file);
2994chmod 0440,$file;
2995
2996EOF
2997
2998    if ($vtype =~ /(v|r)m/) {
2999        # Sync date
3000        # do it after sudoers is setup
3001        print SCRIPT "pb_system(\"$ntpline\");\n";
3002    }
3003    # We may need a proxy configuration. Get it from the local env
3004
3005    if (defined $ENV{'http_proxy'}) {
3006        print SCRIPT "\$ENV\{'http_proxy'\}=\"$ENV{'http_proxy'}\";\n";
3007    }
3008
3009    if (defined $ENV{'ftp_proxy'}) {
3010        print SCRIPT "\$ENV\{'ftp_proxy'\}=\"$ENV{'ftp_proxy'}\";\n";
3011    }
3012
3013    print SCRIPT << 'EOF';
3014   
3015# Suse wants sudoers as 640
3016if ((($pbos->{'name'} eq "sles") && (($pbos->{'version'} =~ /10/) || ($pbos->{'version'} =~ /9/))) || (($pbos->{'name'} eq "opensuse") && ($pbos->{'version'} =~ /10.[012]/))) {
3017    chmod 0640,$file;
3018}
3019
3020# First install all required packages
3021pb_system("yum clean all","Cleaning yum env") if (($pbos->{'name'} eq "fedora") || ($pbos->{'name'} eq "asianux") || ($pbos->{'name'} eq "rhel"));
3022my ($ospkgdep) = pb_conf_get_if("ospkgdep");
3023   
3024my $pkgdep = pb_distro_get_param($pbos,$ospkgdep);
3025pb_distro_installdeps(undef,$pbos,pb_distro_only_deps_needed($pbos,join(' ',split(/,/,$pkgdep))));
3026
3027EOF
3028    my $itype = pb_distro_get_param($pbos,pb_conf_get("pbinstalltype"));
3029    # Install from sandbox mean a file base install
3030    $itype = "file" if (defined $sbx);
3031    if ($itype =~ /^file/) {
3032        my $cmdget;
3033        if (defined $sbx) {
3034            # Install from sandbox mean using the result of the just passed sbx2build command
3035            # Get content saved in cms2build
3036            my ($pkg) = pb_conf_read("$ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.pb","pbpkg");
3037            die "Unable to get package list" if (not defined $pkg);
3038
3039            # We consider 2 specific packages
3040            my $vertag1 = $pkg->{"ProjectBuilder"};
3041            my $vertag2 = $pkg->{"project-builder"};
3042            # get the version of the current package - maybe different
3043            my ($pbver1,$tmp1) = split(/-/,$vertag1);
3044            my ($pbver2,$tmp2) = split(/-/,$vertag2);
3045            # Copy inside the VE
3046            if ($vtype eq "ve") {
3047                my ($vepath) = pb_conf_get("vepath");
3048                copy("$ENV{'PBDESTDIR'}/ProjectBuilder-$pbver1.tar.gz","$vepath->{$ENV{'PBPROJ'}}/$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}/tmp");
3049                copy("$ENV{'PBDESTDIR'}/project-builder-$pbver2.tar.gz","$vepath->{$ENV{'PBPROJ'}}/$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}/tmp");
3050            } else {
3051                pb_system("scp -i $keyfile -p -o UserKnownHostsFile=/dev/null -P $nport $ENV{'PBDESTDIR'}/ProjectBuilder-$pbver1.tar.gz $ENV{'PBDESTDIR'}/project-builder-$pbver2.tar.gz root\@$vmhost->{$ENV{'PBPROJ'}}:/tmp","Copying local project files to $vtype.");
3052            }
3053            $cmdget = "mv /tmp/ProjectBuilder-$pbver1.tar.gz ProjectBuilder-latest.tar.gz ; mv /tmp/project-builder-$pbver2.tar.gz project-builder-latest.tar.gz";
3054        } else {
3055            $cmdget = "wget --passive-ftp ftp://ftp.project-builder.org/src/ProjectBuilder-latest.tar.gz; wget --passive-ftp ftp://ftp.project-builder.org/src/project-builder-latest.tar.gz";
3056        }
3057        print SCRIPT << 'EOF';
3058# Then install manually the missing perl modules
3059my ($osperldep,$osperlver) = pb_conf_get_if("osperldep","osperlver");
3060   
3061my $perldep = pb_distro_get_param($pbos,$osperldep);
3062foreach my $m (split(/,/,$perldep)) {
3063    # Skip empty deps
3064    next if ($m =~ /^\s*$/);
3065    my $dir = $m;
3066    $dir =~ s/-.*//;
3067    pb_system("echo \"rm -rf $m* ; wget http://search.cpan.org/CPAN/modules/by-module/$dir/$m-$osperlver->{$m}.tar.gz ; gzip -cd $m-$osperlver->{$m}.tar.gz | tar xf - ; cd $m* ; if [ -f Build.PL ]; then perl Build.PL; ./Build ; ./Build install ; else perl Makefile.PL; make ; make install ; fi; cd .. ; rm -rf $m*\" | bash" ,"Installing perl module $m-$osperlver->{$m}");
3068}
3069EOF
3070
3071        print SCRIPT << "EOF";
3072pb_system("rm -rf ProjectBuilder-* ; rm -rf project-builder-* ; $cmdget ; gzip -cd ProjectBuilder-latest.tar.gz | tar xf - ; cd ProjectBuilder-* ; perl Makefile.PL ; make ; make install ; cd .. ; rm -rf ProjectBuilder-* ; gzip -cd project-builder-latest.tar.gz | tar xf - ; cd project-builder-* ; perl Makefile.PL ; make ; make install ; cd .. ; rm -rf project-builder-* ;","Building Project-Builder");
3073EOF
3074    } elsif ($itype =~ /^pkg/) {
3075        # pkg based install. We need to point to the project-builder.org repository
3076        print SCRIPT << 'EOF';
3077my $pkgforpb = pb_distro_get_param($pbos,pb_conf_get_if("ospkg"));
3078pb_distro_setuposrepo($pbos);
3079pb_distro_installdeps(undef,$pbos,pb_distro_only_deps_needed($pbos,join(' ',split(/,/,$pkgforpb))));
3080EOF
3081    } else {
3082        # Unknown install type
3083        die("Unknown install type $itype->{$ENV{'PBPROJ'}} for param pbinstalltype");
3084    }
3085    print SCRIPT << 'EOF';
3086pb_system("pb 2>&1 | head -5",undef,"verbose");
3087pb_system("pbdistrocheck",undef,"verbose");
3088EOF
3089    if ($vtype eq "ve") {
3090            print SCRIPT << 'EOF';
3091# For VE we need to umount some FS at the end
3092
3093pb_system("umount /proc");
3094
3095# Create a basic network file if not already there
3096
3097my $nf="/etc/sysconfig/network";
3098if ((! -f $nf) && ($pbos->{'type'} eq "rpm")) {
3099    open(NF,"> $nf") || die "Unable to create $nf";
3100    print NF "NETWORKING=yes\n";
3101    print NF "HOSTNAME=localhost\n";
3102    close(NF);
3103}
3104chmod 0755,$nf;
3105EOF
3106    }
3107
3108    # Adds pb_distro_get_context and all functions needed from ProjectBuilder::Distribution, Conf and Base
3109    foreach my $d (@INC) {
3110        my @f = ("$d/ProjectBuilder/Base.pm","$d/ProjectBuilder/Distribution.pm","$d/ProjectBuilder/Conf.pm");
3111        foreach my $f (@f) {
3112            if (-f "$f") {
3113                open(PBD,"$f") || die "Unable to open $f";
3114                while (<PBD>) {
3115                    next if (/^package/);
3116                    next if (/^use Exporter/);
3117                    next if (/^use ProjectBuilder::/);
3118                    next if (/^our /);
3119                    print SCRIPT $_;
3120                }
3121                close(PBD);
3122            }
3123        }
3124    }
3125    # Use a fake pb_version_init version here
3126    print SCRIPT << "EOF";
3127sub pb_version_init {
3128
3129return("$projectbuilderver","$projectbuilderrev");
3130}
31311;
3132EOF
3133    close(SCRIPT);
3134    chmod 0755,"$pbscript";
3135
3136    # That build script needs to be run as root and force stop of VM at end
3137    $pbaccount = "root";
3138
3139    # Force shutdown of VM except if it was already launched
3140    my $pbforce = 0;
3141    if ((! $vmexist) && ($vtype eq "vm")) {
3142        $pbforce = 1;
3143    }
3144   
3145    pb_script2v($pbscript,$vtype,$pbforce,$v);
3146    $pm->finish if (defined $pbparallel);
3147}
3148$pm->wait_all_children if (defined $pbparallel);
3149return;
3150}
3151
3152# Function to create a snapshot named 'pb' for VMs and a compressed tar for VEs
3153sub pb_snap2v {
3154
3155my $vtype = shift;
3156
3157my ($vm,$all) = pb_get2v($vtype);
3158
3159# Script generated
3160my $pbscript = "$ENV{'PBDESTDIR'}/snapv";
3161
3162my ($pbac) = pb_conf_get($vtype."login");
3163
3164foreach my $v (@$vm) {
3165    if ($vtype eq "ve") {
3166        # Get distro context
3167        my $pbos = pb_distro_get_context($v);
3168        my ($vepath) = pb_conf_get("vepath");
3169
3170        # Test if an existing snapshot exists and remove it if there is a VE
3171        if ((-f "$vepath->{$ENV{'PBPROJ'}}/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}.tar.gz") &&
3172            (! -d "$vepath->{$ENV{'PBPROJ'}}/$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}")) {
3173                pb_system("sudo rm -f $vepath->{$ENV{'PBPROJ'}}/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}.tar.gz","Removing previous snapshot $pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}.tar.gz");
3174        }
3175    }
3176
3177    # Prepare the script to be executed on the VM/VE
3178    open(SCRIPT,"> $pbscript") || die "Unable to create $pbscript";
3179    print SCRIPT << 'EOF';
3180    #!/bin/bash
3181    sleep 2
3182EOF
3183    close(SCRIPT);
3184    chmod 0755,"$pbscript";
3185
3186    # Force shutdown of VM/VE
3187    # Force snapshot of VM/VE
3188    pb_script2v($pbscript,$vtype,1,$v,1);
3189}
3190return;
3191}
3192
3193# Function to update VMs/VEs/RMs with the latest distribution content
3194sub pb_update2v {
3195
3196my $vtype = shift;
3197
3198my ($vm,$all) = pb_get2v($vtype);
3199
3200# Script generated
3201my $pbscript = "$ENV{'PBDESTDIR'}/updatev";
3202
3203my ($pbac) = pb_conf_get($vtype."login");
3204
3205foreach my $v (@$vm) {
3206    # Get distro context
3207    my $pbos = pb_distro_get_context($v);
3208
3209    # Prepare the script to be executed on the VM/VE/RM
3210    # in $ENV{'PBDESTDIR'}/updatev
3211    open(SCRIPT,"> $pbscript") || die "Unable to create $pbscript";
3212   
3213    print SCRIPT << 'EOF';
3214    #!/bin/bash
3215    sleep 2
3216EOF
3217    # VE needs a good /proc
3218    if ($vtype eq "ve") {
3219        print SCRIPT "sudo /bin/mount -t proc /proc /proc\n";
3220    }
3221    print SCRIPT "$pbos->{'update'}\n";
3222    if ($vtype eq "ve") {
3223        print SCRIPT "sudo /bin/umount /proc\n";
3224    }
3225    close(SCRIPT);
3226    chmod 0755,"$pbscript";
3227
3228    # Force shutdown of VM except
3229    pb_script2v($pbscript,$vtype,1,$v);
3230}
3231return;
3232}
3233
3234sub pb_announce {
3235
3236    my $antype = shift;
3237
3238    # Get all required parameters
3239    my ($pbpackager,$pbrepo,$pbml,$pbsmtp) = pb_conf_get("pbpackager","pbrepo","pbml","pbsmtp");
3240    my ($pkgv, $pkgt, $testver) = pb_conf_get_if("pkgver","pkgtag","testver");
3241    if (((not defined $testver) || (not defined $testver->{$ENV{'PBPROJ'}}) || ($testver->{$ENV{'PBPROJ'}} !~ /true/i)) && ($antype eq "Clean")) {
3242        # We just clean for test versions
3243        pb_log(0,"Unable to clean SSH repository for non testver version\n");
3244        return;
3245    }
3246    my $pkg = pb_cms_get_pkg($defpkgdir,$extpkgdir);
3247    my @pkgs = @$pkg;
3248    my %pkgs;
3249    my $first = 0;
3250
3251    # Get all distros concerned
3252    my $pbos = pb_distro_get_context();
3253    my $distrolist = pb_get_distros($pbos,undef);
3254    my %dl;
3255    my %theorlist;
3256    my %archlist;
3257    foreach my $d (split(/,/,$distrolist)) {
3258        my ($d1,$d2,$d3) = split(/-/,$d);
3259        $dl{$d1}++;
3260    }
3261
3262    # Command to find packages on repo
3263    my $findstr = "find ".join(" ",keys %dl)." ";
3264    my $srcstr = "";
3265    # Generated announce files
3266    my @files;
3267
3268    foreach my $pbpkg (@pkgs) {
3269        if ($first != 0) {
3270            $findstr .= "-o ";
3271        }
3272        $first++;
3273        if ((defined $pkgv) && (defined $pkgv->{$pbpkg})) {
3274            $pbver = $pkgv->{$pbpkg};
3275        } else {
3276            $pbver = $ENV{'PBPROJVER'};
3277        }
3278        if ((defined $pkgt) && (defined $pkgt->{$pbpkg})) {
3279            $pbtag = $pkgt->{$pbpkg};
3280        } else {
3281            $pbtag = $ENV{'PBPROJTAG'};
3282        }
3283
3284        # TODO: use virtual/real names here now
3285        my $pbrealpkg = $pbpkg;
3286        my $pbrealpkgrpm = pb_cms_get_real_pkg($pbpkg,"rpm");
3287        my $pbrealpkgdeb = pb_cms_get_real_pkg($pbpkg,"deb");
3288        if ($antype eq "Clean") {
3289            $pbtag = "0.[0-9][0-9]*";
3290            $findstr .= "-name \'$pbrealpkgrpm-$pbver-$pbtag\.*.rpm\' -o -name \'$pbrealpkgrpm-debug-$pbver-$pbtag\.*.rpm\' -o -name \'$pbrealpkgdeb"."_$pbver-$pbtag"."_*\.deb\' -o -name \'$pbrealpkgdeb"."_$pbver-$pbtag.dsc\' -o -name \'$pbrealpkgdeb"."_$pbver-$pbtag.tar.gz\' -o -name \'$pbrealpkg-$pbver"."_p[0-9]*\.ebuild\' -o -name \'$pbrealpkg-$pbver-$pbtag*\.pkg\' -o -name \'$pbrealpkg-$pbver-$pbtag*\.sd\' ";
3291            $srcstr .= "src/$pbrealpkg-$pbver.tar.gz src/$pbrealpkg-$pbver.pbconf.tar.gz ";
3292        } else {
3293            $findstr .= "-name \'$pbrealpkgrpm-$pbver-$pbtag\.*.rpm\' -o -name \'$pbrealpkgdeb"."_$pbver*\.deb\' -o -name \'$pbrealpkg-$pbver*\.ebuild\' -o -name \'$pbrealpkg-$pbver*\.pkg\' -o -name \'$pbrealpkg-$pbver*\.sd\' ";
3294        }
3295
3296        if ($antype eq "Announce") {
3297            my $chglog;
3298
3299            pb_cms_init($pbinit);
3300            # Get project info on log file and generate tmp files used later on
3301            $chglog = "$ENV{'PBROOTDIR'}/$pbpkg/pbcl";
3302            $chglog = "$ENV{'PBROOTDIR'}/pbcl" if (! -f $chglog);
3303            $chglog = undef if (! -f $chglog);
3304
3305            open(OUT,"> $ENV{'PBTMP'}/$pbpkg.ann") || die "Unable to create $ENV{'PBTMP'}/$pbpkg.ann: $!";
3306            my $pb;
3307            $pb->{'realpkg'} = $pbrealpkg;
3308            $pb->{'ver'} = $pbver;
3309            $pb->{'tag'} = $pbtag;
3310            $pb->{'date'} = $pbdate;
3311            $pb->{'chglog'} = $chglog;
3312            $pb->{'packager'} = $pbpackager;
3313            $pb->{'proj'} = $ENV{'PBPROJ'};
3314            $pb->{'repo'} = $pbrepo;
3315            $pb->{'pbos'}->{'type'} = "announce";
3316            $pb->{'pbos'}->{'suffix'} = "none";
3317            pb_changelog($pb,\*OUT,"yes");
3318            close(OUT);
3319            push(@files,"$ENV{'PBTMP'}/$pbpkg.ann");
3320        } elsif ($antype eq "Check") {
3321            # For the check we also build the theoritical complete list we should get
3322            foreach my $d (split(/,/,$distrolist)) {
3323                $pbos = pb_distro_get_context($d);
3324                if ($pbos->{'type'} eq "rpm") {
3325                    $theorlist{"$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}/$pbrealpkgrpm-$pbver-$pbtag$pbos->{'suffix'}"} = 0;
3326                } elsif ($pbos->{'type'} eq "deb") {
3327                    $theorlist{"$pbos->{'name'}/$pbos->{'version'}/$pbrealpkgdeb"."_$pbver-$pbtag"} = 0;
3328                    $archlist{"$pbos->{'name'}/$pbos->{'version'}/$pbrealpkgdeb"."_$pbver-$pbtag"} = "$pbos->{'arch'}";
3329                } elsif ($pbos->{'type'} eq "ebuild") {
3330                    $theorlist{"$pbos->{'name'}/$pbos->{'version'}/$pbrealpkg-$pbver-r$pbtag.ebuild"} = 0;
3331                    $archlist{"$pbos->{'name'}/$pbos->{'version'}/$pbrealpkg-$pbver-r$pbtag.ebuild"} = "$pbos->{'arch'}";
3332                } elsif ($pbos->{'type'} eq "pkg") {
3333                    $theorlist{"$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}/$pbrealpkg-$pbver-$pbtag.pkg"} = 0;
3334                } else {
3335                    pb_log(1,"No theoritical list possible for type $pbos->{'type'}\n");
3336                }
3337            }
3338        }
3339        pb_log(2,"theorlist : ".Dumper(%theorlist)."\n");
3340    }
3341    if ($antype eq "Announce") {
3342        $findstr .= " | grep -Ev \'src.rpm\'";
3343    } elsif ($antype eq "Clean") {
3344        $findstr .= " | xargs rm -f -v $srcstr ";
3345    }
3346
3347    # Prepare the command to run and execute it
3348    open(PBS,"> $ENV{'PBTMP'}/pbscript") || die "Unable to create $ENV{'PBTMP'}/pbscript";
3349    print PBS "#!/bin/bash\n";
3350    print PBS "set -x\n" if ($pbdebug gt 1);
3351    print PBS "$findstr | sort 2> /dev/null\n";
3352    close(PBS);
3353    chmod 0755,"$ENV{'PBTMP'}/pbscript";
3354    pb_send2target("Announce");
3355
3356    my $sl = "Project $ENV{'PBPROJ'} version $ENV{'PBPROJVER'} is now available";
3357    if ($antype eq "Announce") {
3358        # Get subject line
3359        pb_log(0,"Please enter the title of your announce\n");
3360        pb_log(0,"(By default: $sl)\n");
3361        my $sl2 = <STDIN>;
3362        $sl = $sl2 if ($sl2 !~ /^$/);
3363
3364        # Prepare a template of announce
3365        open(ANN,"> $ENV{'PBTMP'}/announce.html") || die "Unable to create $ENV{'PBTMP'}/announce.html: $!";
3366        print ANN << "EOF";
3367$sl</p>
3368
3369<p>The project team is happy to announce the availability of a newest version of $ENV{'PBPROJ'} $ENV{'PBPROJVER'}. Enjoy it as usual!</p>
3370<p>
3371Now available at <a href="$pbrepo->{$ENV{'PBPROJ'}}">$pbrepo->{$ENV{'PBPROJ'}}</a>
3372</p>
3373<p>
3374EOF
3375    }
3376
3377    open(LOG,"$ENV{'PBTMP'}/system.$$.log") || die "Unable to read $ENV{'PBTMP'}/system.$$.log: $!";
3378    if ($antype eq "Announce") {
3379        my $col = 2;
3380        my $i = 1;
3381        print ANN << 'EOF';
3382<TABLE WIDTH="700" CELLPADDING="0" CELLSPACING="0" BORDER="0">
3383<TR>
3384EOF
3385        while (<LOG>) {
3386            print ANN "<TD><A HREF=\"$pbrepo->{$ENV{'PBPROJ'}}/$_\">$_</A></TD>";
3387            $i++;
3388            if ($i > $col) {
3389                print ANN "</TR>\n<TR>";
3390                $i = 1;
3391            }
3392        }
3393    } elsif ($antype eq "Clean") {
3394        while (<LOG>) {
3395            # skip errors
3396            next if ($_ !~ /^removed /);
3397            pb_log(0,"$_");
3398        }
3399    } else {
3400        # In Check mode we need to compare the 2 lists (real and theoritical)
3401        while (<LOG>) {
3402            # Get package name and remove what is in extra for the theoritical list (arch at the end)
3403            chomp();
3404            # skip find errors
3405            next if (/^find:/);
3406            my $p = $_;
3407            $p =~ s/\.(i[3456]86|x86_64|noarch|src)\.rpm$//;
3408            $p =~ s/_(i[3456]86|amd64|all).deb$//;
3409            $theorlist{$p} = -2 if (not defined $theorlist{$p});
3410            $theorlist{$p} = $theorlist{$p} + 1;
3411        }
3412        pb_log(2,"theorlist : ".Dumper(%theorlist)."\n");
3413    }
3414    close(LOG);
3415
3416    # Nothing more for the cleanssh case
3417    return if ($antype eq "Clean");
3418
3419    if ($antype eq "Check") {
3420        my ($chkex) = pb_conf_get_if("checkexclude");
3421        my $vmbuildlist = "";
3422        my $vebuildlist = "";
3423        my $rmbuildlist = "";
3424        my @pt = pb_conf_get_if("vmlist","velist","rmlist");
3425        foreach my $t (sort keys %theorlist) {
3426            if (defined $theorlist{$t} and $theorlist{$t} >= 1) {
3427                pb_log(1,"Packages found for $t\n");
3428            } elsif (defined $theorlist{$t} and $theorlist{$t} < 0) {
3429                pb_log(0,"Extra Package found for $t\n");
3430            } else {
3431                my ($os,$ver,$arch,$package) = split(/\//,$t);
3432                # Some distro have no arch subdir
3433                if (not defined $package) {
3434                    $package = $arch;
3435                    # TODO: If both arch have failed, we just make the last one
3436                    $arch = $archlist{$t};
3437                }
3438                my $pbos = pb_distro_get_context("$os-$ver-$arch");
3439                my $pkgn = $package;
3440                if ($pbos->{'type'} ne "deb") {
3441                    # package name is more easily found from the end for non deb
3442                    # as '-' is the separator, but it can also be used in names
3443                    $pkgn = reverse($package);
3444                    # search the second '-' and isolate the now last part which is the full name
3445                    $pkgn =~ s/([^-]+)-([^-]+)-([\S])+$/$3/;
3446                } else {
3447                    $pkgn =~ s/([^_]+)_([\S])+$/$2/;
3448                }
3449                my $found = 0;
3450                # Handle the exclusion of OSes
3451                my $excl = "";
3452                $excl .= $chkex->{$pkgn} if (defined $chkex->{$pkgn});
3453                $excl .= $chkex->{"all"} if (defined $chkex->{"all"});
3454                foreach my $ex (split(/,/,$excl)) {
3455                    $found = 1 if ("$os-$ver-$arch" =~ /^$ex/);
3456                }
3457                # Skip as excluded
3458                next if ($found == 1);
3459                pb_log(0,"Package NOT found for $t\n");
3460                # Avoid duplicates in list
3461                next if ($vmbuildlist =~ /$os-$ver-$arch/);
3462                next if ($vebuildlist =~ /$os-$ver-$arch/);
3463                next if ($rmbuildlist =~ /$os-$ver-$arch/);
3464                # check with which method we need to build
3465                if ((defined $pt[0]->{$ENV{'PBPROJ'}}) and ($pt[0]->{$ENV{'PBPROJ'}} =~ /$os-$ver-$arch/)) {
3466                    $vmbuildlist = "$os-$ver-$arch" if ($vmbuildlist eq "");
3467                    $vmbuildlist .= ",$os-$ver-$arch" if ($vmbuildlist !~ /$os-$ver-$arch/);
3468                    next;
3469                }
3470                if ((defined $pt[1]->{$ENV{'PBPROJ'}}) and ($pt[1]->{$ENV{'PBPROJ'}} =~ /$os-$ver-$arch/)) {
3471                    $vebuildlist = "$os-$ver-$arch" if ($vebuildlist eq "");
3472                    $vebuildlist .= ",$os-$ver-$arch" if ($vebuildlist !~ /$os-$ver-$arch/);
3473                    next;
3474                }
3475                if ((defined $pt[2]->{$ENV{'PBPROJ'}}) and ($pt[2]->{$ENV{'PBPROJ'}} =~ /$os-$ver-$arch/)) {
3476                    $rmbuildlist = "$os-$ver-$arch" if ($rmbuildlist eq "");
3477                    $rmbuildlist .= ",$os-$ver-$arch" if ($rmbuildlist !~ /$os-$ver-$arch/);
3478                }
3479            }
3480        }
3481        # If we want to rebuild automatically, let's do it
3482        if (defined $opts{'rebuild'}) {
3483            # SandBox or CMS
3484            pb_log(0,"Rebuilding from SandBox\n");
3485            pb_log(0,"for VMs: $vmbuildlist\n") if ($vmbuildlist ne "");
3486            pb_log(0,"for VEs: $vebuildlist\n") if ($vebuildlist ne "");
3487            pb_log(0,"for RMs: $rmbuildlist\n") if ($rmbuildlist ne "");
3488            pb_cms2build("SandBox");
3489            # Which mode
3490            $ENV{'PBV'} = $vmbuildlist;
3491            pb_build2v("vm","build") if ($vmbuildlist ne "");
3492            $ENV{'PBV'} = $vebuildlist;
3493            pb_build2v("ve","build") if ($vebuildlist ne "");
3494            $ENV{'PBV'} = $rmbuildlist;
3495            pb_build2v("rm","build") if ($rmbuildlist ne "");
3496        }
3497        # For the check part this is now finished
3498        return;
3499    }
3500
3501    print ANN << "EOF";
3502</TR>
3503</TABLE>
3504</p>
3505
3506<p>As usual source packages are also available in the same directory.</p>
3507
3508<p>
3509Changes are :
3510</p>
3511<p>
3512EOF
3513    # Get each package changelog content
3514    foreach my $f (sort(@files)) {
3515        open(IN,"$f") || die "Unable to read $f:$!";
3516        while (<IN>) {
3517            print ANN $_;
3518        }
3519        close(IN);
3520        print ANN "</p><p>\n";
3521    }
3522    print ANN "</p>\n";
3523    close(ANN);
3524
3525    # Allow for modification
3526    my $editor = "vi";
3527    $editor = $ENV{'EDITOR'} if (defined $ENV{'EDITOR'});
3528    pb_system("$editor $ENV{'PBTMP'}/announce.html","Allowing modification of the announce","noredir");
3529
3530    # Store it in DB for external usage (Web pages generation)
3531    my $db = "$ENV{'PBCONFDIR'}/announces3.sql";
3532
3533    my $precmd = "";
3534    if (! -f $db) {
3535        $precmd = "CREATE TABLE announces (id INTEGER PRIMARY KEY AUTOINCREMENT, date DATE, announce VARCHAR[65535])";
3536    }
3537
3538    my $dbh = DBI->connect("dbi:SQLite:dbname=$db","","",
3539                        { RaiseError => 1, AutoCommit => 1 })
3540                        || die "Unable to connect to $db";
3541
3542    if ($precmd ne "") {
3543        my $sth = $dbh->prepare(qq{$precmd})
3544                    || die "Unable to create table into $db";
3545        $sth->execute();
3546    }
3547
3548    # To read whole file
3549    local $/;
3550    open(ANN,"$ENV{'PBTMP'}/announce.html") || die "Unable to read $ENV{'PBTMP'}/announce.html: $!";
3551    my $announce = <ANN>;
3552    close(ANN);
3553   
3554    pb_log(2,"INSERT INTO announces VALUES (NULL, $pbdate, $announce)");
3555    my $sth = $dbh->prepare(qq{INSERT INTO announces VALUES (NULL,?,?)})
3556                    || die "Unable to insert into $db";
3557    $sth->execute($pbdate, $announce);
3558    $sth->finish();
3559    $dbh->disconnect;
3560
3561    # Then deliver it on the Web
3562    # $TOOLHOME/livwww www
3563
3564    # Mail it to project's ML
3565    open(ML,"| w3m -dump -T text/html > $ENV{'PBTMP'}/announce.txt") || die "Unable to create $ENV{'PBTMP'}/announce.txt: $!";
3566    print ML << 'EOF';
3567<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/x html1/DTD/xhtml1-strict.dtd">
3568
3569<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" xml:lang="en" lang="en">
3570  <head>
3571  </head>
3572  <body>
3573  <p>
3574EOF
3575    open(ANN,"$ENV{'PBTMP'}/announce.html") || die "Unable to read $ENV{'PBTMP'}/announce.html: $!";
3576    while(<ANN>) {
3577        print ML $_;
3578    }
3579    print ML << 'EOF';
3580</body>
3581</html>
3582EOF
3583    close(ML);
3584
3585    # To read whole file
3586    local $/;
3587    open(ANN,"$ENV{'PBTMP'}/announce.txt") || die "Unable to read $ENV{'PBTMP'}/announce.txt: $!";
3588    my $msg = <ANN>;
3589    close(ANN);
3590   
3591    # Preparation of headers
3592    eval
3593    {
3594        require Mail::Sendmail;
3595        Mail::Sendmail->import();
3596    };
3597    if ($@) {
3598        # Mail::Sendmail not found not sending mail !
3599        pb_log(0,"No Mail::Sendmail module found so not sending any mail !\n");
3600    } else {
3601        my %mail = (   
3602            To          =>  $pbml->{$ENV{'PBPROJ'}},
3603            From        =>  $pbpackager->{$ENV{'PBPROJ'}},
3604            Smtp        =>  $pbsmtp->{$ENV{'PBPROJ'}},
3605            Body        =>  $msg,
3606            Subject     =>  "[ANNOUNCE] $sl",
3607        );
3608           
3609        # Send mail
3610        if (! sendmail(%mail)) {
3611            if ((defined $Mail::Sendmail::error) and (defined $Mail::Sendmail::log)) {
3612                die "Unable to send mail ($Mail::Sendmail::error): $Mail::Sendmail::log";
3613            }
3614        }
3615    }
3616}
3617
3618#
3619# Creates a set of HTML file containing the news for the project
3620# based on what has been generated by the pb_announce function
3621#
3622sub pb_web_news2html {
3623
3624    my $dest = shift || $ENV{'PBTMP'};
3625
3626    # Get all required parameters
3627    my ($pkgv, $pkgt) = pb_conf_get_if("pkgver","pkgtag");
3628
3629    # DB of announces for external usage (Web pages generation)
3630    my $db = "$ENV{'PBCONFDIR'}/announces3.sql";
3631
3632    my $dbh = DBI->connect("dbi:SQLite:dbname=$db","","",
3633                        { RaiseError => 1, AutoCommit => 1 })
3634                        || die "Unable to connect to $db";
3635    # For date handling
3636    $ENV{LANGUAGE}="C";
3637    my $firstjan = strftime("%Y-%m-%d", 0, 0, 0, 1, 0, localtime->year(), 0, 0, -1);
3638    my $oldfirst = strftime("%Y-%m-%d", 0, 0, 0, 1, 0, localtime->year()-1, 0, 0, -1);
3639    pb_log(2,"firstjan: $firstjan, oldfirst: $oldfirst, pbdate:$pbdate\n");
3640    my $all = $dbh->selectall_arrayref("SELECT id,date,announce FROM announces ORDER BY date DESC");
3641    my %news;
3642    $news{"cy"} = "";   # current year's news
3643    $news{"ly"} = "";   # last year news
3644    $news{"py"} = "";   # previous years news
3645    $news{"fp"} = "";   # first page news
3646    my $cpt = 4;        # how many news for first page
3647    # Extract info from DB
3648    foreach my $row (@$all) {
3649        my ($id, $date, $announce) = @$row;
3650        $news{"cy"} = $news{"cy"}."<p><B>$date</B> $announce\n" if ((($date cmp $pbdate) le 0) && (($firstjan cmp $date) le 0));
3651        $news{"ly"} = $news{"ly"}."<p><B>$date</B> $announce\n" if ((($date cmp $firstjan) le 0) && (($oldfirst cmp $date) le 0));
3652        $news{"py"} = $news{"py"}."<p><B>$date</B> $announce\n" if (($date cmp $oldfirst) le 0);
3653        $news{"fp"} = $news{"fp"}."<p><B>$date</B> $announce\n" if ($cpt > 0);
3654        $cpt--;
3655    }
3656    pb_log(1,"news{fp}: ".$news{"fp"}."\n");
3657    $dbh->disconnect;
3658
3659    # Generate the HTML content
3660    foreach my $pref (keys %news) {
3661        open(NEWS,"> $dest/pb_web_$pref"."news.html") || die "Unable to create $dest/pb_web_$pref"."news.html: $!";
3662        print NEWS "$news{$pref}";
3663        close(NEWS);
3664    }
3665}
3666
3667
3668# Return the SSH key file to use
3669# Potentially create it if needed
3670
3671sub pb_ssh_get {
3672
3673my $create = shift || 0;    # Do not create keys by default
3674
3675# Check the SSH environment
3676my $keyfile = undef;
3677
3678# We have specific keys by default
3679$keyfile = "$ENV{'HOME'}/.ssh/pb_dsa";
3680if (!(-e $keyfile) && ($create eq 1)) {
3681    pb_system("ssh-keygen -q -b 1024 -N '' -f $keyfile -t dsa","Generating SSH keys for pb");
3682}
3683
3684$keyfile = "$ENV{'HOME'}/.ssh/id_rsa" if (-s "$ENV{'HOME'}/.ssh/id_rsa");
3685$keyfile = "$ENV{'HOME'}/.ssh/id_dsa" if (-s "$ENV{'HOME'}/.ssh/id_dsa");
3686$keyfile = "$ENV{'HOME'}/.ssh/pb_dsa" if (-s "$ENV{'HOME'}/.ssh/pb_dsa");
3687die "Unable to find your public ssh key under $keyfile" if (not defined $keyfile);
3688return($keyfile);
3689}
3690
3691
3692# Returns the pid of a running VM command using a specific VM file
3693sub pb_check_ps {
3694    my $vmcmd = shift;
3695    my $vmm = shift;
3696    my $vmexist = 0;        # FALSE by default
3697
3698    open(PS, "ps auxhww|") || die "Unable to call ps";
3699    while (<PS>) {
3700        next if (! /$vmcmd/);
3701        next if (! /$vmm/);
3702        my ($void1, $void2);
3703        ($void1, $vmexist, $void2) = split(/ +/);
3704        last;
3705    }
3706    return($vmexist);
3707}
3708
3709
3710sub pb_extract_build_files {
3711
3712my $src=shift;
3713my $dir=shift;
3714my $ddir=shift;
3715my $mandatory=shift || "spec";
3716my @files;
3717
3718my $flag = "mayfail" if (($mandatory eq "patch") || ($mandatory eq "src"));
3719my $res;
3720
3721if ($src =~ /tar\.gz$/) {
3722    $res = pb_system("tar xfpz $src $dir","Extracting $mandatory files from $src",$flag);
3723} elsif ($src =~ /tar\.bz2$/) {
3724    $res = pb_system("tar xfpj $src $dir","Extracting $mandatory files from $src",$flag);
3725} else {
3726    die "Unknown compression algorithm for $src";
3727}
3728# If not mandatory return now
3729return() if (($res != 0) and (($mandatory eq "patch") || ($mandatory eq "src")));
3730opendir(DIR,"$dir") || die "Unable to open directory $dir";
3731foreach my $f (readdir(DIR)) {
3732    next if ($f =~ /^\./);
3733    # Skip potential patch dir
3734    next if ($f =~ /^pbpatch/);
3735    # Skip potential source dir
3736    next if ($f =~ /^pbsrc/);
3737    move("$dir/$f","$ddir") || die "Unable to move $dir/$f to $ddir";
3738    pb_log(2,"mv $dir/$f $ddir\n");
3739    push @files,"$ddir/$f";
3740}
3741closedir(DIR);
3742# Not enough but still a first cleanup
3743pb_rm_rf("$dir");
3744return(@files);
3745}
3746
3747sub pb_list_bfiles {
3748
3749my $dir = shift;
3750my $pbpkg = shift;
3751my $bfiles = shift;
3752my $pkgfiles = shift;
3753my $supfiles = shift;
3754# subdir to keep if recursive mode, empty by default
3755my $subdir = shift || "";
3756# In a recursive function , we need a local var as DIR handle
3757my $bdir;
3758
3759pb_log(2,"DEBUG: entering pb_list_bfiles in $dir: ".Dumper($bfiles)."\n");
3760opendir($bdir,"$dir") || die "Unable to open dir $dir: $!";
3761foreach my $f (readdir($bdir)) {
3762    pb_log(3,"DEBUG: pb_list_bfiles found $f\n");
3763    next if ($f =~ /^\./);
3764    if (-d "$dir/$f") {
3765        # Recurse for directories (Debian 3.0 format e.g.)
3766        pb_log(2,"DEBUG: pb_list_bfiles recurse in $dir/$f\n");
3767        pb_list_bfiles("$dir/$f",$pbpkg,$bfiles,$pkgfiles,$supfiles,$f);
3768        next;
3769    }
3770
3771    my $key = $f;
3772    # if recursive then store also the subdir
3773    $key = "$subdir/$f" if ($subdir ne "");
3774    $bfiles->{$key} = "$dir/$f";
3775    $bfiles->{$key} =~ s~$ENV{'PBROOTDIR'}~~;
3776    if (defined $supfiles->{$pbpkg}) {
3777        $pkgfiles->{$key} = "$dir/$f" if ($f =~ /$supfiles->{$pbpkg}/);
3778    }
3779}
3780closedir($bdir);
3781pb_log(2,"DEBUG: exiting pb_list_bfiles: ".Dumper($bfiles)."\n");
3782}
3783
3784sub pb_add_coma {
3785
3786my $str = shift;
3787my $addstr = shift;
3788
3789$str .= "," if (defined $str);
3790$str .= $addstr;
3791return($str);
3792}
3793
3794sub pb_list_sfiles {
3795
3796my $sdir = shift;
3797my $ptr = shift;
3798my $pbos = shift;
3799my $extdir = shift;
3800
3801pb_log(2,"DEBUG: entering pb_list_sfiles: ".Dumper($ptr)."\n");
3802my $key = "$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}";
3803
3804# Prepare local sources for this distro - They are always applied first - May be a problem one day
3805# This function works for both patches and additional sources
3806foreach my $p (sort(<$sdir/*>)) {
3807    $ptr->{$key} = pb_add_coma($ptr->{$key},"file://$p") if (($p =~ /\.all$/) || ($p =~ /\.$pbos->{'os'}$/) || ($p =~ /\.$pbos->{'type'}$/) || ($p =~ /\.$pbos->{'family'}$/) || ($p =~ /\.$pbos->{'name'}$/) || ($p =~ /\.$pbos->{'name'}-$pbos->{'version'}$/) ||($p =~ /\.$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}$/));
3808}
3809
3810# Prepare also remote sources to be included - Applied after the local ones
3811foreach my $p ("all","$pbos->{'os'}","$pbos->{'type'}","$pbos->{'family'}","$pbos->{'name'}","$pbos->{'name'}-$pbos->{'version'}","$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}") {
3812    my $f = "$extdir.".".$p";
3813    next if (not -f $f);
3814    if (not open(PATCH,$f)) {
3815        pb_display("Unable to open existing external source file content $f\n");
3816        next;
3817    }
3818    while (<PATCH>) {
3819        chomp();
3820        $ptr->{$key} = pb_add_coma($ptr->{$key},"$_");
3821    }
3822    close(PATCH);
3823}
3824pb_log(2,"DEBUG: exiting pb_list_sfiles: ".Dumper($ptr)."\n");
3825return($ptr);
3826}
3827   
3828#
3829# Return the list of packages we are working on in a non CMS action
3830#
3831sub pb_get_pkg {
3832
3833my @pkgs = ();
3834
3835my ($var) = pb_conf_read("$ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.pb","pbpkg");
3836@pkgs = keys %$var;
3837
3838pb_log(0,"Packages: ".join(',',@pkgs)."\n");
3839return(\@pkgs);
3840}
3841
3842# Manages VM/RM SSH port communication
3843sub pb_get_port {
3844
3845my $port = shift;
3846my $pbos = shift;
3847my $cmt = shift;
3848my $nport;
3849
3850die "No port passed in parameter. Report to dev team\n" if (not defined $port);
3851# key is project on VM, but machine tuple for RM
3852if ($cmt =~ /^RM/i) {
3853    $nport = $port->{"$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}"};
3854} else {
3855    $nport = $port->{$ENV{'PBPROJ'}};
3856}
3857pb_log(2,"pb_get_port with $nport\n");
3858# Maybe a port was given as parameter so overwrite
3859$nport = "$pbport" if (defined $pbport);
3860# Maybe in // mode so use the env var set up as an offset to the base port, except when called from send2target for Packages or for RM
3861if (($cmt ne "Packages") && ($cmt !~ /^RM/i)) {
3862    $nport += $ENV{'PBVMPORT'} if ((defined $pbparallel) && (defined $ENV{'PBVMPORT'}));
3863}
3864pb_log(2,"pb_get_port returns $nport\n");
3865return($nport);
3866}
3867
3868sub pb_set_port { 
3869       
3870my ($pid,$ident) = @_;
3871pb_log(2,"pb_set_port for VM ($pid), id $ident\n");
3872$ENV{'PBVMPORT'} = $ident;
3873pb_log(2,"pb_set_port sets PBVMPORT in env to $ENV{'PBVMPORT'}\n");
3874}
3875
3876sub pb_set_parallel {
3877
3878my $vtype = shift;
3879
3880pb_log(2,"pb_set_parallel vtype: $vtype\n");
3881# Take care of memory size if VM, parallel mode and more than 1 action
3882if ((defined $pbparallel) && ($pbparallel ne 1) && ($vtype eq "vm")) {
3883    eval
3884    {
3885        require Linux::SysInfo;
3886        Linux::SysInfo->import();
3887    };
3888    if ($@) {
3889        # Linux::SysInfo not found
3890        pb_log(1,"ADVISE: Install Linux::SysInfo to benefit from automatic parallelism optimization.\nOr optimize manually pbparallel in your pb.conf file\nUsing $pbparallel processes max at a time for the moment\nWARNING: This may consume too much memory for your system\n");
3891    } else {
3892        # Using the memory size
3893        my $si = Linux::SysInfo::sysinfo();
3894        if (not defined $si) {
3895            pb_log(1,"ADVISE: Install Linux::SysInfo to benefit from automatic parallelism optimization.\nOr optimize manually pbparallel in your pb.conf file\nUsing $pbparallel processes max at a time for the moment\nWARNING: This may consume too much memory for your system\n");
3896        } else {
3897            # Keep the number of VM whose memory can be allocated
3898            my $ram = $si->{"totalram"}-$si->{"sharedram"}-$si->{"bufferram"};
3899            my $ram2;
3900            my ($vmmem) = pb_conf_get_if("vmmem");
3901
3902            my $v = "default";
3903            if ((defined $vmmem) and (defined $vmmem->{$v})) {
3904                $ram2 = $vmmem->{$v};
3905            } else {
3906                # Default for KVM/QEMU
3907                $ram2 = 128;
3908            }
3909            $pbparallel = sprintf("%d",$ram/$ram2);
3910        }
3911        pb_log(1,"Using $pbparallel processes at a time\n");
3912    }
3913}
3914pb_log(2,"pb_set_parallel returns: $pbparallel\n") if (defined $pbparallel);
3915return($pbparallel);
3916}
3917
3918sub pb_get_sudocmds { 
3919       
3920my $pbos = shift;
3921my %sudocmds;
3922
3923pb_log(2,"pb_get_sudocmds entering with lines:".Dumper(@_)."\n");
3924foreach my $c (split(/;/,$pbos->{'update'}),split(/;/,$pbos->{'install'}),@_) {
3925    pb_log(2,"pb_get_sudocmds analyses $c\n");
3926    next if ($c !~ /^\s*sudo/);
3927    # remove sudo and leading spaces
3928    $c =~ s/^\s*sudo\s+//;
3929    # keep only the command, not the params
3930    $c =~ s/([^\s]+)\s.*$/$1/;
3931    $sudocmds{$c} = "";
3932}
3933pb_log(2,"pb_get_sudocmds returns ".Dumper(keys %sudocmds)."\n");
3934return(keys %sudocmds);
3935}
3936
3937sub pb_sign_pkgs {
3938
3939my $pbos = shift;
3940my $made = shift;
3941
3942pb_log(2,"entering pb_sign_pkg: $made ".Dumper($pbos)."\n");
3943my ($passfile, $passphrase, $passpath) = pb_conf_get_if("pbpassfile","pbpassphrase","pbpasspath");
3944$ENV{'PBPASSPHRASE'} = $passphrase->{$ENV{'PBPROJ'}} if ((not defined $ENV{'PBPASSPHRASE'}) && (defined $passphrase->{$ENV{'PBPROJ'}}));
3945$ENV{'PBPASSFILE'} = $passfile->{$ENV{'PBPROJ'}} if ((not defined $ENV{'PBPASSFILE'})&& (defined $passfile->{$ENV{'PBPROJ'}})) ;
3946$ENV{'PBPASSPATH'} = $passpath->{$ENV{'PBPROJ'}} if ((not defined $ENV{'PBPASSPATH'})&& (defined $passpath->{$ENV{'PBPROJ'}})) ;
3947
3948# Remove extra spaces
3949$made =~ s/\s+/ /g;
3950$made =~ s/^\s//g;
3951$made =~ s/\s$//g;
3952
3953if ($pbos->{'type'} eq "rpm") {
3954    eval
3955    {
3956        require RPM4::Sign;
3957        RPM4::Sign->import();
3958    };
3959    if ($@) {
3960        # RPM4::Sign not found
3961        pb_log(1,"WARNING: Install RPM4::Sign to benefit from automatic package signing.\n");
3962    } else {
3963        return if ((not defined $ENV{'PBPASSPHRASE'}) and (not defined $ENV{'PBPASSFILE'}));
3964        my $sign = RPM4::Sign->new(
3965            passphrase => $ENV{'PBPASSPHRASE'},
3966            name => $ENV{'PBPACKAGER'},
3967            path => $ENV{'PBPASSPATH'},
3968            password_file => $ENV{'PBPASSFILE'}, 
3969        );
3970
3971        pb_log(0,"Signing RPM packages...\n");
3972        pb_log(2,"pb_sign_pkg: pkgs:".Dumper(split(/ /,$made))."\n");
3973        $sign->rpmssign(split(/ /,$made));
3974    }
3975} elsif ($pbos->{'type'} eq "deb") {
3976    my $changes = "";
3977    foreach my $c (split(/ /,$made)) {
3978        $changes .= " $ENV{'PBBUILDDIR'}/$c" if ($c =~ /\.changes$/);
3979    }
3980    my $debsigncmd = pb_check_req("debsign",1);
3981    pb_system("$debsigncmd -m\'$ENV{'PBPACKAGER'}\' $changes","Signing DEB packages");
3982} else {
3983    pb_log(0,"I don't know yet how to sign packages for type $pbos->{'type'}.\nPlease give feedback to dev team\n");
3984}
3985pb_log(2,"exiting pb_sign_pkg\n");
3986}
3987
3988# return list of all distributins supported, coma separated
3989sub pb_get_distros {
3990
3991my $pbos = shift;
3992my $pbtarget = shift;
3993
3994my $tmpl = "$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'},";
3995
3996# Get list of distributions for which we need to generate build files if no target
3997if (not defined $pbtarget) {
3998    my @pt = pb_conf_get_if("vmlist","velist","rmlist");
3999    if (defined $pt[0]->{$ENV{'PBPROJ'}}) {
4000        $tmpl .= $pt[0]->{$ENV{'PBPROJ'}};
4001    }
4002    if (defined $pt[1]->{$ENV{'PBPROJ'}}) {
4003        # The 2 lists need to be grouped with a ',' separating them
4004        if ($tmpl ne "") {
4005            $tmpl .= ",";
4006        }
4007        $tmpl .= $pt[1]->{$ENV{'PBPROJ'}} 
4008    }
4009    if (defined $pt[2]->{$ENV{'PBPROJ'}}) {
4010        # The lists needs to be grouped with a ',' separating them
4011        if ($tmpl ne "") {
4012            $tmpl .= ",";
4013        }
4014    $tmpl .= $pt[2]->{$ENV{'PBPROJ'}} 
4015    }
4016}
4017return($tmpl);
4018}   
4019
40201;
Note: See TracBrowser for help on using the repository browser.