source: devel/pb/bin/pb @ 1130

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