source: devel/pb/bin/pb @ 1420

Last change on this file since 1420 was 1420, checked in by bruno, 8 years ago
  • Fix 2 bugs in newver with automatic change of version and delivery check to be done.
  • Property svn:executable set to *
File size: 131.6 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
1818(cd repodata ; ln -sf ../$ENV{'PBPROJ'}.pubkey 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            my $txt = $_;
2633            chomp($txt);
2634            pb_log(0,"Please check delivery ($txt) in $ENV{'PBCONFDIR'}/$newver/$ENV{'PBPROJ'}.pb\n");
2635        }
2636        print OUT $_;
2637    }
2638    close(FILE);
2639    close(OUT);
2640    rename("$ENV{'PBCONFDIR'}/$newver/$ENV{'PBPROJ'}.pb.new","$ENV{'PBCONFDIR'}/$newver/$ENV{'PBPROJ'}.pb");
2641
2642    # Checking pbcl files
2643    foreach my $f (<$ENV{'PBROOTDIR'}/*/pbcl>) {
2644        # Compute new pbcl file
2645        my $f2 = $f;
2646        $f2 =~ s|$ENV{'PBROOTDIR'}|$ENV{'PBCONFDIR'}/$newver/|;
2647        open(PBCL,$f) || die "Unable to open $f";
2648        my $foundnew = 0;
2649        while (<PBCL>) {
2650            $foundnew = 1 if (/^$newvertxt \(/);
2651        }
2652        close(PBCL);
2653        open(OUT,"> $f2") || die "Unable to write to $f2: $!";
2654        open(PBCL,$f) || die "Unable to open $f";
2655        while (<PBCL>) {
2656            print OUT "$_" if (not /^$oldvertxt \(/);
2657            if ((/^$oldvertxt \(/) && ($foundnew == 0)) {
2658                print OUT "$newvertxt ($pbdate)\n";
2659                print OUT "- TBD\n";
2660                print OUT "\n";
2661                pb_log(0,"WARNING: version $newvertxt not found in $f so added to $f2...\n") if ($foundnew == 0);
2662            }
2663        }
2664        close(OUT);
2665        close(PBCL);
2666    }
2667
2668    pb_log(2,"Checkin $ENV{'PBCONFDIR'}/$newver\n");
2669    pb_cms_checkin($scheme,"$ENV{'PBCONFDIR'}/$newver",undef);
2670}
2671
2672#
2673# Return the list of VMs/VEs/RMs we are working on
2674# $all is a flag to know if we return all of them
2675# or only some (if all we publish also tar files in addition to pkgs
2676#
2677sub pb_get2v {
2678
2679my $vtype = shift;
2680my @v;
2681my $all = 0;
2682my $pbv = 'PBV';
2683my $vlist = $vtype."list";
2684
2685# Get VM/VE list
2686if ((not defined $ENV{$pbv}) || ($ENV{$pbv} =~ /^all$/)) {
2687    my ($ptr) = pb_conf_get($vlist);
2688    $ENV{$pbv} = $ptr->{$ENV{'PBPROJ'}};
2689    $all = 1;
2690}
2691pb_log(2,"$vtype: $ENV{$pbv}\n");
2692@v = split(/,/,$ENV{$pbv});
2693return(\@v,$all);
2694}
2695
2696# Function to create a potentialy missing pb account on the VM/VE/RM, and adds it to sudo
2697# Needs to use root account to connect to the VM/VE/RM
2698# pb will take your local public SSH key to access
2699# the pb account in the VM/VE/RM later on if needed
2700sub pb_setup2v {
2701
2702my $vtype = shift;
2703my $sbx = shift || undef;
2704
2705my ($vm,$all) = pb_get2v($vtype);
2706
2707# Script generated
2708my $pbscript = "$ENV{'PBDESTDIR'}/setupv";
2709
2710# Adapt // mode to memory size
2711$pbparallel = pb_set_parallel($vtype);
2712
2713my $pm;
2714if (defined $pbparallel) {
2715    $pm = new Parallel::ForkManager($pbparallel);
2716
2717    # Set which port the VM/RM will use to communicate
2718    $pm->run_on_start(\&pb_set_port);
2719}
2720
2721my $counter = 0;
2722foreach my $v (@$vm) {
2723    $counter++;
2724    # Modulo pbparallel
2725    $counter = 1 if ((defined $pbparallel) && ($counter > $pbparallel));
2726    $pm->start($counter) and next if (defined $pbparallel);
2727
2728    # Get distro context
2729    my $pbos = pb_distro_get_context($v);
2730   
2731    # Deal with date sync.
2732    my $ntpline = pb_date2v($vtype,$pbos);
2733
2734    # Name of the account to deal with for VM/VE/RM
2735    # Do not use the one passed potentially with -a
2736    my ($pbac) = pb_conf_get($vtype."login");
2737    my ($key,$zero0,$zero1,$zero2);
2738    my ($vmexist,$vmpid);
2739
2740    # Prepare the script to be executed on the VM/VE/RM
2741    # in $ENV{'PBDESTDIR'}/setupv
2742    open(SCRIPT,"> $pbscript") || die "Unable to create $pbscript";
2743   
2744    print SCRIPT << 'EOF';
2745#!/usr/bin/perl -w
2746
2747use strict;
2748use File::Copy;
2749
2750# We should not need in this script more functions than what is provided
2751# by Base, Conf and Distribution to avoid problems at exec time.
2752# They are appended at the end.
2753
2754# Define mandatory global vars
2755our $pbdebug;
2756our $pbLOG;
2757our $pbsynmsg = "pbscript";
2758our $pbdisplaytype = "text";
2759our $pblocale = "";
2760pb_log_init($pbdebug, $pbLOG);
2761pb_temp_init();
2762
2763EOF
2764
2765    # Launch the VM/VE/RM - Usage of snapshot disabled
2766    ($vmexist,$vmpid) = pb_launchv($vtype,$v,0,0,0);
2767
2768    my $keyfile;
2769    my $nport;
2770    my $vmhost;
2771
2772    # Prepare the key to be used and transfered remotely
2773    $keyfile = pb_ssh_get(1);
2774       
2775    if ($vtype =~ /(v|r)m/) {
2776        my ($vmport);
2777        ($vmhost,$vmport) = pb_conf_get($vtype."host",$vtype."port");
2778        $nport = pb_get_port($vmport,$pbos,$vtype);
2779   
2780        # Skip that VM/RM if something went wrong
2781        next if (($vmpid == 0) && ($vmexist == 0));
2782   
2783        # Store the pub key part in a variable
2784        open(FILE,"$keyfile.pub") || die "Unable to open $keyfile.pub";
2785        ($zero0,$zero1,$zero2) = split(/ /,<FILE>);
2786        close(FILE);
2787
2788        $key = "\Q$zero1";
2789
2790        # We call true to avoid problems if SELinux is not activated, but chcon is present and returns in that case 1
2791        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");
2792        # once this is done, we can do what we need on the VM/RM remotely
2793    } elsif ($vtype eq "ve") {
2794        print SCRIPT << "EOF";
2795# For VE we need a good null dev
2796pb_system("rm -f /dev/null; mknod /dev/null c 1 3; chmod 777 /dev/null");
2797EOF
2798        print SCRIPT << "EOF";
2799# For VE we first need to mount some FS
2800pb_system("mount -t proc /proc /proc");
2801
2802EOF
2803    }
2804
2805    if ($vtype =~ /(v|r)m/) {
2806        print SCRIPT << 'EOF';
2807# Removes duplicate in .ssh/authorized_keys of our key if needed
2808#
2809my $file1="$ENV{'HOME'}/.ssh/authorized_keys";
2810open(PBFILE,$file1) || die "Unable to open $file1";
2811open(PBOUT,"> $file1.new") || die "Unable to open $file1.new";
2812my $count = 0;
2813while (<PBFILE>) {
2814
2815EOF
2816        print SCRIPT << "EOF";
2817    if (/ $key /) {
2818        \$count++;
2819    }
2820print PBOUT \$_ if ((\$count <= 1) || (\$_ !~ / $key /));
2821}
2822close(PBFILE);
2823close(PBOUT);
2824rename("\$file1.new",\$file1);
2825chmod 0600,\$file1;
2826
2827EOF
2828    }
2829    print SCRIPT << 'EOF';
2830
2831# Adds $pbac->{$ENV{'PBPROJ'}} as an account if needed
2832#
2833my $file="/etc/passwd";
2834open(PBFILE,$file) || die "Unable to open $file";
2835my $found = 0;
2836while (<PBFILE>) {
2837EOF
2838    print SCRIPT << "EOF";
2839    \$found = 1 if (/^$pbac->{$ENV{'PBPROJ'}}:/);
2840EOF
2841
2842# TODO: use an external parameter
2843my $home = "/home";
2844# Solaris doesn't like that we use /home
2845$home = "/export/home" if ($pbos->{'type'} eq "pkg");
2846
2847    print SCRIPT << "EOF";
2848}
2849close(PBFILE);
2850
2851if ( \$found == 0 ) {
2852    if ( ! -d "$home" ) {
2853        pb_mkdir_p("$home");
2854    }
2855EOF
2856    # TODO: Level of portability of these cmds ? Critical now for RM
2857    # TODO: Check existence before adding to avoid errors
2858    print SCRIPT << "EOF";
2859pb_system("/usr/sbin/groupadd $pbac->{$ENV{'PBPROJ'}}","Adding group $pbac->{$ENV{'PBPROJ'}}");
2860pb_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'}})");
2861}
2862EOF
2863
2864    # Copy the content of our local conf file to the VM/VE/RM
2865    my $content = pb_get_content(pb_distro_conffile());
2866    print SCRIPT << "EOF";
2867    #
2868    # Create a temporary local conf file for distribution support
2869    # This is created here before its use later. Its place is hardcoded, so no choice for the path
2870    #
2871    my \$tempconf = pb_distro_conffile();
2872    pb_mkdir_p(dirname(\$tempconf));
2873    open(CONF,"> \$tempconf") || die "Unable to create \$tempconf";
2874    print CONF q{$content};
2875    close(CONF);
2876EOF
2877
2878    if ($vtype =~ /(v|r)m/) {
2879        print SCRIPT << "EOF";
2880# allow ssh entry to build
2881#
2882mkdir "$home/$pbac->{$ENV{'PBPROJ'}}/.ssh",0700;
2883# Allow those accessing root to access the build account
2884copy("\$ENV{'HOME'}/.ssh/authorized_keys","$home/$pbac->{$ENV{'PBPROJ'}}/.ssh/authorized_keys");
2885chmod 0600,".ssh/authorized_keys";
2886pb_system("chown -R $pbac->{$ENV{'PBPROJ'}}:$pbac->{$ENV{'PBPROJ'}} $home/$pbac->{$ENV{'PBPROJ'}}","Finish setting up the account env for $pbac->{$ENV{'PBPROJ'}}");
2887
2888EOF
2889}
2890    print SCRIPT << 'EOF';
2891# No passwd for build account only keys
2892$file="/etc/shadow";
2893if (-f $file) {
2894    open(PBFILE,$file) || die "Unable to open $file";
2895    open(PBOUT,"> $file.new") || die "Unable to open $file.new";
2896    while (<PBFILE>) {
2897EOF
2898    print SCRIPT << "EOF";
2899        s/^$pbac->{$ENV{'PBPROJ'}}:\!\!:/$pbac->{$ENV{'PBPROJ'}}:*:/;
2900        s/^$pbac->{$ENV{'PBPROJ'}}:\!:/$pbac->{$ENV{'PBPROJ'}}:*:/; #SLES 9 e.g.
2901        s/^$pbac->{$ENV{'PBPROJ'}}:\\*LK\\*:/$pbac->{$ENV{'PBPROJ'}}:NP:/;  #Solaris e.g.
2902EOF
2903        print SCRIPT << 'EOF';
2904        print PBOUT $_;
2905    }
2906    close(PBFILE);
2907    close(PBOUT);
2908    rename("$file.new",$file);
2909    chmod 0640,$file;
2910    }
2911
2912# Keep the VM in text mode
2913$file="/etc/inittab";
2914if (-f $file) {
2915    open(PBFILE,$file) || die "Unable to open $file";
2916    open(PBOUT,"> $file.new") || die "Unable to open $file.new";
2917    while (<PBFILE>) {
2918        s/^(..):5:initdefault:$/$1:3:initdefault:/;
2919        print PBOUT $_;
2920    }
2921    close(PBFILE);
2922    close(PBOUT);
2923    rename("$file.new",$file);
2924    chmod 0640,$file;
2925}
2926
2927# pb has to be added to portage group on gentoo
2928
2929# We need to have that pb_distro_get_context function
2930# Get it from Project-Builder::Distribution
2931# And we now need the conf file required for this to work created above
2932
2933my $pbos = pb_distro_get_context(); 
2934print "distro tuple: ".Dumper($pbos)."\n";
2935
2936# Adapt sudoers
2937# sudo is not default on Solaris and needs to be installed first
2938# from http://www.sunfreeware.com/programlistsparc10.html#sudo
2939if ($pbos->{'type'} eq "pkg") {
2940    $file="/usr/local/etc/sudoers";
2941} else {
2942    $file="/etc/sudoers";
2943}
2944open(PBFILE,$file) || die "Unable to open $file";
2945open(PBOUT,"> $file.new") || die "Unable to open $file.new";
2946while (<PBFILE>) {
2947EOF
2948    # Skip what will be generated
2949    print SCRIPT << "EOF";
2950    next if (/^$pbac->{$ENV{'PBPROJ'}}\\s+/);
2951    next if (/^Defaults:$pbac->{$ENV{'PBPROJ'}}\\s+/);
2952    next if (/^Defaults:root \!requiretty/);
2953EOF
2954    print SCRIPT << 'EOF';
2955    s/Defaults[ \t]+requiretty//;
2956    print PBOUT $_;
2957}
2958close(PBFILE);
2959EOF
2960    print SCRIPT << "EOF";
2961# Some distro force requiretty at compile time, so disable here
2962print PBOUT "Defaults:$pbac->{$ENV{'PBPROJ'}} !requiretty\n";
2963print PBOUT "Defaults:root !requiretty\n";
2964# Keep proxy configuration while using sudo
2965print PBOUT "Defaults:$pbac->{$ENV{'PBPROJ'}}    env_keep += \\\"http_proxy ftp_proxy\\\"\n";
2966EOF
2967    # Try to restrict security to what is really needed
2968    if ($vtype =~ /^vm/) {
2969        my $hpath = pb_distro_get_param($pbos,pb_conf_get("ospathcmd-halt"));
2970        my @sudocmds = pb_get_sudocmds($pbos,$ntpline,"sudo $hpath");
2971        print SCRIPT << "EOF";
2972# This is needed in order to be able on VM to halt the machine from the $pbac->{$ENV{'PBPROJ'}} account at least
2973# Build account $pbac->{$ENV{'PBPROJ'}} in VM also needs to setup date and install deps.
2974# Nothing else should be needed
2975EOF
2976        foreach my $c (@sudocmds) {
2977            print SCRIPT "print PBOUT \"$pbac->{$ENV{'PBPROJ'}}   ALL = NOPASSWD: $c\n\";";
2978        }
2979    } elsif ($vtype =~ /^rm/) {
2980        my @sudocmds = pb_get_sudocmds($pbos,$ntpline);
2981        print SCRIPT << "EOF";
2982# Build account $pbac->{$ENV{'PBPROJ'}} in RM only needs to setup date and install deps if needed each time
2983EOF
2984        foreach my $c (@sudocmds) {
2985            print SCRIPT "print PBOUT \"$pbac->{$ENV{'PBPROJ'}}   ALL = NOPASSWD: $c\n\";";
2986        }
2987    } else {
2988        print SCRIPT << "EOF";
2989# Build account $pbac->{$ENV{'PBPROJ'}} for VE needs to do a lot in the host (and chroot), so allow without restriction for now
2990print PBOUT "$pbac->{$ENV{'PBPROJ'}}   ALL=(ALL) NOPASSWD:ALL\n";
2991EOF
2992}
2993    print SCRIPT << 'EOF';
2994close(PBOUT);
2995rename("$file.new",$file);
2996chmod 0440,$file;
2997
2998EOF
2999
3000    if ($vtype =~ /(v|r)m/) {
3001        # Sync date
3002        # do it after sudoers is setup
3003        print SCRIPT "pb_system(\"$ntpline\");\n";
3004    }
3005    # We may need a proxy configuration. Get it from the local env
3006
3007    if (defined $ENV{'http_proxy'}) {
3008        print SCRIPT "\$ENV\{'http_proxy'\}=\"$ENV{'http_proxy'}\";\n";
3009    }
3010
3011    if (defined $ENV{'ftp_proxy'}) {
3012        print SCRIPT "\$ENV\{'ftp_proxy'\}=\"$ENV{'ftp_proxy'}\";\n";
3013    }
3014
3015    print SCRIPT << 'EOF';
3016   
3017# Suse wants sudoers as 640
3018if ((($pbos->{'name'} eq "sles") && (($pbos->{'version'} =~ /10/) || ($pbos->{'version'} =~ /9/))) || (($pbos->{'name'} eq "opensuse") && ($pbos->{'version'} =~ /10.[012]/))) {
3019    chmod 0640,$file;
3020}
3021
3022# First install all required packages
3023pb_system("yum clean all","Cleaning yum env") if (($pbos->{'name'} eq "fedora") || ($pbos->{'name'} eq "asianux") || ($pbos->{'name'} eq "rhel"));
3024my ($ospkgdep) = pb_conf_get_if("ospkgdep");
3025   
3026my $pkgdep = pb_distro_get_param($pbos,$ospkgdep);
3027pb_distro_installdeps(undef,$pbos,pb_distro_only_deps_needed($pbos,join(' ',split(/,/,$pkgdep))));
3028
3029EOF
3030    my $itype = pb_distro_get_param($pbos,pb_conf_get("pbinstalltype"));
3031    # Install from sandbox mean a file base install
3032    $itype = "file" if (defined $sbx);
3033    if ($itype =~ /^file/) {
3034        my $cmdget;
3035        if (defined $sbx) {
3036            # Install from sandbox mean using the result of the just passed sbx2build command
3037            # Get content saved in cms2build
3038            my ($pkg) = pb_conf_read("$ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.pb","pbpkg");
3039            die "Unable to get package list" if (not defined $pkg);
3040
3041            # We consider 2 specific packages
3042            my $vertag1 = $pkg->{"ProjectBuilder"};
3043            my $vertag2 = $pkg->{"project-builder"};
3044            # get the version of the current package - maybe different
3045            my ($pbver1,$tmp1) = split(/-/,$vertag1);
3046            my ($pbver2,$tmp2) = split(/-/,$vertag2);
3047            # Copy inside the VE
3048            if ($vtype eq "ve") {
3049                my ($vepath) = pb_conf_get("vepath");
3050                copy("$ENV{'PBDESTDIR'}/ProjectBuilder-$pbver1.tar.gz","$vepath->{$ENV{'PBPROJ'}}/$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}/tmp");
3051                copy("$ENV{'PBDESTDIR'}/project-builder-$pbver2.tar.gz","$vepath->{$ENV{'PBPROJ'}}/$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}/tmp");
3052            } else {
3053                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.");
3054            }
3055            $cmdget = "mv /tmp/ProjectBuilder-$pbver1.tar.gz ProjectBuilder-latest.tar.gz ; mv /tmp/project-builder-$pbver2.tar.gz project-builder-latest.tar.gz";
3056        } else {
3057            $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";
3058        }
3059        print SCRIPT << 'EOF';
3060# Then install manually the missing perl modules
3061my ($osperldep,$osperlver) = pb_conf_get_if("osperldep","osperlver");
3062   
3063my $perldep = pb_distro_get_param($pbos,$osperldep);
3064foreach my $m (split(/,/,$perldep)) {
3065    # Skip empty deps
3066    next if ($m =~ /^\s*$/);
3067    my $dir = $m;
3068    $dir =~ s/-.*//;
3069    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}");
3070}
3071EOF
3072        print SCRIPT << "EOF";
3073pb_system("rm -rf ProjectBuilder-* ; rm -rf project-builder-* ; rm -rf `perl -V:installvendorlib  | awk -F"'" '{print  \$2}'`/ProjectBuilder ; $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");
3074EOF
3075    } elsif ($itype =~ /^pkg/) {
3076        # pkg based install. We need to point to the project-builder.org repository
3077        print SCRIPT << 'EOF';
3078my $pkgforpb = pb_distro_get_param($pbos,pb_conf_get_if("ospkg"));
3079pb_distro_setuposrepo($pbos);
3080pb_distro_installdeps(undef,$pbos,pb_distro_only_deps_needed($pbos,join(' ',split(/,/,$pkgforpb))));
3081EOF
3082    } else {
3083        # Unknown install type
3084        die("Unknown install type $itype->{$ENV{'PBPROJ'}} for param pbinstalltype");
3085    }
3086    print SCRIPT << 'EOF';
3087pb_system("pb 2>&1 | head -5",undef,"verbose");
3088pb_system("pbdistrocheck",undef,"verbose");
3089EOF
3090    if ($vtype eq "ve") {
3091            print SCRIPT << 'EOF';
3092# For VE we need to umount some FS at the end
3093
3094pb_system("umount /proc");
3095
3096# Create a basic network file if not already there
3097
3098my $nf="/etc/sysconfig/network";
3099if ((! -f $nf) && ($pbos->{'type'} eq "rpm")) {
3100    open(NF,"> $nf") || die "Unable to create $nf";
3101    print NF "NETWORKING=yes\n";
3102    print NF "HOSTNAME=localhost\n";
3103    close(NF);
3104}
3105chmod 0755,$nf;
3106EOF
3107    }
3108
3109    # Adds pb_distro_get_context and all functions needed from ProjectBuilder::Distribution, Conf and Base
3110    foreach my $d (@INC) {
3111        my @f = ("$d/ProjectBuilder/Base.pm","$d/ProjectBuilder/Distribution.pm","$d/ProjectBuilder/Conf.pm");
3112        foreach my $f (@f) {
3113            if (-f "$f") {
3114                open(PBD,"$f") || die "Unable to open $f";
3115                while (<PBD>) {
3116                    next if (/^package/);
3117                    next if (/^use Exporter/);
3118                    next if (/^use ProjectBuilder::/);
3119                    next if (/^our /);
3120                    print SCRIPT $_;
3121                }
3122                close(PBD);
3123            }
3124        }
3125    }
3126    # Use a fake pb_version_init version here
3127    print SCRIPT << "EOF";
3128sub pb_version_init {
3129
3130return("$projectbuilderver","$projectbuilderrev");
3131}
31321;
3133EOF
3134    close(SCRIPT);
3135    chmod 0755,"$pbscript";
3136
3137    # That build script needs to be run as root and force stop of VM at end
3138    $pbaccount = "root";
3139
3140    # Force shutdown of VM except if it was already launched
3141    my $pbforce = 0;
3142    if ((! $vmexist) && ($vtype eq "vm")) {
3143        $pbforce = 1;
3144    }
3145   
3146    pb_script2v($pbscript,$vtype,$pbforce,$v);
3147    $pm->finish if (defined $pbparallel);
3148}
3149$pm->wait_all_children if (defined $pbparallel);
3150return;
3151}
3152
3153# Function to create a snapshot named 'pb' for VMs and a compressed tar for VEs
3154sub pb_snap2v {
3155
3156my $vtype = shift;
3157
3158my ($vm,$all) = pb_get2v($vtype);
3159
3160# Script generated
3161my $pbscript = "$ENV{'PBDESTDIR'}/snapv";
3162
3163my ($pbac) = pb_conf_get($vtype."login");
3164
3165foreach my $v (@$vm) {
3166    if ($vtype eq "ve") {
3167        # Get distro context
3168        my $pbos = pb_distro_get_context($v);
3169        my ($vepath) = pb_conf_get("vepath");
3170
3171        # Test if an existing snapshot exists and remove it if there is a VE
3172        if ((-f "$vepath->{$ENV{'PBPROJ'}}/$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}.tar.gz") &&
3173            (! -d "$vepath->{$ENV{'PBPROJ'}}/$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}")) {
3174                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");
3175        }
3176    }
3177
3178    # Prepare the script to be executed on the VM/VE
3179    open(SCRIPT,"> $pbscript") || die "Unable to create $pbscript";
3180    print SCRIPT << 'EOF';
3181    #!/bin/bash
3182    sleep 2
3183EOF
3184    close(SCRIPT);
3185    chmod 0755,"$pbscript";
3186
3187    # Force shutdown of VM/VE
3188    # Force snapshot of VM/VE
3189    pb_script2v($pbscript,$vtype,1,$v,1);
3190}
3191return;
3192}
3193
3194# Function to update VMs/VEs/RMs with the latest distribution content
3195sub pb_update2v {
3196
3197my $vtype = shift;
3198
3199my ($vm,$all) = pb_get2v($vtype);
3200
3201# Script generated
3202my $pbscript = "$ENV{'PBDESTDIR'}/updatev";
3203
3204my ($pbac) = pb_conf_get($vtype."login");
3205
3206foreach my $v (@$vm) {
3207    # Get distro context
3208    my $pbos = pb_distro_get_context($v);
3209
3210    # Prepare the script to be executed on the VM/VE/RM
3211    # in $ENV{'PBDESTDIR'}/updatev
3212    open(SCRIPT,"> $pbscript") || die "Unable to create $pbscript";
3213   
3214    print SCRIPT << 'EOF';
3215    #!/bin/bash
3216    sleep 2
3217EOF
3218    # VE needs a good /proc
3219    if ($vtype eq "ve") {
3220        print SCRIPT "sudo /bin/mount -t proc /proc /proc\n";
3221    }
3222    print SCRIPT "$pbos->{'update'}\n";
3223    if ($vtype eq "ve") {
3224        print SCRIPT "sudo /bin/umount /proc\n";
3225    }
3226    close(SCRIPT);
3227    chmod 0755,"$pbscript";
3228
3229    # Force shutdown of VM except
3230    pb_script2v($pbscript,$vtype,1,$v);
3231}
3232return;
3233}
3234
3235sub pb_announce {
3236
3237    my $antype = shift;
3238
3239    # Get all required parameters
3240    my ($pbpackager,$pbrepo,$pbml,$pbsmtp) = pb_conf_get("pbpackager","pbrepo","pbml","pbsmtp");
3241    my ($pkgv, $pkgt, $testver) = pb_conf_get_if("pkgver","pkgtag","testver");
3242    if (((not defined $testver) || (not defined $testver->{$ENV{'PBPROJ'}}) || ($testver->{$ENV{'PBPROJ'}} !~ /true/i)) && ($antype eq "Clean")) {
3243        # We just clean for test versions
3244        pb_log(0,"Unable to clean SSH repository for non testver version\n");
3245        return;
3246    }
3247    my $pkg = pb_cms_get_pkg($defpkgdir,$extpkgdir);
3248    my @pkgs = @$pkg;
3249    my %pkgs;
3250    my $first = 0;
3251
3252    # Get all distros concerned
3253    my $pbos = pb_distro_get_context();
3254    my $distrolist = pb_get_distros($pbos,undef);
3255    my %dl;
3256    my %theorlist;
3257    my %archlist;
3258    foreach my $d (split(/,/,$distrolist)) {
3259        my ($d1,$d2,$d3) = split(/-/,$d);
3260        $dl{$d1}++;
3261    }
3262
3263    # Command to find packages on repo
3264    my $findstr = "find ".join(" ",keys %dl)." ";
3265    my $srcstr = "";
3266    # Generated announce files
3267    my @files;
3268
3269    foreach my $pbpkg (@pkgs) {
3270        if ($first != 0) {
3271            $findstr .= "-o ";
3272        }
3273        $first++;
3274        if ((defined $pkgv) && (defined $pkgv->{$pbpkg})) {
3275            $pbver = $pkgv->{$pbpkg};
3276        } else {
3277            $pbver = $ENV{'PBPROJVER'};
3278        }
3279        if ((defined $pkgt) && (defined $pkgt->{$pbpkg})) {
3280            $pbtag = $pkgt->{$pbpkg};
3281        } else {
3282            $pbtag = $ENV{'PBPROJTAG'};
3283        }
3284
3285        # TODO: use virtual/real names here now
3286        my $pbrealpkg = $pbpkg;
3287        my $pbrealpkgrpm = pb_cms_get_real_pkg($pbpkg,"rpm");
3288        my $pbrealpkgdeb = pb_cms_get_real_pkg($pbpkg,"deb");
3289        if ($antype eq "Clean") {
3290            $pbtag = "0.[0-9][0-9]*";
3291            $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\' ";
3292            $srcstr .= "src/$pbrealpkg-$pbver.tar.gz src/$pbrealpkg-$pbver.pbconf.tar.gz ";
3293        } else {
3294            my @date=pb_get_date();
3295            # the matching is only done on packages made the same day for test version. Hopefully this is enough
3296            $pbtag = "0.".strftime("%Y%m%d*", @date) if ((defined $testver) && (defined $testver->{$ENV{'PBPROJ'}}) && ($testver->{$ENV{'PBPROJ'}} =~ /true/i) && ($antype eq "Check"));
3297            $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\' ";
3298        }
3299
3300        if ($antype eq "Announce") {
3301            my $chglog;
3302
3303            pb_cms_init($pbinit);
3304            # Get project info on log file and generate tmp files used later on
3305            $chglog = "$ENV{'PBROOTDIR'}/$pbpkg/pbcl";
3306            $chglog = "$ENV{'PBROOTDIR'}/pbcl" if (! -f $chglog);
3307            $chglog = undef if (! -f $chglog);
3308
3309            open(OUT,"> $ENV{'PBTMP'}/$pbpkg.ann") || die "Unable to create $ENV{'PBTMP'}/$pbpkg.ann: $!";
3310            my $pb;
3311            $pb->{'realpkg'} = $pbrealpkg;
3312            $pb->{'ver'} = $pbver;
3313            $pb->{'tag'} = $pbtag;
3314            $pb->{'date'} = $pbdate;
3315            $pb->{'chglog'} = $chglog;
3316            $pb->{'packager'} = $pbpackager;
3317            $pb->{'proj'} = $ENV{'PBPROJ'};
3318            $pb->{'repo'} = $pbrepo;
3319            $pb->{'pbos'}->{'type'} = "announce";
3320            $pb->{'pbos'}->{'suffix'} = "none";
3321            pb_changelog($pb,\*OUT,"yes");
3322            close(OUT);
3323            push(@files,"$ENV{'PBTMP'}/$pbpkg.ann");
3324        } elsif ($antype eq "Check") {
3325            # For the check we also build the theoritical complete list we should get
3326            foreach my $d (split(/,/,$distrolist)) {
3327                $pbos = pb_distro_get_context($d);
3328                if ($pbos->{'type'} eq "rpm") {
3329                    $theorlist{"$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}/$pbrealpkgrpm-$pbver-$pbtag$pbos->{'suffix'}"} = 0;
3330                } elsif ($pbos->{'type'} eq "deb") {
3331                    $theorlist{"$pbos->{'name'}/$pbos->{'version'}/$pbrealpkgdeb"."_$pbver-$pbtag"} = 0;
3332                    # TODO are we always using the last arch ?
3333                    $archlist{"$pbos->{'name'}/$pbos->{'version'}/$pbrealpkgdeb"."_$pbver-$pbtag"} = "$pbos->{'arch'}";
3334                } elsif ($pbos->{'type'} eq "ebuild") {
3335                    $theorlist{"$pbos->{'name'}/$pbos->{'version'}/$pbrealpkg-$pbver"."_p$pbtag.ebuild"} = 0;
3336                    $archlist{"$pbos->{'name'}/$pbos->{'version'}/$pbrealpkg-$pbver"."_p$pbtag.ebuild"} = "$pbos->{'arch'}";
3337                } elsif ($pbos->{'type'} eq "pkg") {
3338                    $theorlist{"$pbos->{'name'}/$pbos->{'version'}/$pbos->{'arch'}/$pbrealpkg-$pbver-$pbtag.pkg"} = 0;
3339                } else {
3340                    pb_log(1,"No theoritical list possible for type $pbos->{'type'}\n");
3341                }
3342            }
3343        }
3344        pb_log(2,"theorlist : ".Dumper(%theorlist)."\n");
3345    }
3346    if ($antype eq "Announce") {
3347        $findstr .= " | grep -Ev \'src.rpm\'";
3348    } elsif ($antype eq "Clean") {
3349        $findstr .= " | xargs rm -f -v $srcstr ";
3350    }
3351
3352    # Prepare the command to run and execute it
3353    open(PBS,"> $ENV{'PBTMP'}/pbscript") || die "Unable to create $ENV{'PBTMP'}/pbscript";
3354    print PBS "#!/bin/bash\n";
3355    print PBS "set -x\n" if ($pbdebug gt 1);
3356    print PBS "$findstr | sort 2> /dev/null\n";
3357    close(PBS);
3358    chmod 0755,"$ENV{'PBTMP'}/pbscript";
3359    pb_send2target("Announce");
3360
3361    my $sl = "Project $ENV{'PBPROJ'} version $ENV{'PBPROJVER'} is now available";
3362    if ($antype eq "Announce") {
3363        # Get subject line
3364        pb_log(0,"Please enter the title of your announce\n");
3365        pb_log(0,"(By default: $sl)\n");
3366        my $sl2 = <STDIN>;
3367        $sl = $sl2 if ($sl2 !~ /^$/);
3368
3369        # Prepare a template of announce
3370        open(ANN,"> $ENV{'PBTMP'}/announce.html") || die "Unable to create $ENV{'PBTMP'}/announce.html: $!";
3371        print ANN << "EOF";
3372$sl</p>
3373
3374<p>The project team is happy to announce the availability of a newest version of $ENV{'PBPROJ'} $ENV{'PBPROJVER'}. Enjoy it as usual!</p>
3375<p>
3376Now available at <a href="$pbrepo->{$ENV{'PBPROJ'}}">$pbrepo->{$ENV{'PBPROJ'}}</a>
3377</p>
3378<p>
3379EOF
3380    }
3381
3382    open(LOG,"$ENV{'PBTMP'}/system.$$.log") || die "Unable to read $ENV{'PBTMP'}/system.$$.log: $!";
3383    if ($antype eq "Announce") {
3384        my $col = 2;
3385        my $i = 1;
3386        print ANN << 'EOF';
3387<TABLE WIDTH="700" CELLPADDING="0" CELLSPACING="0" BORDER="0">
3388<TR>
3389EOF
3390        while (<LOG>) {
3391            print ANN "<TD><A HREF=\"$pbrepo->{$ENV{'PBPROJ'}}/$_\">$_</A></TD>";
3392            $i++;
3393            if ($i > $col) {
3394                print ANN "</TR>\n<TR>";
3395                $i = 1;
3396            }
3397        }
3398    } elsif ($antype eq "Clean") {
3399        while (<LOG>) {
3400            # skip errors
3401            next if ($_ !~ /^removed /);
3402            pb_log(0,"$_");
3403        }
3404    } else {
3405        # In Check mode we need to compare the 2 lists (real and theoritical)
3406        while (<LOG>) {
3407            # Get package name and remove what is in extra for the theoritical list (arch at the end)
3408            chomp();
3409            # skip find errors
3410            next if (/^find:/);
3411            my $p = $_;
3412            $p =~ s/\.(i[3456]86|x86_64|noarch|src)\.rpm$//;
3413            $p =~ s/_(i[3456]86|amd64|all).deb$//;
3414            $p =~ s/(-0\.|_p[0-9]{8})[0-9]{6}/$1*/ if ((defined $testver) && (defined $testver->{$ENV{'PBPROJ'}}) && ($testver->{$ENV{'PBPROJ'}} =~ /true/i));
3415            $theorlist{$p} = -2 if (not defined $theorlist{$p});
3416            $theorlist{$p} = $theorlist{$p} + 1;
3417        }
3418        pb_log(2,"theorlist : ".Dumper(%theorlist)."\n");
3419    }
3420    close(LOG);
3421
3422    # Nothing more for the cleanssh case
3423    return if ($antype eq "Clean");
3424
3425    if ($antype eq "Check") {
3426        my ($chkex) = pb_conf_get_if("checkexclude");
3427        my $vmbuildlist = "";
3428        my $vebuildlist = "";
3429        my $rmbuildlist = "";
3430        my @pt = pb_conf_get_if("vmlist","velist","rmlist");
3431        foreach my $t (sort keys %theorlist) {
3432            if (defined $theorlist{$t} and $theorlist{$t} >= 1) {
3433                pb_log(1,"Packages found for $t\n");
3434            } elsif (defined $theorlist{$t} and $theorlist{$t} < 0) {
3435                pb_log(0,"Extra Package found for $t\n");
3436            } else {
3437                pb_log(2,"Analyzing $t\n");
3438                my ($os,$ver,$arch,$package) = split(/\//,$t);
3439                # Some distro have no arch subdir
3440                if (not defined $package) {
3441                    $package = $arch;
3442                    # TODO: If both arch have failed, we just make the last one
3443                    $arch = $archlist{$t};
3444                }
3445                my $pbos = pb_distro_get_context("$os-$ver-$arch");
3446                my $pkgn = $package;
3447                if ($pbos->{'type'} ne "deb") {
3448                    # package name is more easily found from the end for non deb
3449                    # as '-' is the separator, but it can also be used in names
3450                    $pkgn = reverse($package);
3451                    # search the second '-' and isolate the now last part which is the full name
3452                    $pkgn =~ s/([^-]+)-([^-]+)-([\S])+$/$3/;
3453                } else {
3454                    $pkgn =~ s/([^_]+)_([\S])+$/$2/;
3455                }
3456                my $found = 0;
3457                # Handle the exclusion of OSes
3458                my $excl = "";
3459                $excl .= $chkex->{$pkgn} if (defined $chkex->{$pkgn});
3460                $excl .= $chkex->{"all"} if (defined $chkex->{"all"});
3461                foreach my $ex (split(/,/,$excl)) {
3462                    $found = 1 if ("$os-$ver-$arch" =~ /^$ex/);
3463                }
3464                # Skip as excluded
3465                next if ($found == 1);
3466                pb_log(0,"Package NOT found for $t\n");
3467                # Avoid duplicates in list
3468                next if ($vmbuildlist =~ /$os-$ver-$arch/);
3469                next if ($vebuildlist =~ /$os-$ver-$arch/);
3470                next if ($rmbuildlist =~ /$os-$ver-$arch/);
3471                # check with which method we need to build
3472                if ((defined $pt[0]->{$ENV{'PBPROJ'}}) and ($pt[0]->{$ENV{'PBPROJ'}} =~ /$os-$ver-$arch/)) {
3473                    $vmbuildlist = "$os-$ver-$arch" if ($vmbuildlist eq "");
3474                    $vmbuildlist .= ",$os-$ver-$arch" if ($vmbuildlist !~ /$os-$ver-$arch/);
3475                    next;
3476                }
3477                if ((defined $pt[1]->{$ENV{'PBPROJ'}}) and ($pt[1]->{$ENV{'PBPROJ'}} =~ /$os-$ver-$arch/)) {
3478                    $vebuildlist = "$os-$ver-$arch" if ($vebuildlist eq "");
3479                    $vebuildlist .= ",$os-$ver-$arch" if ($vebuildlist !~ /$os-$ver-$arch/);
3480                    next;
3481                }
3482                if ((defined $pt[2]->{$ENV{'PBPROJ'}}) and ($pt[2]->{$ENV{'PBPROJ'}} =~ /$os-$ver-$arch/)) {
3483                    $rmbuildlist = "$os-$ver-$arch" if ($rmbuildlist eq "");
3484                    $rmbuildlist .= ",$os-$ver-$arch" if ($rmbuildlist !~ /$os-$ver-$arch/);
3485                }
3486            }
3487        }
3488        # If we want to rebuild automatically, let's do it
3489        if (defined $opts{'rebuild'}) {
3490            # SandBox or CMS
3491            pb_log(0,"Rebuilding from SandBox\n");
3492            pb_log(0,"for VMs: $vmbuildlist\n") if ($vmbuildlist ne "");
3493            pb_log(0,"for VEs: $vebuildlist\n") if ($vebuildlist ne "");
3494            pb_log(0,"for RMs: $rmbuildlist\n") if ($rmbuildlist ne "");
3495            pb_cms2build("SandBox");
3496            # Which mode
3497            $ENV{'PBV'} = $vmbuildlist;
3498            pb_build2v("vm","build") if ($vmbuildlist ne "");
3499            $ENV{'PBV'} = $vebuildlist;
3500            pb_build2v("ve","build") if ($vebuildlist ne "");
3501            $ENV{'PBV'} = $rmbuildlist;
3502            pb_build2v("rm","build") if ($rmbuildlist ne "");
3503        }
3504        # For the check part this is now finished
3505        return;
3506    }
3507
3508    print ANN << "EOF";
3509</TR>
3510</TABLE>
3511</p>
3512
3513<p>As usual source packages are also available in the same directory.</p>
3514
3515<p>
3516Changes are :
3517</p>
3518<p>
3519EOF
3520    # Get each package changelog content
3521    foreach my $f (sort(@files)) {
3522        open(IN,"$f") || die "Unable to read $f:$!";
3523        while (<IN>) {
3524            print ANN $_;
3525        }
3526        close(IN);
3527        print ANN "</p><p>\n";
3528    }
3529    print ANN "</p>\n";
3530    close(ANN);
3531
3532    # Allow for modification
3533    my $editor = "vi";
3534    $editor = $ENV{'EDITOR'} if (defined $ENV{'EDITOR'});
3535    pb_system("$editor $ENV{'PBTMP'}/announce.html","Allowing modification of the announce","noredir");
3536
3537    # Store it in DB for external usage (Web pages generation)
3538    my $db = "$ENV{'PBCONFDIR'}/announces3.sql";
3539
3540    my $precmd = "";
3541    if (! -f $db) {
3542        $precmd = "CREATE TABLE announces (id INTEGER PRIMARY KEY AUTOINCREMENT, date DATE, announce VARCHAR[65535])";
3543    }
3544
3545    my $dbh = DBI->connect("dbi:SQLite:dbname=$db","","",
3546                        { RaiseError => 1, AutoCommit => 1 })
3547                        || die "Unable to connect to $db";
3548
3549    if ($precmd ne "") {
3550        my $sth = $dbh->prepare(qq{$precmd})
3551                    || die "Unable to create table into $db";
3552        $sth->execute();
3553    }
3554
3555    # To read whole file
3556    local $/;
3557    open(ANN,"$ENV{'PBTMP'}/announce.html") || die "Unable to read $ENV{'PBTMP'}/announce.html: $!";
3558    my $announce = <ANN>;
3559    close(ANN);
3560   
3561    pb_log(2,"INSERT INTO announces VALUES (NULL, $pbdate, $announce)");
3562    my $sth = $dbh->prepare(qq{INSERT INTO announces VALUES (NULL,?,?)})
3563                    || die "Unable to insert into $db";
3564    $sth->execute($pbdate, $announce);
3565    $sth->finish();
3566    $dbh->disconnect;
3567
3568    # Then deliver it on the Web
3569    # $TOOLHOME/livwww www
3570
3571    # Mail it to project's ML
3572    open(ML,"| w3m -dump -T text/html > $ENV{'PBTMP'}/announce.txt") || die "Unable to create $ENV{'PBTMP'}/announce.txt: $!";
3573    print ML << 'EOF';
3574<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/x html1/DTD/xhtml1-strict.dtd">
3575
3576<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" xml:lang="en" lang="en">
3577  <head>
3578  </head>
3579  <body>
3580  <p>
3581EOF
3582    open(ANN,"$ENV{'PBTMP'}/announce.html") || die "Unable to read $ENV{'PBTMP'}/announce.html: $!";
3583    while(<ANN>) {
3584        print ML $_;
3585    }
3586    print ML << 'EOF';
3587</body>
3588</html>
3589EOF
3590    close(ML);
3591
3592    # To read whole file
3593    local $/;
3594    open(ANN,"$ENV{'PBTMP'}/announce.txt") || die "Unable to read $ENV{'PBTMP'}/announce.txt: $!";
3595    my $msg = <ANN>;
3596    close(ANN);
3597   
3598    # Preparation of headers
3599    eval
3600    {
3601        require Mail::Sendmail;
3602        Mail::Sendmail->import();
3603    };
3604    if ($@) {
3605        # Mail::Sendmail not found not sending mail !
3606        pb_log(0,"No Mail::Sendmail module found so not sending any mail !\n");
3607    } else {
3608        my %mail = (   
3609            To          =>  $pbml->{$ENV{'PBPROJ'}},
3610            From        =>  $pbpackager->{$ENV{'PBPROJ'}},
3611            Smtp        =>  $pbsmtp->{$ENV{'PBPROJ'}},
3612            Body        =>  $msg,
3613            Subject     =>  "[ANNOUNCE] $sl",
3614        );
3615           
3616        # Send mail
3617        if (! sendmail(%mail)) {
3618            if ((defined $Mail::Sendmail::error) and (defined $Mail::Sendmail::log)) {
3619                die "Unable to send mail ($Mail::Sendmail::error): $Mail::Sendmail::log";
3620            }
3621        }
3622    }
3623}
3624
3625#
3626# Creates a set of HTML file containing the news for the project
3627# based on what has been generated by the pb_announce function
3628#
3629sub pb_web_news2html {
3630
3631    my $dest = shift || $ENV{'PBTMP'};
3632
3633    # Get all required parameters
3634    my ($pkgv, $pkgt) = pb_conf_get_if("pkgver","pkgtag");
3635
3636    # DB of announces for external usage (Web pages generation)
3637    my $db = "$ENV{'PBCONFDIR'}/announces3.sql";
3638
3639    my $dbh = DBI->connect("dbi:SQLite:dbname=$db","","",
3640                        { RaiseError => 1, AutoCommit => 1 })
3641                        || die "Unable to connect to $db";
3642    # For date handling
3643    $ENV{LANGUAGE}="C";
3644    my $firstjan = strftime("%Y-%m-%d", 0, 0, 0, 1, 0, localtime->year(), 0, 0, -1);
3645    my $oldfirst = strftime("%Y-%m-%d", 0, 0, 0, 1, 0, localtime->year()-1, 0, 0, -1);
3646    pb_log(2,"firstjan: $firstjan, oldfirst: $oldfirst, pbdate:$pbdate\n");
3647    my $all = $dbh->selectall_arrayref("SELECT id,date,announce FROM announces ORDER BY date DESC");
3648    my %news;
3649    $news{"cy"} = "";   # current year's news
3650    $news{"ly"} = "";   # last year news
3651    $news{"py"} = "";   # previous years news
3652    $news{"fp"} = "";   # first page news
3653    my $cpt = 4;        # how many news for first page
3654    # Extract info from DB
3655    foreach my $row (@$all) {
3656        my ($id, $date, $announce) = @$row;
3657        $news{"cy"} = $news{"cy"}."<p><B>$date</B> $announce\n" if ((($date cmp $pbdate) le 0) && (($firstjan cmp $date) le 0));
3658        $news{"ly"} = $news{"ly"}."<p><B>$date</B> $announce\n" if ((($date cmp $firstjan) le 0) && (($oldfirst cmp $date) le 0));
3659        $news{"py"} = $news{"py"}."<p><B>$date</B> $announce\n" if (($date cmp $oldfirst) le 0);
3660        $news{"fp"} = $news{"fp"}."<p><B>$date</B> $announce\n" if ($cpt > 0);
3661        $cpt--;
3662    }
3663    pb_log(1,"news{fp}: ".$news{"fp"}."\n");
3664    $dbh->disconnect;
3665
3666    # Generate the HTML content
3667    foreach my $pref (keys %news) {
3668        open(NEWS,"> $dest/pb_web_$pref"."news.html") || die "Unable to create $dest/pb_web_$pref"."news.html: $!";
3669        print NEWS "$news{$pref}";
3670        close(NEWS);
3671    }
3672}
3673
3674
3675# Return the SSH key file to use
3676# Potentially create it if needed
3677
3678sub pb_ssh_get {
3679
3680my $create = shift || 0;    # Do not create keys by default
3681
3682# Check the SSH environment
3683my $keyfile = undef;
3684
3685# We have specific keys by default
3686$keyfile = "$ENV{'HOME'}/.ssh/pb_dsa";
3687if (!(-e $keyfile) && ($create eq 1)) {
3688    pb_system("ssh-keygen -q -b 1024 -N '' -f $keyfile -t dsa","Generating SSH keys for pb");
3689}
3690
3691$keyfile = "$ENV{'HOME'}/.ssh/id_rsa" if (-s "$ENV{'HOME'}/.ssh/id_rsa");
3692$keyfile = "$ENV{'HOME'}/.ssh/id_dsa" if (-s "$ENV{'HOME'}/.ssh/id_dsa");
3693$keyfile = "$ENV{'HOME'}/.ssh/pb_dsa" if (-s "$ENV{'HOME'}/.ssh/pb_dsa");
3694die "Unable to find your public ssh key under $keyfile" if (not defined $keyfile);
3695return($keyfile);
3696}
3697
3698
3699# Returns the pid of a running VM command using a specific VM file
3700sub pb_check_ps {
3701    my $vmcmd = shift;
3702    my $vmm = shift;
3703    my $vmexist = 0;        # FALSE by default
3704
3705    open(PS, "ps auxhww|") || die "Unable to call ps";
3706    while (<PS>) {
3707        next if (! /$vmcmd/);
3708        next if (! /$vmm/);
3709        my ($void1, $void2);
3710        ($void1, $vmexist, $void2) = split(/ +/);
3711        last;
3712    }
3713    return($vmexist);
3714}
3715
3716
3717sub pb_extract_build_files {
3718
3719my $src=shift;
3720my $dir=shift;
3721my $ddir=shift;
3722my $mandatory=shift || "spec";
3723my @files;
3724
3725my $flag = "mayfail" if (($mandatory eq "patch") || ($mandatory eq "src"));
3726my $res;
3727
3728if ($src =~ /tar\.gz$/) {
3729    $res = pb_system("tar xfpz $src $dir","Extracting $mandatory files from $src",$flag);
3730} elsif ($src =~ /tar\.bz2$/) {
3731    $res = pb_system("tar xfpj $src $dir","Extracting $mandatory files from $src",$flag);
3732} else {
3733    die "Unknown compression algorithm for $src";
3734}
3735# If not mandatory return now
3736return() if (($res != 0) and (($mandatory eq "patch") || ($mandatory eq "src")));
3737opendir(DIR,"$dir") || die "Unable to open directory $dir";
3738foreach my $f (readdir(DIR)) {
3739    next if ($f =~ /^\./);
3740    # Skip potential patch dir
3741    next if ($f =~ /^pbpatch/);
3742    # Skip potential source dir
3743    next if ($f =~ /^pbsrc/);
3744    move("$dir/$f","$ddir") || die "Unable to move $dir/$f to $ddir";
3745    pb_log(2,"mv $dir/$f $ddir\n");
3746    push @files,"$ddir/$f";
3747}
3748closedir(DIR);
3749# Not enough but still a first cleanup
3750pb_rm_rf("$dir");
3751return(@files);
3752}
3753
3754sub pb_list_bfiles {
3755
3756my $dir = shift;
3757my $pbpkg = shift;
3758my $bfiles = shift;
3759my $pkgfiles = shift;
3760my $supfiles = shift;
3761# subdir to keep if recursive mode, empty by default
3762my $subdir = shift || "";
3763# In a recursive function , we need a local var as DIR handle
3764my $bdir;
3765
3766pb_log(2,"DEBUG: entering pb_list_bfiles in $dir: ".Dumper($bfiles)."\n");
3767opendir($bdir,"$dir") || die "Unable to open dir $dir: $!";
3768foreach my $f (readdir($bdir)) {
3769    pb_log(3,"DEBUG: pb_list_bfiles found $f\n");
3770    next if ($f =~ /^\./);
3771    if (-d "$dir/$f") {
3772        # Recurse for directories (Debian 3.0 format e.g.)
3773        pb_log(2,"DEBUG: pb_list_bfiles recurse in $dir/$f\n");
3774        pb_list_bfiles("$dir/$f",$pbpkg,$bfiles,$pkgfiles,$supfiles,$f);
3775        next;
3776    }
3777
3778    my $key = $f;
3779    # if recursive then store also the subdir
3780    $key = "$subdir/$f" if ($subdir ne "");
3781    $bfiles->{$key} = "$dir/$f";
3782    $bfiles->{$key} =~ s~$ENV{'PBROOTDIR'}~~;
3783    if (defined $supfiles->{$pbpkg}) {
3784        $pkgfiles->{$key} = "$dir/$f" if ($f =~ /$supfiles->{$pbpkg}/);
3785    }
3786}
3787closedir($bdir);
3788pb_log(2,"DEBUG: exiting pb_list_bfiles: ".Dumper($bfiles)."\n");
3789}
3790
3791sub pb_add_coma {
3792
3793my $str = shift;
3794my $addstr = shift;
3795
3796$str .= "," if (defined $str);
3797$str .= $addstr;
3798return($str);
3799}
3800
3801sub pb_list_sfiles {
3802
3803my $sdir = shift;
3804my $ptr = shift;
3805my $pbos = shift;
3806my $extdir = shift;
3807
3808pb_log(2,"DEBUG: entering pb_list_sfiles: ".Dumper($ptr)."\n");
3809my $key = "$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}";
3810
3811# Prepare local sources for this distro - They are always applied first - May be a problem one day
3812# This function works for both patches and additional sources
3813foreach my $p (sort(<$sdir/*>)) {
3814    $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'}$/));
3815}
3816
3817# Prepare also remote sources to be included - Applied after the local ones
3818foreach my $p ("all","$pbos->{'os'}","$pbos->{'type'}","$pbos->{'family'}","$pbos->{'name'}","$pbos->{'name'}-$pbos->{'version'}","$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}") {
3819    my $f = "$extdir.".".$p";
3820    next if (not -f $f);
3821    if (not open(PATCH,$f)) {
3822        pb_display("Unable to open existing external source file content $f\n");
3823        next;
3824    }
3825    while (<PATCH>) {
3826        chomp();
3827        $ptr->{$key} = pb_add_coma($ptr->{$key},"$_");
3828    }
3829    close(PATCH);
3830}
3831pb_log(2,"DEBUG: exiting pb_list_sfiles: ".Dumper($ptr)."\n");
3832return($ptr);
3833}
3834   
3835#
3836# Return the list of packages we are working on in a non CMS action
3837#
3838sub pb_get_pkg {
3839
3840my @pkgs = ();
3841
3842my ($var) = pb_conf_read("$ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.pb","pbpkg");
3843@pkgs = keys %$var;
3844
3845pb_log(0,"Packages: ".join(',',@pkgs)."\n");
3846return(\@pkgs);
3847}
3848
3849# Manages VM/RM SSH port communication
3850sub pb_get_port {
3851
3852my $port = shift;
3853my $pbos = shift;
3854my $cmt = shift;
3855my $nport;
3856
3857die "No port passed in parameter. Report to dev team\n" if (not defined $port);
3858# key is project on VM, but machine tuple for RM
3859if ($cmt =~ /^RM/i) {
3860    $nport = $port->{"$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'}"};
3861} else {
3862    $nport = $port->{$ENV{'PBPROJ'}};
3863}
3864pb_log(2,"pb_get_port with $nport\n");
3865# Maybe a port was given as parameter so overwrite
3866$nport = "$pbport" if (defined $pbport);
3867# 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
3868if (($cmt ne "Packages") && ($cmt !~ /^RM/i)) {
3869    $nport += $ENV{'PBVMPORT'} if ((defined $pbparallel) && (defined $ENV{'PBVMPORT'}));
3870}
3871pb_log(2,"pb_get_port returns $nport\n");
3872return($nport);
3873}
3874
3875sub pb_set_port { 
3876       
3877my ($pid,$ident) = @_;
3878pb_log(2,"pb_set_port for VM ($pid), id $ident\n");
3879$ENV{'PBVMPORT'} = $ident;
3880pb_log(2,"pb_set_port sets PBVMPORT in env to $ENV{'PBVMPORT'}\n");
3881}
3882
3883sub pb_set_parallel {
3884
3885my $vtype = shift;
3886
3887pb_log(2,"pb_set_parallel vtype: $vtype\n");
3888# Take care of memory size if VM, parallel mode and more than 1 action
3889if ((defined $pbparallel) && ($pbparallel ne 1) && ($vtype eq "vm")) {
3890    eval
3891    {
3892        require Linux::SysInfo;
3893        Linux::SysInfo->import();
3894    };
3895    if ($@) {
3896        # Linux::SysInfo not found
3897        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");
3898    } else {
3899        # Using the memory size
3900        my $si = Linux::SysInfo::sysinfo();
3901        if (not defined $si) {
3902            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");
3903        } else {
3904            # Keep the number of VM whose memory can be allocated
3905            my $ram = $si->{"totalram"}-$si->{"sharedram"}-$si->{"bufferram"};
3906            my $ram2;
3907            my ($vmmem) = pb_conf_get_if("vmmem");
3908
3909            my $v = "default";
3910            if ((defined $vmmem) and (defined $vmmem->{$v})) {
3911                $ram2 = $vmmem->{$v};
3912            } else {
3913                # Default for KVM/QEMU
3914                $ram2 = 128;
3915            }
3916            $pbparallel = sprintf("%d",$ram/$ram2);
3917        }
3918        pb_log(1,"Using $pbparallel processes at a time\n");
3919    }
3920}
3921pb_log(2,"pb_set_parallel returns: $pbparallel\n") if (defined $pbparallel);
3922return($pbparallel);
3923}
3924
3925sub pb_get_sudocmds { 
3926       
3927my $pbos = shift;
3928my %sudocmds;
3929
3930pb_log(2,"pb_get_sudocmds entering with lines:".Dumper(@_)."\n");
3931foreach my $c (split(/;/,$pbos->{'update'}),split(/;/,$pbos->{'install'}),@_) {
3932    pb_log(2,"pb_get_sudocmds analyses $c\n");
3933    next if ($c !~ /^\s*sudo/);
3934    # remove sudo and leading spaces
3935    $c =~ s/^\s*sudo\s+//;
3936    # keep only the command, not the params
3937    $c =~ s/([^\s]+)\s.*$/$1/;
3938    $sudocmds{$c} = "";
3939}
3940pb_log(2,"pb_get_sudocmds returns ".Dumper(keys %sudocmds)."\n");
3941return(keys %sudocmds);
3942}
3943
3944sub pb_sign_pkgs {
3945
3946my $pbos = shift;
3947my $made = shift;
3948
3949pb_log(2,"entering pb_sign_pkg: $made ".Dumper($pbos)."\n");
3950my ($passfile, $passphrase, $passpath) = pb_conf_get_if("pbpassfile","pbpassphrase","pbpasspath");
3951$ENV{'PBPASSPHRASE'} = $passphrase->{$ENV{'PBPROJ'}} if ((not defined $ENV{'PBPASSPHRASE'}) && (defined $passphrase->{$ENV{'PBPROJ'}}));
3952$ENV{'PBPASSFILE'} = $passfile->{$ENV{'PBPROJ'}} if ((not defined $ENV{'PBPASSFILE'})&& (defined $passfile->{$ENV{'PBPROJ'}})) ;
3953$ENV{'PBPASSPATH'} = $passpath->{$ENV{'PBPROJ'}} if ((not defined $ENV{'PBPASSPATH'})&& (defined $passpath->{$ENV{'PBPROJ'}})) ;
3954
3955# Remove extra spaces
3956$made =~ s/\s+/ /g;
3957$made =~ s/^\s//g;
3958$made =~ s/\s$//g;
3959
3960if ($pbos->{'type'} eq "rpm") {
3961    eval
3962    {
3963        require RPM4::Sign;
3964        RPM4::Sign->import();
3965    };
3966    if ($@) {
3967        # RPM4::Sign not found
3968        pb_log(1,"WARNING: Install RPM4::Sign to benefit from automatic package signing.\n");
3969    } else {
3970        return if ((not defined $ENV{'PBPASSPHRASE'}) and (not defined $ENV{'PBPASSFILE'}));
3971        my $sign = RPM4::Sign->new(
3972            passphrase => $ENV{'PBPASSPHRASE'},
3973            name => $ENV{'PBPACKAGER'},
3974            path => $ENV{'PBPASSPATH'},
3975            password_file => $ENV{'PBPASSFILE'}, 
3976        );
3977
3978        pb_log(0,"Signing RPM packages...\n");
3979        pb_log(2,"pb_sign_pkg: pkgs:".Dumper(split(/ /,$made))."\n");
3980        $sign->rpmssign(split(/ /,$made));
3981    }
3982} elsif ($pbos->{'type'} eq "deb") {
3983    my $changes = "";
3984    foreach my $c (split(/ /,$made)) {
3985        $changes .= " $ENV{'PBBUILDDIR'}/$c" if ($c =~ /\.changes$/);
3986    }
3987    my $debsigncmd = pb_check_req("debsign",1);
3988    pb_system("$debsigncmd -m\'$ENV{'PBPACKAGER'}\' $changes","Signing DEB packages");
3989} else {
3990    pb_log(0,"I don't know yet how to sign packages for type $pbos->{'type'}.\nPlease give feedback to dev team\n");
3991}
3992pb_log(2,"exiting pb_sign_pkg\n");
3993}
3994
3995# return list of all distributins supported, coma separated
3996sub pb_get_distros {
3997
3998my $pbos = shift;
3999my $pbtarget = shift;
4000
4001my $tmpl = "$pbos->{'name'}-$pbos->{'version'}-$pbos->{'arch'},";
4002
4003# Get list of distributions for which we need to generate build files if no target
4004if (not defined $pbtarget) {
4005    my @pt = pb_conf_get_if("vmlist","velist","rmlist");
4006    if (defined $pt[0]->{$ENV{'PBPROJ'}}) {
4007        $tmpl .= $pt[0]->{$ENV{'PBPROJ'}};
4008    }
4009    if (defined $pt[1]->{$ENV{'PBPROJ'}}) {
4010        # The 2 lists need to be grouped with a ',' separating them
4011        if ($tmpl ne "") {
4012            $tmpl .= ",";
4013        }
4014        $tmpl .= $pt[1]->{$ENV{'PBPROJ'}} 
4015    }
4016    if (defined $pt[2]->{$ENV{'PBPROJ'}}) {
4017        # The lists needs to be grouped with a ',' separating them
4018        if ($tmpl ne "") {
4019            $tmpl .= ",";
4020        }
4021    $tmpl .= $pt[2]->{$ENV{'PBPROJ'}} 
4022    }
4023}
4024return($tmpl);
4025}   
4026
40271;
Note: See TracBrowser for help on using the repository browser.