#!/usr/bin/perl -w
#
# Project Builder main application
#
# $Id$
#
# Copyright B. Cornec 2007
# Provided under the GPL v2

# Syntax: see at end

use strict 'vars';
use Getopt::Long qw(:config auto_abbrev no_ignore_case);
use Data::Dumper;
use English;
use File::Basename;
use File::Copy;
use File::stat;
use File::Temp qw(tempdir);
use POSIX qw(strftime);
use lib qw (lib);
use ProjectBuilder::Version;
use ProjectBuilder::Base;
use ProjectBuilder::Conf;
use ProjectBuilder::Distribution;
use ProjectBuilder::CMS;
use ProjectBuilder::Env;
use ProjectBuilder::Filter;

# Global variables
my %opts;					# CLI Options
my $action;					# action to realize
my $test = "FALSE";			# Not used
my $force = 0;				# Force VE/VM rebuild
my $option = "";			# Not used
my @pkgs;					# list of packages
my $pbtag;					# Global Tag variable
my $pbver;					# Global Version variable
my $pbscript;				# Name of the script
my %pbver;					# per package
my %pbtag;					# per package
my $pbrev;					# Global REVISION variable
my $pbaccount;				# Login to use to connect to the VM
my $pbport;					# Port to use to connect to the VM
my $newver;					# New version to create
my $iso;					# ISO image for the VM to create

my @date = pb_get_date();
my $pbdate = strftime("%Y-%m-%d", @date);

=pod

=head1 NAME

pb, aka project-builder.org - builds packages for your projects

=head1 DESCRIPTION

pb helps you build various packages directly from your project sources. 
Those sources could be handled by a CMS (Configuration Management System)
such as Subversion, CVS, ... or being a simple reference to a compressed tar file.
It's based on a set of configuration files, a set of provided macros to help 
you keeping build files as generic as possible. For example, a single .spec
file should be required to generate for all rpm based distributions, even 
if you could also have multiple .spec files if required.

=head1 SYNOPSIS

pb [-vhq][-r pbroot][-p project][[-s script -a account -P port][-m mach-1[,...]]][-i iso] <action> [<pkg1> ...]

pb [--verbose][--help][--man][--quiet][--revision pbroot][--project project][[--script script --account account --port port][--machine mach-1[,...]]][--iso iso] <action> [<pkg1> ...]

=head1 OPTIONS

=over 4

=item B<-v|--verbose>

Print a brief help message and exits.

=item B<-q|--quiet>

Do not print any output.

=item B<-h|--help>

Print a brief help message and exits.

=item B<--man>

Prints the manual page and exits.

=item B<-m|--machine machine1[,machine2,...]>

Name of the Virtual Machines (VM) or Virtual Environments (VE) you want to build on (coma separated). 
All if none precised (or use the env variable PBV).

=item B<-s|--script script>

Name of the script you want to execute on the related VMs or VEs.

=item B<-i|--iso iso_image>

Name of the ISO image of the distribution you want to install on the related VMs.

=item B<-a|--account account>

Name of the account to use to connect on the related VMs.

=item B<-P|--port port_number>

Port number to use to connect on the related VMs.\n";

=item B<-p|--project project_name>

Name of the project you're working on (or use the env variable PBPROJ)

=item B<-r|--revision revision>

Path Name of the project revision under the CMS (or use the env variable PBROOT)

=item B<-V|--version new_version>

New version of the project to create based on the current one.

=back 

=head1 ARGUMENTS

<action> can be:

=over 4

=item B<cms2build>

Create tar files for the project under your CMS. 
CMS supported are SVN and CVS
parameters are packages to build
if not using default list

=item B<build2pkg>

Create packages for your running distribution

=item B<cms2pkg>

cms2build + build2pkg

=item B<build2ssh>

Send the tar files to a SSH host

=item B<cms2ssh>

cms2build + build2ssh

=item B<pkg2ssh>

Send the packages built to a SSH host

=item B<build2vm>

Create packages in VMs, launching them if needed
and send those packages to a SSH host once built
VM type supported are QEMU

=item B<build2ve>

Create packages in VEs, creating it if needed
and send those packages to a SSH host once built

=item B<cms2vm>

cms2build + build2vm

=item B<cms2ve>

cms2build + build2ve

=item B<launchvm>

Launch one virtual machine

=item B<launchve>

Launch one virtual environment

=item B<script2vm>

Launch one virtual machine if needed
and executes a script on it

=item B<script2ve>

Execute a script in a virtual environment

=item B<newvm>

Create a new virtual machine

=item B<newve>

Create a new virtual environment

=item B<setupvm>

Setup a virtual machine for pb usage

=item B<setupve>

Setup a virtual environment for pb usage

=item B<newver>

Create a new version of the project derived
from the current one

=item B<newproj>

Create a new project and a template set of
configuration files under pbconf

=back 

<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).

=head1 WEB SITES

The 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/>.

=head1 USER MAILING LIST

None exists for the moment.

=head1 CONFIGURATION FILES

Each pb user may have a configuration in F<$HOME/.pbrc>. The values in this file may overwrite any other configuration file value. 

Here is an example of such a configuration file:

 #
 # Define for each project the URL of its pbconf repository
 # No default option allowed here as they need to be all different
 #
 # URL of the pbconf content
 # This is the format of a classical URL with the extension of additional schema such as 
 # svn+ssh, cvs+ssh, ...
 #
 pbconfurl linuxcoe = cvs+ssh://:ext:bcornec@linuxcoe.cvs.sourceforge.net:/cvsroot/linuxcoe/pbconf

 # This is normaly defined in the project's configuration file
 # Url of the project
 #
 pburl linuxcoe = cvs+ssh://:ext:bcornec@linuxcoe.cvs.sourceforge.net:/cvsroot/linuxcoe
 
 # All these URLs needs to be defined here as the are the entry point 
 # for how to build packages for the project
 #
 pbconfurl pb = svn+ssh://svn.project-builder.org/mondo/svn/pb/pbconf
 pbconfurl mondorescue = svn+ssh://svn.project-builder.org/mondo/svn/project-builder/mondorescue/pbconf
 pbconfurl collectl = svn+ssh://bruno@svn.mondorescue.org/mondo/svn/project-builder/collectl/pbconf
 pbconfurl netperf = svn+ssh://svn.mondorescue.org/mondo/svn/project-builder/netperf/pbconf
 
 # Under that dir will take place everything related to pb
 # If you want to use VMs/chroot/..., then use $ENV{'HOME'} to make it portable
 # to your VMs/chroot/...
 # if not defined then /var/cache
 pbdefdir default = $ENV{'HOME'}/project-builder
 pbdefdir pb = $ENV{'HOME'}
 pbdefdir linuxcoe = $ENV{'HOME'}/LinuxCOE/cvs
 pbdefdir mondorescue = $ENV{'HOME'}/mondo/svn
 
 # pbconfdir points to the directory where the CMS content of the pbconfurl is checked out
 # If not defined, pbconfdir is under pbdefdir/pbproj/pbconf
 pbconfdir linuxcoe = $ENV{'HOME'}/LinuxCOE/cvs/pbconf
 pbconfdir mondorescue = $ENV{'HOME'}/mondo/svn/pbconf
 
 # pbdir points to the directory where the CMS content of the pburl is checked out
 # If not defined, pbdir is under pbdefdir/pbproj
 # Only defined if we have access to the dev of the project
 pbdir linuxcoe = $ENV{'HOME'}/LinuxCOE/cvs
 pbdir mondorescue = $ENV{'HOME'}/mondo/svn
 
 # -daemonize doesn't work with qemu 0.8.2
 vmopt default = -m 384

=head1 AUTHORS

The Project-Builder.org team L<http://trac.project-builder.org/> lead by Bruno Cornec L<mailto:bruno@project-builder.org>.

=head1 COPYRIGHT

Project-Builder.org is distributed under the GPL v2.0 license
described in the file C<COPYING> included with the distribution.

=cut

# ---------------------------------------------------------------------------

# Old syntax
#getopts('a:fhi:l:m:P:p:qr:s:vV:',\%opts);

my ($projectbuilderver,$projectbuilderrev) = pb_version_init();

# Initialize the syntax string

pb_syntax_init("pb (aka project-builder.org) Version $projectbuilderver-$projectbuilderrev\n");

GetOptions("help|?|h" => \$opts{'h'}, 
		"man" => \$opts{'man'},
		"verbose|v+" => \$opts{'v'},
		"quiet|q" => \$opts{'q'},
		"log-files|l=s" => \$opts{'l'},
		"force|f" => \$opts{'f'},
		"account|a=s" => \$opts{'a'},
		"revision|r=s" => \$opts{'r'},
		"script|s=s" => \$opts{'s'},
		"machines|mock|m=s" => \$opts{'m'},
		"port|P=i" => \$opts{'P'},
		"project|p=s" => \$opts{'p'},
		"iso|i=s" => \$opts{'i'},
		"version|V=s" => \$opts{'V'},
) || pb_syntax(-1,0);

if (defined $opts{'h'}) {
	pb_syntax(0,1);
}
if (defined $opts{'man'}) {
	pb_syntax(0,2);
}
if (defined $opts{'v'}) {
	$debug = $opts{'v'};
}
if (defined $opts{'f'}) {
	$force=1;
}
if (defined $opts{'q'}) {
	$debug=-1;
}
if (defined $opts{'l'}) {
	open(LOG,"> $opts{'l'}") || die "Unable to log to $opts{'l'}: $!";
	$LOG = \*LOG;
	$debug = 0  if ($debug == -1);
	}
pb_log_init($debug, $LOG);

# Handle root of the project if defined
if (defined $opts{'r'}) {
	$ENV{'PBROOTDIR'} = $opts{'r'};
}
# Handle virtual machines if any
if (defined $opts{'m'}) {
	$ENV{'PBV'} = $opts{'m'};
}
if (defined $opts{'s'}) {
	$pbscript = $opts{'s'};
}
if (defined $opts{'a'}) {
	$pbaccount = $opts{'a'};
	die "option -a requires a -s script option" if (not defined $pbscript);
}
if (defined $opts{'P'}) {
	$pbport = $opts{'P'};
}
if (defined $opts{'V'}) {
	$newver = $opts{'V'};
}
if (defined $opts{'i'}) {
	$iso = $opts{'i'};
}

# Get Action
$action = shift @ARGV;
die pb_syntax(-1,1) if (not defined $action);

my ($filteredfiles, $supfiles, $defpkgdir, $extpkgdir);
my $pbinit = undef;
$pbinit = 1 if ($action =~ /^newproj$/);

# Handles project name if any
# And get global params
($filteredfiles, $supfiles, $defpkgdir, $extpkgdir) = pb_env_init($opts{'p'},$pbinit,$action);

pb_log(0,"Project: $ENV{'PBPROJ'}\n");
pb_log(0,"Action: $action\n");

# Act depending on action
if ($action =~ /^cms2build$/) {
	pb_cms2build();
} elsif ($action =~ /^build2pkg$/) {
	pb_build2pkg();
} elsif ($action =~ /^cms2pkg$/) {
	pb_cms2build();
	pb_build2pkg();
} elsif ($action =~ /^build2ssh$/) {
	pb_build2ssh();
} elsif ($action =~ /^cms2ssh$/) {
	pb_cms2build();
	pb_build2ssh();
} elsif ($action =~ /^pkg2ssh$/) {
	pb_pkg2ssh();
} elsif ($action =~ /^build2ve$/) {
	pb_build2v("ve");
} elsif ($action =~ /^build2vm$/) {
	pb_build2v("vm");
} elsif ($action =~ /^cms2ve$/) {
	pb_cms2build();
	pb_build2v("ve");
} elsif ($action =~ /^cms2vm$/) {
	pb_cms2build();
	pb_build2v("vm");
} elsif ($action =~ /^launchvm$/) {
	pb_launchv("vm",$ENV{'PBV'},0);
} elsif ($action =~ /^launchve$/) {
	pb_launchv("ve",$ENV{'PBV'},0);
} elsif ($action =~ /^script2vm$/) {
	pb_script2v($pbscript,"vm");
} elsif ($action =~ /^script2ve$/) {
	pb_script2v($pbscript,"ve");
} elsif ($action =~ /^newver$/) {
	pb_newver();
} elsif ($action =~ /^newve$/) {
	pb_launchv("ve",$ENV{'PBV'},1);
} elsif ($action =~ /^newvm$/) {
	pb_launchv("vm",$ENV{'PBV'},1);
} elsif ($action =~ /^setupve$/) {
	pb_setup_v("ve");
} elsif ($action =~ /^setupvm$/) {
	pb_setup_v("vm");
} elsif ($action =~ /^newproj$/) {
	# Nothing to do - already done in pb_env_init
} elsif ($action =~ /^clean$/) {
} else {
	pb_log(0,"\'$action\' is not available\n");
	pb_syntax(-2,1);
}

sub pb_cms2build {

	my $pkg = pb_cms_get_pkg($defpkgdir,$extpkgdir);
	my @pkgs = @$pkg;
	my %pkgs;

	my ($scheme, $uri) = pb_cms_init($pbinit);

	my ($pkgv, $pkgt) = pb_conf_get_if("pkgver","pkgtag");

	# declare packager and repo for filtering
	my ($tmp1, $tmp2) = pb_conf_get("pbpackager","pbrepo");
	$ENV{'PBPACKAGER'} = $tmp1->{$ENV{'PBPROJ'}};
	$ENV{'PBREPO'} = $tmp2->{$ENV{'PBPROJ'}};

	foreach my $pbpkg (@pkgs) {
		$ENV{'PBPKG'} = $pbpkg;
		if ((defined $pkgv) && (defined $pkgv->{$pbpkg})) {
			$pbver = $pkgv->{$pbpkg};
		} else {
			$pbver = $ENV{'PBPROJVER'};
		}
		if ((defined $pkgt) && (defined $pkgt->{$pbpkg})) {
			$pbtag = $pkgt->{$pbpkg};
		} else {
			$pbtag = $ENV{'PBPROJTAG'};
		}

		$pbrev = $ENV{'PBREVISION'};
		pb_log(0,"\n");
		pb_log(0,"Management of $pbpkg $pbver-$pbtag (rev $pbrev)\n");
		die "Unable to get env var PBDESTDIR" if (not defined $ENV{'PBDESTDIR'});
		# Clean up dest if necessary. The export will recreate it
		my $dest = "$ENV{'PBDESTDIR'}/$pbpkg-$pbver";
		pb_rm_rf($dest) if (-d $dest);

		# Export CMS tree for the concerned package to dest
		# And generate some additional files
		$OUTPUT_AUTOFLUSH=1;

		# computes in which dir we have to work
		my $dir = $defpkgdir->{$pbpkg};
		$dir = $extpkgdir->{$pbpkg} if (not defined $dir);
		pb_log(2,"def:".Dumper($defpkgdir)." ext: ".Dumper($extpkgdir)." \n");

		# Exporting from CMS
		pb_cms_export($uri,"$ENV{'PBDIR'}/$dir",$dest);

		# Generated fake content for test versions to speed up stuff
		my ($testver) = pb_conf_get_if("testver");
		my $chglog;

		if ((defined $testver) && (defined $testver->{$ENV{'PBPROJ'}}) && ($testver->{$ENV{'PBPROJ'}} =~ /true/i)) {
			if (! -f "$dest/NEWS") {
				open(NEWS,"> $dest/NEWS") || die "Unable to create $dest/NEWS";
				close(NEWS);
			}
			open(CL,"> $dest/ChangeLog") || die "Unable to create $dest/ChangeLog";
			close(CL);
			open(CL,"> $dest/$ENV{'PBCMSLOGFILE'}") || die "Unable to create $dest/$ENV{'PBCMSLOGFILE'}";
			close(CL);
			$chglog = undef;
		} else {

			# Get project info on authors and log file
			$chglog = "$ENV{'PBROOTDIR'}/$pbpkg/pbcl";
			$chglog = "$ENV{'PBROOTDIR'}/pbcl" if (! -f $chglog);
			$chglog = undef if (! -f $chglog);

			my $authors = "$ENV{'PBROOTDIR'}/$pbpkg/pbauthors";
			$authors = "$ENV{'PBROOTDIR'}/pbauthors" if (! -f $authors);
			$authors = "/dev/null" if (! -f $authors);

			# Extract cms log history and store it
			if ((defined $chglog) && (! -f "$dest/NEWS")) {
				pb_log(2,"Generating NEWS file from $chglog\n");
				copy($chglog,"$dest/NEWS") || die "Unable to create $dest/NEWS";
			}
			pb_cms_log($scheme,"$ENV{'PBDIR'}/$dir",$dest,$chglog,$authors);
		}

		my %build;
		my @pt;
		my $tmpl = "";

		@pt = pb_conf_get_if("vmlist","velist");
		if (defined $pt[0]->{$ENV{'PBPROJ'}}) {
			$tmpl .= $pt[0]->{$ENV{'PBPROJ'}};
		}
		if (defined $pt[1]->{$ENV{'PBPROJ'}}) {
			# the 2 lists needs to be grouped with a ',' separated them
			if ($tmpl ne "") {
				$tmpl .= ",";
			}
			$tmpl .= $pt[1]->{$ENV{'PBPROJ'}} 
		}
		foreach my $d (split(/,/,$tmpl)) {
			my ($name,$ver,$arch) = split(/-/,$d);
			chomp($arch);
			my ($ddir, $dver, $dfam, $dtype, $pbsuf) = pb_distro_init($name,$ver);
			pb_log(2,"DEBUG: distro tuple: ".Dumper($ddir, $dver, $dfam, $dtype, $pbsuf)."\n");
			pb_log(2,"DEBUG Filtering PBDATE => $pbdate, PBTAG => $pbtag, PBVER => $pbver\n");

			# Filter build files from the less precise up to the most with overloading
			# Filter all files found, keeping the name, and generating in dest

			# Find all build files first relatively to PBROOTDIR
			# Find also all specific files referenced in the .pb conf file
			my %bfiles = ();
			my %pkgfiles = ();
			$build{"$ddir-$dver"} = "yes";

			if (-d "$ENV{'PBROOTDIR'}/$pbpkg/$dtype") {
				pb_list_bfiles("$ENV{'PBROOTDIR'}/$pbpkg/$dtype",$pbpkg,\%bfiles,\%pkgfiles,$supfiles);
			} elsif (-d "$ENV{'PBROOTDIR'}/$pbpkg/$dfam") {
				pb_list_bfiles("$ENV{'PBROOTDIR'}/$pbpkg/$dfam",$pbpkg,\%bfiles,\%pkgfiles,$supfiles);
			} elsif (-d "$ENV{'PBROOTDIR'}/$pbpkg/$ddir") {
				pb_list_bfiles("$ENV{'PBROOTDIR'}/$pbpkg/$ddir",$pbpkg,\%bfiles,\%pkgfiles,$supfiles);
			} elsif (-d "$ENV{'PBROOTDIR'}/$pbpkg/$ddir-$dver") {
				pb_list_bfiles("$ENV{'PBROOTDIR'}/$pbpkg/$ddir-$dver",$pbpkg,\%bfiles,\%pkgfiles,$supfiles);
			} else {
				$build{"$ddir-$dver"} = "no";
				next;
			}
			pb_log(2,"DEBUG bfiles: ".Dumper(\%bfiles)."\n");

			# Get all filters to apply
			my $ptr = pb_get_filters($pbpkg, $dtype, $dfam, $ddir, $dver);

			# Apply now all the filters on all the files concerned
			# destination dir depends on the type of file
			if (defined $ptr) {
				foreach my $f (values %bfiles,values %pkgfiles) {
					pb_filter_file_pb("$ENV{'PBROOTDIR'}/$f",$ptr,"$dest/pbconf/$ddir-$dver/".basename($f),$dtype,$pbsuf,$pbpkg,$pbver,$pbtag,$pbrev,$pbdate,$defpkgdir,$extpkgdir,$ENV{'PBPACKAGER'},$chglog,$ENV{'PBPROJ'},$ENV{'PBREPO'});
				}
			}
		}
		my @found;
		my @notfound;
		foreach my $b (keys %build) {
			push @found,$b if ($build{$b} =~ /yes/);
			push @notfound,$b if ($build{$b} =~ /no/);
		}
		pb_log(0,"Build files generated for ".join(',',@found)."\n");
		pb_log(0,"No Build files found for ".join(',',@notfound)."\n") if (@notfound);
		# Get the generic filter (all.pbf) and 
		# apply those to the non-build files including those
		# generated by pbinit if applicable

		# Get only all.pbf filter
		my $ptr = pb_get_filters($pbpkg);

		my $liste ="";
		if (defined $filteredfiles->{$pbpkg}) {
			foreach my $f (split(/,/,$filteredfiles->{$pbpkg})) {
				pb_filter_file_inplace($ptr,"$dest/$f",$pbpkg,$pbver,$pbtag,$pbrev,$pbdate,$ENV{'PBPACKAGER'},$ENV{'PBPROJ'},$ENV{'PBREPO'});
				$liste = "$f $liste";
			}
		}
		pb_log(2,"Files ".$liste."have been filtered\n");

		# Prepare the dest directory for archive
		if (-x "$ENV{'PBROOTDIR'}/$pbpkg/pbinit") {
			pb_filter_file("$ENV{'PBROOTDIR'}/$pbpkg/pbinit",$ptr,"$ENV{'PBTMP'}/pbinit",$pbpkg,$pbver,$pbtag,$pbrev,$pbdate,$ENV{'PBPACKAGER'},$ENV{'PBPROJ'},$ENV{'PBREPO'});
			chmod 0755,"$ENV{'PBTMP'}/pbinit";
			pb_system("cd $dest ; $ENV{'PBTMP'}/pbinit","Executing init script from $ENV{'PBROOTDIR'}/$pbpkg/pbinit");
		}

		# Archive dest dir
		chdir "$ENV{'PBDESTDIR'}" || die "Unable to change dir to $ENV{'PBDESTDIR'}";
		# Possibility to look at PBSRC to guess more the filename
		pb_system("tar cfz $pbpkg-$pbver.tar.gz $pbpkg-$pbver","Creating $pbpkg tar files compressed");
		pb_log(0,"Under $ENV{'PBDESTDIR'}/$pbpkg-$pbver.tar.gz\n");

		# Keep track of version-tag per pkg
		$pkgs{$pbpkg} = "$pbver-$pbtag";

		# Final cleanup
		pb_rm_rf($dest) if (-d $dest);
	}

	# Keep track of per package version
	pb_log(2,"DEBUG pkgs: ".Dumper(%pkgs)."\n");
	open(PKG,"> $ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.pb") || die "Unable to create $ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.pb";
	foreach my $pbpkg (@pkgs) {
		print PKG "pbpkg $pbpkg = $pkgs{$pbpkg}\n";
	}
	close(PKG);

	# Keep track of what is generated by default
	# We need to store the dir and info on version-tag
	# Base our content on the existing .pb file
	copy("$ENV{'PBROOTDIR'}/$ENV{'PBPROJ'}.pb","$ENV{'PBDESTDIR'}/pbrc");
	open(LAST,">> $ENV{'PBDESTDIR'}/pbrc") || die "Unable to create $ENV{'PBDESTDIR'}/pbrc";
	print LAST "pbroot $ENV{'PBPROJ'} = $ENV{'PBROOTDIR'}\n";
	print LAST "pbprojver $ENV{'PBPROJ'} = $ENV{'PBPROJVER'}\n";
	print LAST "pbprojtag $ENV{'PBPROJ'} = $ENV{'PBPROJTAG'}\n";
	print LAST "pbpackager $ENV{'PBPROJ'} = $ENV{'PBPACKAGER'}\n";
	close(LAST);
}

sub pb_build2pkg {

	# Get the running distro to build on
	my ($ddir, $dver, $dfam, $dtype, $pbsuf) = pb_distro_init();
	pb_log(2,"DEBUG: distro tuple: ".join(',',($ddir, $dver, $dfam, $dtype, $pbsuf))."\n");

	# Get list of packages to build
	# Get content saved in cms2build
	my $ptr = pb_get_pkg();
	@pkgs = @$ptr;

	my ($pkg) = pb_conf_read("$ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.pb","pbpkg");
	$pkg = { } if (not defined $pkg);

	chdir "$ENV{'PBBUILDDIR'}";
	my $made = ""; # pkgs made during build
	foreach my $pbpkg (@pkgs) {
		my $vertag = $pkg->{$pbpkg};
		# get the version of the current package - maybe different
		($pbver,$pbtag) = split(/-/,$vertag);

		my $src="$ENV{'PBDESTDIR'}/$pbpkg-$pbver.tar.gz";
		pb_log(2,"Source file: $src\n");

		pb_log(2,"Working directory: $ENV{'PBBUILDDIR'}\n");
		if ($dtype eq "rpm") {
			foreach my $d ('RPMS','SRPMS','SPECS','SOURCES','BUILD') {
				if (! -d "$ENV{'PBBUILDDIR'}/$d") {
				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";
				}
			}

			# Remove in case a previous link/file was there
			unlink "$ENV{'PBBUILDDIR'}/SOURCES/".basename($src);
			symlink "$src","$ENV{'PBBUILDDIR'}/SOURCES/".basename($src) || die "Unable to symlink $src in $ENV{'PBBUILDDIR'}/SOURCES";
			# We need to first extract the spec file
			my @specfile;
			@specfile = pb_extract_build_files($src,"$pbpkg-$pbver/pbconf/$ddir-$dver/","$ENV{'PBBUILDDIR'}/SPECS");

			pb_log(2,"specfile: ".Dumper(\@specfile)."\n");
			# set LANGUAGE to check for correct log messages
			$ENV{'LANGUAGE'}="C";
			foreach my $f (@specfile) {
				if ($f =~ /\.spec$/) {
					pb_system("rpmbuild --define \'packager $ENV{'PBPACKAGER'}\' --define \"_topdir $ENV{'PBBUILDDIR'}\" -ba $f","Building package with $f under $ENV{'PBBUILDDIR'}");
					last;
				}
			}
			$made="$made RPMS/*/$pbpkg-$pbver-$pbtag$pbsuf.*.rpm SRPMS/$pbpkg-$pbver-$pbtag$pbsuf.src.rpm";
			if (-f "/usr/bin/rpmlint") {
				pb_system("rpmlint $made","Checking validity of rpms with rpmlint");
			}
		} elsif ($dtype eq "deb") {
			chdir "$ENV{'PBBUILDDIR'}" || die "Unable to chdir to $ENV{'PBBUILDDIR'}";
			pb_system("tar xfz $src","Extracting sources");

			chdir "$pbpkg-$pbver" || die "Unable to chdir to $pbpkg-$pbver";
			pb_rm_rf("debian");
			symlink "pbconf/$ddir-$dver","debian" || die "Unable to symlink to pbconf/$ddir-$dver";
			chmod 0755,"debian/rules";
			pb_system("dpkg-buildpackage -us -uc -rfakeroot","Building package");
			$made="$made $pbpkg"."_*.deb $pbpkg"."_*.dsc $pbpkg"."_*.tar.gz";
			if (-f "/usr/bin/lintian") {
				pb_system("lintian $made","Checking validity of debs with lintian");
			}
		} elsif ($dtype eq "ebuild") {
			my @ebuildfile;
			# For gentoo we need to take pb as subsystem name
			# We put every apps here under sys-apps. hope it's correct
			# We use pb's home dir in order to have a single OVERLAY line
			my $tmpd = "$ENV{'HOME'}/portage/pb/sys-apps/$pbpkg";
			pb_mkdir_p($tmpd) if (! -d "$tmpd");
			pb_mkdir_p("$ENV{'HOME'}/portage/distfiles") if (! -d "$ENV{'HOME'}/portage/distfiles");

			# We need to first extract the ebuild file 
			@ebuildfile = pb_extract_build_files($src,"$pbpkg-$pbver/pbconf/$ddir-$dver/","$tmpd");

			# Prepare the build env for gentoo
			my $found = 0;
			my $pbbd = $ENV{'HOME'};
			$pbbd =~ s|/|\\/|g;
			if (-r "/etc/make.conf") {
				open(MAKE,"/etc/make.conf");
				while (<MAKE>) {
					$found = 1 if (/$pbbd\/portage/);
				}
				close(MAKE);
			}
			if ($found == 0) {
				pb_system("sudo sh -c 'echo PORTDIR_OVERLAY=\"$ENV{'HOME'}/portage\" >> /etc/make.conf'");
			}
			#$found = 0;
			#if (-r "/etc/portage/package.keywords") {
			#open(KEYW,"/etc/portage/package.keywords");
			#while (<KEYW>) {
			#$found = 1 if (/portage\/pb/);
			#}
			#close(KEYW);
			#}
			#if ($found == 0) {
			#pb_system("sudo sh -c \"echo portage/pb >> /etc/portage/package.keywords\"");
			#}

			# Build
			foreach my $f (@ebuildfile) {
				if ($f =~ /\.ebuild$/) {
					move($f,"$tmpd/$pbpkg-$pbver.ebuild");
					pb_system("cd $tmpd ; ebuild $pbpkg-$pbver.ebuild clean ; ebuild $pbpkg-$pbver.ebuild digest ; ebuild $pbpkg-$pbver.ebuild package");
					# Now move it where pb expects it
					pb_mkdir_p("$ENV{'PBBUILDDIR'}/portage/pb/sys-apps/$pbpkg");
					move("$tmpd/$pbpkg-$pbver.ebuild","$ENV{'PBBUILDDIR'}/portage/pb/sys-apps/$pbpkg");
				}
			}

			$made="$made portage/pb/sys-apps/$pbpkg/$pbpkg-$pbver.ebuild";
		} elsif ($dtype eq "slackware") {
			$made="$made $pbpkg/$pbpkg-$pbver-*-$pbtag.tgz";

			chdir "$ENV{'PBBUILDDIR'}" || die "Unable to chdir to $ENV{'PBBUILDDIR'}";
			pb_system("tar xfz $src","Extracting sources");
			chdir "$pbpkg-$pbver" || die "Unable to chdir to $pbpkg-$pbver";
			symlink "pbconf/$ddir-$dver","install" || die "Unable to symlink to pbconf/$ddir-$dver";
			if (-x "install/pbslack") {
				pb_system("./install/pbslack","Building package");
				pb_system("sudo /sbin/makepkg -p -l y -c y $pbpkg","Packaging $pbpkg");
			}
		} else {
			die "Unknown dtype format $dtype";
		}
	}
	# Keep track of what is generated so that we can get them back from VMs
	open(KEEP,"> $ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}") || die "Unable to create $ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}";
	print KEEP "$made\n";
	close(KEEP);
}

sub pb_build2ssh {
	pb_send2target("Sources");
}

sub pb_pkg2ssh {
	pb_send2target("Packages");
}

# By default deliver to the the public site hosting the 
# ftp structure (or whatever) or a VM/VE
sub pb_send2target {

	my $cmt = shift;
	my $v = shift || undef;
	my $vmexist = shift || 0;			# 0 is FALSE
	my $vmpid = shift || 0;				# 0 is FALSE

	my $host = "sshhost";
	my $login = "sshlogin";
	my $dir = "sshdir";
	my $port = "sshport";
	my $conf = "sshconf";
	my $rebuild = "sshrebuild";
	my $tmout = "vmtmout";
	my $path = "vmpath";
	if (($cmt eq "vm") || ($cmt eq "Script")) {
		$login = "vmlogin";
		$dir = "pbdefdir";
		$tmout = "vmtmout";
		$rebuild = "vmrebuild";
		# Specific VM
		$host = "vmhost";
		$port = "vmport";
	} elsif ($cmt eq "ve") {
		$login = "velogin";
		$dir = "pbdefdir";
		$tmout = "vetmout";
		# Specific VE
		$path = "vepath";
		$conf = "veconf";
		$rebuild = "verebuild";
	}
	my $cmd = "";

	my $ptr = pb_get_pkg();
	@pkgs = @$ptr;

	# Get the running distro to consider
	my ($odir,$over,$oarch) = (undef, undef, undef);
	if (defined $v) {
		($odir,$over,$oarch) = split(/-/,$v);
	}
	my ($ddir, $dver, $dfam, $dtype, $pbsuf) = pb_distro_init($odir,$over);
	pb_log(2,"DEBUG: distro tuple: ".join(',',($ddir, $dver, $dfam, $dtype, $pbsuf))."\n");

	# Get list of packages to build
	# Get content saved in cms2build
	my ($pkg) = pb_conf_read("$ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.pb","pbpkg");
	$pkg = { } if (not defined $pkg);

	my $src = "";
	chdir "$ENV{'PBBUILDDIR'}";
	foreach my $pbpkg (@pkgs) {
		my $vertag = $pkg->{$pbpkg};
		# get the version of the current package - maybe different
		($pbver,$pbtag) = split(/-/,$vertag);

		if (($cmt eq "Sources") || ($cmt eq "vm") || ($cmt eq "ve")) {
			$src = "$src $ENV{'PBDESTDIR'}/$pbpkg-$pbver.tar.gz";
			if ($cmd eq "") {
				$cmd = "ln -sf $pbpkg-$pbver.tar.gz $pbpkg-latest.tar.gz";
			} else {
				$cmd = "$cmd ; ln -sf $pbpkg-$pbver.tar.gz $pbpkg-latest.tar.gz";
			}
		}
	}
	# Adds conf file for availability of conf elements
	pb_conf_add("$ENV{'PBROOTDIR'}/$ENV{'PBPROJ'}.pb");

	if (($cmt eq "vm") || ($cmt eq "ve")) {
		$src="$src $ENV{'PBROOTDIR'}/$ENV{'PBPROJ'}.pb $ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.pb $ENV{'PBETC'} $ENV{'PBDESTDIR'}/pbrc";
	} elsif ($cmt eq "Script") {
		# Nothing special to do
	} elsif ($cmt eq "Packages") {
		# Get package list from file made during build2pkg
		open(KEEP,"$ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}") || die "Unable to read $ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}";
		$src = <KEEP>;
		chomp($src);
		close(KEEP);

	}
	# Systematically adds the pbscript
	$src="$src $ENV{'PBDESTDIR'}/pbscript";
	# Remove potential leading spaces (cause problem with basename)
	$src =~ s/^ *//;
	my $basesrc = "";
	foreach my $i (split(/ +/,$src)) {
		$basesrc .= " ".basename($i);
	}

	pb_log(0,"Sources handled ($cmt): $src\n");
	pb_log(2,"values: ".Dumper(($host,$login,$dir,$port,$tmout,$rebuild,$path,$conf))."\n");
	my ($sshhost,$sshlogin,$sshdir,$sshport,$vtmout,$vepath) = pb_conf_get($host,$login,$dir,$port,$tmout,$path);
	my ($vrebuild,$veconf) = pb_conf_get_if($rebuild,$conf);
	pb_log(2,"ssh: ".Dumper(($sshhost,$sshlogin,$sshdir,$sshport,$vtmout,$vrebuild,$vepath,$veconf))."\n");
	# Not mandatory
	my ($testver) = pb_conf_get_if("testver");

	my $mac;
	# Useless for VE
	if ($cmt ne "ve") {
		$mac = "$sshlogin->{$ENV{'PBPROJ'}}\@$sshhost->{$ENV{'PBPROJ'}}";
		# Overwrite account value if passed as parameter
		$mac = "$pbaccount\@$sshhost->{$ENV{'PBPROJ'}}" if (defined $pbaccount);
		pb_log(2, "DEBUG: pbaccount: $pbaccount => mac: $mac\n") if (defined $pbaccount);
	}

	my $tdir;
	my $bdir;
	if (($cmt eq "Sources") || ($cmt eq "Script")) {
		$tdir = "$sshdir->{$ENV{'PBPROJ'}}/src";
		if ((defined $testver) && (defined $testver->{$ENV{'PBPROJ'}}) && ($testver->{$ENV{'PBPROJ'}} =~ /true/i)) {
			# This is a test pkg => target dir is under test
			$tdir = "$sshdir->{$ENV{'PBPROJ'}}/test/src";
		}
	} elsif (($cmt eq "vm") || ($cmt eq "ve")) {
		$tdir = $sshdir->{$ENV{'PBPROJ'}}."/$ENV{'PBPROJ'}/delivery";
		$bdir = $sshdir->{$ENV{'PBPROJ'}}."/$ENV{'PBPROJ'}/build";
		# Remove a potential $ENV{'HOME'} as bdir should be relative to pb's home
		$bdir =~ s|\$ENV.+\}/||;
	} elsif ($cmt eq "Packages") {
		$tdir = "$sshdir->{$ENV{'PBPROJ'}}/$ddir/$dver";

		if ((defined $testver) && (defined $testver->{$ENV{'PBPROJ'}}) && ($testver->{$ENV{'PBPROJ'}} =~ /true/i)) {
			# This is a test pkg => target dir is under test
			$tdir = "$sshdir->{$ENV{'PBPROJ'}}/test/$ddir/$dver";
		}

		my $repodir = $tdir;
		$repodir =~ s|^$sshdir->{$ENV{'PBPROJ'}}/||;

		my ($pbrepo) = pb_conf_get("pbrepo");

		# Repository management
		open(PBS,"> $ENV{'PBDESTDIR'}/pbscript") || die "Unable to create $ENV{'PBDESTDIR'}/pbscript";
		if ($dtype eq "rpm") {
			# Also make a pbscript to generate yum/urpmi bases
			print PBS << "EOF";
#!/bin/bash
# Prepare a script to ease yum setup
cat > $ENV{'PBPROJ'}.repo << EOT
[$ENV{'PBPROJ'}]
name=$ddir $dver - $ENV{'PBPROJ'} Vanilla Packages
baseurl=$pbrepo->{$ENV{'PBPROJ'}}/$repodir
enabled=1
gpgcheck=0
EOT
chmod 644 $ENV{'PBPROJ'}.repo

# Clean up old repo content
rm -rf headers/ repodata/
# Create yum repo
yum-arch .
# Create repodata
createrepo .
EOF
			if ($dfam eq "md") {
				# For Mandriva add urpmi management
				print PBS << "EOF";
# Prepare a script to ease urpmi setup
cat > $ENV{'PBPROJ'}.addmedia << EOT
urpmi.addmedia $ENV{'PBPROJ'} $pbrepo->{$ENV{'PBPROJ'}}/$repodir with hdlist.cz
EOT
chmod 755 $ENV{'PBPROJ'}.addmedia

# Clean up old repo content
rm -f hdlist.cz
# Create urpmi repo
genhdlist .
EOF
			}
		} elsif ($dtype eq "deb") {
			# Also make a pbscript to generate apt bases
		}
		close(PBS);

	} else {
		return;
	}

	# Useless for VE
	my $nport;
	if ($cmt ne "ve") {
		$nport = $sshport->{$ENV{'PBPROJ'}};
		$nport = "$pbport" if (defined $pbport);
	}

	# Remove a potential $ENV{'HOME'} as tdir should be relative to pb's home
	$tdir =~ s|\$ENV.+\}/||;

	my $tm = $vtmout->{$ENV{'PBPROJ'}};

	# ssh communication if not VE
	# should use a hash instead...
	my ($shcmd,$cpcmd,$cptarget,$cp2target);
	if ($cmt ne "ve") {
		my $keyfile = pb_ssh_get(0);
		$shcmd = "ssh -i $keyfile -q -o UserKnownHostsFile=/dev/null -p $nport $mac";
		$cpcmd = "scp -i $keyfile -p -o UserKnownHostsFile=/dev/null -P $nport";
		$cptarget = "$mac:$tdir";
		if ($cmt eq "vm") {
			$cp2target = "$mac:$bdir";
		}
	} else {
		my $tp = $vepath->{$ENV{'PBPROJ'}};
		$shcmd = "sudo chroot $tp/$v /bin/su - $sshlogin->{$ENV{'PBPROJ'}} -c ";
		$cpcmd = "cp -a ";
		$cptarget = "$tp/$tdir";
		$cp2target = "$tp/$bdir";
	}

	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");
	pb_system("cd $ENV{'PBBUILDDIR'} ; $cpcmd $src $cptarget 2> /dev/null","$cmt delivery in $cptarget");
	# For VE we need to change the owner manually - To be tested if needed
	#if ($cmt eq "ve") {
	#pb_system("cd $cptarget ; sudo chown -R $sshlogin->{$ENV{'PBPROJ'}} .","$cmt chown in $cptarget to $sshlogin->{$ENV{'PBPROJ'}}");
	#}
	pb_system("$shcmd \"echo \'cd $tdir ; if [ -f pbscript ]; then ./pbscript; fi ; rm -f ./pbscript\' | bash\"","Executing pbscript on $cptarget if needed");
	if (($cmt eq "vm") || ($cmt eq "ve")) {
		# Get back info on pkg produced, compute their name and get them from the VM
		pb_system("$cpcmd $cp2target/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'} $ENV{'PBBUILDDIR'} 2> /dev/null","Get package names in $cp2target");
		open(KEEP,"$ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}") || die "Unable to read $ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}";
		my $src = <KEEP>;
		chomp($src);
		close(KEEP);
		$src =~ s/^ *//;
		pb_mkdir_p("$ENV{'PBBUILDDIR'}/$odir/$over");
		# Change pgben to make the next send2target happy
		my $made = "";
		open(KEEP,"> $ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}") || die "Unable to write $ENV{'PBBUILDDIR'}/pbgen-$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}";
		foreach my $p (split(/ +/,$src)) {
			my $j = basename($p);
			pb_system("$cpcmd $cp2target/\'$p\' $ENV{'PBBUILDDIR'}/$odir/$over 2> /dev/null","Package recovery of $j in $cp2target");
			$made="$made $odir/$over/$j" if (($dtype ne "rpm") || ($j !~ /.src.rpm$/));
		}
		print KEEP "$made\n";
		close(KEEP);
		pb_system("$shcmd \"rm -rf $tdir $bdir\"","$cmt cleanup");

		# We want to send them to the ssh account so overwrite what has been done before
		undef $pbaccount;
		pb_log(2,"Before sending pkgs, vmexist: $vmexist, vmpid: $vmpid\n");
		pb_send2target("Packages",$odir."-".$over."-".$oarch,$vmexist,$vmpid);
		if ((! $vmexist) && ($cmt eq "vm")) {
			pb_system("$shcmd \"sudo /sbin/halt -p \"; sleep $tm ; echo \'if [ -d /proc/$vmpid ]; then kill -9 $vmpid; fi \' | bash ; sleep 10","VM $v halt (pid $vmpid)");
		}
		pb_rm_rf("$ENV{'PBBUILDDIR'}/$odir");
	}
}

sub pb_script2v {
	my $pbscript=shift;
	my $vtype=shift;

	# Prepare the script to be executed on the VM
	# in $ENV{'PBDESTDIR'}/pbscript
	if ((defined $pbscript ) && ($pbscript ne "$ENV{'PBDESTDIR'}/pbscript")) {
		copy($pbscript,"$ENV{'PBDESTDIR'}/pbscript") || die "Unable to create $ENV{'PBDESTDIR'}/pbscript";
		chmod 0755,"$ENV{'PBDESTDIR'}/pbscript";
	}

	my ($vm,$all) = pb_get_v($vtype);
	my ($vmexist,$vmpid) = (undef,undef);

	foreach my $v (@$vm) {
		# Launch the VM/VE
		if ($vtype eq "vm") {
			($vmexist,$vmpid) = pb_launchv($vtype,$v,0);

			# Skip that VM if something went wrong
			next if (($vmpid == 0) && ($vmexist ==0));
		}

		# Gather all required files to send them to the VM 
		# and launch the build through pbscript
		pb_send2target("Script","$v",$vmexist,$vmpid);

	}
}

sub pb_launchv {
	my $vtype = shift;
	my $v = shift;
	my $create = shift || 0;		# By default do not create a VM

	die "No VM/VE defined, unable to launch" if (not defined $v);
	# Keep only the first VM in case many were given
	$v =~ s/,.*//;

	# Which is our local arch ? (standardize on i386 for those platforms)
	my $arch = `uname -m`;
	chomp($arch);
	$arch =~ s/i.86/i386/;

	# Launch the VMs/VEs
	if ($vtype eq "vm") {
		die "-i iso parameter needed" if (((not defined $iso) || ($iso eq "")) && ($create != 0));

		my ($ptr,$vmopt,$vmpath,$vmport,$vmtmout,$vmsize) = pb_conf_get("vmtype","vmopt","vmpath","vmport","vmtmout","vmsize");

		my $vmtype = $ptr->{$ENV{'PBPROJ'}};
		if (not defined $ENV{'PBVMOPT'}) {
			$ENV{'PBVMOPT'} = "";
		}
		if (defined $vmopt->{$ENV{'PBPROJ'}}) {
			$ENV{'PBVMOPT'} .= " $vmopt->{$ENV{'PBPROJ'}}" if ($ENV{'PBVMOPT'} !~ / $vmopt->{$ENV{'PBPROJ'}}/);
		}
		my $nport = $vmport->{$ENV{'PBPROJ'}};
		$nport = "$pbport" if (defined $pbport);
	
		my $cmd;
		my $vmcmd;		# has to be used for pb_check_ps
		my $vmm;		# has to be used for pb_check_ps
		if ($vmtype eq "qemu") {
			my $qemucmd32;
			my $qemucmd64;
			if ($arch eq "x86_64") {
				$qemucmd32 = "/usr/bin/qemu-system-i386";
				$qemucmd64 = "/usr/bin/qemu";
			} else {
				$qemucmd32 = "/usr/bin/qemu";
				$qemucmd64 = "/usr/bin/qemu-system-x86_64";
			}
		if ($v =~ /x86_64/) {
				$vmcmd = "$qemucmd64 -no-kqemu";
			} else {
				$vmcmd = "$qemucmd32";
			}
			$vmm = "$vmpath->{$ENV{'PBPROJ'}}/$v.qemu";
			if ($create != 0) {
				$ENV{'PBVMOPT'} .= " -cdrom $iso -boot d";
			}
			$cmd = "$vmcmd $ENV{'PBVMOPT'} -redir tcp:$nport:10.0.2.15:22 $vmm"
		} elsif ($vmtype eq "xen") {
		} elsif ($vmtype eq "vmware") {
		} else {
			die "VM of type $vmtype not supported. Report to the dev team";
		}
		my ($tmpcmd,$void) = split(/ +/,$cmd);
		my $vmexist = pb_check_ps($tmpcmd,$vmm);
		my $vmpid = 0;
		if (! $vmexist) {
			if ($create != 0) {
				if (($vmtype eq "qemu") || ($vmtype eq "xen")) {
					pb_system("/usr/bin/qemu-img create -f qcow2 $vmm $vmsize->{$ENV{'PBPROJ'}}","Creating the QEMU VM");
				} elsif ($vmtype eq "vmware") {
				} else {
				}
			}
			if (! -f "$vmm") {
				pb_log(0,"Unable to find VM $vmm\n");
			} else {
				pb_system("$cmd &","Launching the VM $vmm");
				pb_system("sleep $vmtmout->{$ENV{'PBPROJ'}}","Waiting for VM $v to come up");
				$vmpid = pb_check_ps($tmpcmd,$vmm);
				pb_log(0,"VM $vmm launched (pid $vmpid)\n");
			}
		} else {
			pb_log(0,"Found an existing VM $vmm (pid $vmexist)\n");
		}
		return($vmexist,$vmpid);
	# VE here
	} else {
		# Get VE context
		my ($ptr,$vetmout,$vepath,$verebuild,$veconf) = pb_conf_get("vetype","vetmout","vepath","verebuild","veconf");
		my $vetype = $ptr->{$ENV{'PBPROJ'}};

		# Get distro context
		my ($name,$ver,$darch) = split(/-/,$v);
		chomp($darch);
		my ($ddir, $dver, $dfam, $dtype, $pbsuf) = pb_distro_init($name,$ver);

		if ($vetype eq "chroot") {
			# Architecture consistency
			if ($arch ne $darch) {
				die "Unable to launch a VE of architecture $darch on a $arch platform" if (not (($darch eq "x86_64") && ($arch =~ /i?86/)));
			}

			if (($create != 0) || ($verebuild->{$ENV{'PBPROJ'}} eq "true") || ($force == 1)) {
				# We have to rebuild the chroot
				if ($dtype eq "rpm") {
					pb_system("sudo /usr/sbin/mock --init --resultdir=\"/tmp\" --configdir=\"$veconf->{$ENV{'PBPROJ'}}\" -r $v","Creating the mock VE");
					# Once setup we need to install some packages, the pb account, ...
					pb_system("sudo /usr/sbin/mock --install --configdir=\"$veconf->{$ENV{'PBPROJ'}}\" -r $v su","Configuring the mock VE");
					#pb_system("sudo /usr/sbin/mock --init --resultdir=\"/tmp\" --configdir=\"$veconf->{$ENV{'PBPROJ'}}\" --basedir=\"$vepath->{$ENV{'PBPROJ'}}\" -r $v","Creating the mock VE");
				} elsif ($dtype eq "deb") {
					pb_system("","Creating the pbuilder VE");
				} elsif ($dtype eq "ebuild") {
					die "Please teach the dev team how to build gentoo chroot";
				} else {
					die "Unknown distribution type $dtype. Report to dev team";
				}
			}
			# Nothing more to do for VE. No real launch
		} else {
			die "VE of type $vetype not supported. Report to the dev team";
		}
	}
}

sub pb_build2v {

my $vtype = shift;

# Prepare the script to be executed on the VM/VE
# in $ENV{'PBDESTDIR'}/pbscript
#my ($ntp) = pb_conf_get($vtype."ntp");
#my $vntp = $ntp->{$ENV{'PBPROJ'}};

open(SCRIPT,"> $ENV{'PBDESTDIR'}/pbscript") || die "Unable to create $ENV{'PBDESTDIR'}/pbscript";
print SCRIPT "#!/bin/bash\n";
print SCRIPT "echo ... Execution needed\n";
print SCRIPT "# This is in directory delivery\n";
print SCRIPT "# Setup the variables required for building\n";
print SCRIPT "export PBPROJ=$ENV{'PBPROJ'}\n";
print SCRIPT "# Preparation for pb\n";
print SCRIPT "mv .pbrc \$HOME\n";
print SCRIPT "cd ..\n";
# Force new date to be in the future compared to the date of the tar file by adding 1 minute
my @date=pb_get_date();
$date[1]++;
my $upddate = strftime("%m%d%H%M%Y", @date);
#print SCRIPT "echo Setting up date on $vntp...\n";
# Or use ntpdate if available TBC
print SCRIPT "sudo date $upddate\n";
# Get list of packages to build and get some ENV vars as well
my $ptr = pb_get_pkg();
@pkgs = @$ptr;
my $p = join(' ',@pkgs) if (@pkgs);
print SCRIPT "export PBPROJVER=$ENV{'PBPROJVER'}\n";
print SCRIPT "export PBPROJTAG=$ENV{'PBPROJTAG'}\n";
print SCRIPT "export PBPACKAGER=\"$ENV{'PBPACKAGER'}\"\n";
print SCRIPT "# Build\n";
print SCRIPT "echo Building packages on $vtype...\n";
print SCRIPT "pb -p $ENV{'PBPROJ'} build2pkg $p\n";
close(SCRIPT);
chmod 0755,"$ENV{'PBDESTDIR'}/pbscript";

my ($v,$all) = pb_get_v($vtype);

# Send tar files when we do a global generation
pb_build2ssh() if ($all == 1);

my ($vmexist,$vmpid) = (undef,undef);

foreach my $v (@$v) {
	if ($vtype eq "vm") {
		# Launch the VM
		($vmexist,$vmpid) = pb_launchv($vtype,$v,0);

		# Skip that VM if it something went wrong
		next if (($vmpid == 0) && ($vmexist == 0));
	}
	# Gather all required files to send them to the VM/VE
	# and launch the build through pbscript
	pb_log(2,"Calling send2target $vtype,$v,$vmexist,$vmpid\n");
	pb_send2target($vtype,"$v",$vmexist,$vmpid);
}
}


sub pb_newver {

	die "-V Version parameter needed" if ((not defined $newver) || ($newver eq ""));

	# Need this call for PBDIR
	my ($scheme2,$uri) = pb_cms_init($pbinit);

	my ($pbconf) = pb_conf_get("pbconfurl");
	$uri = $pbconf->{$ENV{'PBPROJ'}};
	my ($scheme, $account, $host, $port, $path) = pb_get_uri($uri);

	# Checking CMS repositories status
	my ($pburl) = pb_conf_get("pburl");
	($scheme2, $account, $host, $port, $path) = pb_get_uri($pburl->{$ENV{'PBPROJ'}});

	if ($scheme !~ /^svn/) {
		die "Only SVN is supported at the moment";
	}
	my $res = pb_cms_isdiff($scheme,$ENV{'PBROOTDIR'});
	die "ERROR: No differences accepted in CMS for $ENV{'PBROOTDIR'} before creating a new version" if ($res != 0);

	$res = pb_cms_isdiff($scheme2,$ENV{'PBDIR'});
	die "ERROR: No differences accepted in CMS for $ENV{'PBDIR'} before creating a new version" if ($res != 0);

	# Tree identical between PBCONFDIR and PBROOTDIR. The delta is what 
	# we want to get for the root of the new URL

	my $tmp = $ENV{'PBROOTDIR'};
	$tmp =~ s|^$ENV{'PBCONFDIR'}||;

	my $newurl = "$uri/".dirname($tmp)."/$newver";
	# Should probably use projver in the old file
	my $oldver= basename($tmp);

	# Checking pbcl files
	foreach my $f (<$ENV{'PBROOTDIR'}/*/pbcl>) {
		open(PBCL,$f) || die "Unable to open $f";
		my $foundnew = 0;
		while (<PBCL>) {
			$foundnew = 1 if (/^$newver \(/);
		}
		close(PBCL);
		die "ERROR: version $newver not found in $f" if ($foundnew == 0);
	}

	# Duplicate and extract project-builder part
	pb_log(2,"Copying $uri/$tmp to $newurl\n");
	pb_cms_copy($scheme,"$uri/$tmp",$newurl);
	pb_log(2,"Checkout $newurl to $ENV{'PBROOTDIR'}/../$newver\n");
	pb_cms_up($scheme,"$ENV{'PBCONFDIR'}/..");

	# Duplicate and extract project
	my $newurl2 = "$pburl->{$ENV{'PBPROJ'}}/".dirname($tmp)."/$newver";

	pb_log(2,"Copying $pburl->{$ENV{'PBPROJ'}}/$tmp to $newurl2\n");
	pb_cms_copy($scheme,"$pburl->{$ENV{'PBPROJ'}}/$tmp",$newurl2);
	pb_log(2,"Checkout $newurl2 to $ENV{'PBDIR'}/../$newver\n");
	pb_cms_up($scheme,"$ENV{'PBDIR'}/..");

	# Update the .pb file
	open(FILE,"$ENV{'PBROOTDIR'}/../$newver/$ENV{'PBPROJ'}.pb") || die "Unable to open $ENV{'PBROOTDIR'}/../$newver/$ENV{'PBPROJ'}.pb";
	open(OUT,"> $ENV{'PBROOTDIR'}/../$newver/$ENV{'PBPROJ'}.pb.new") || die "Unable to write to $ENV{'PBROOTDIR'}/../$newver/$ENV{'PBPROJ'}.pb.new";
	while(<FILE>) {
		s/^projver\s+$ENV{'PBPROJ'}\s*=\s*$oldver/projver $ENV{'PBPROJ'} = $newver/;
		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/);
		s/^testver/#testver/;
		pb_log(0,"Commenting testver in $ENV{'PBROOTDIR'}/../$newver/$ENV{'PBPROJ'}.pb\n") if (/^testver/);
		print OUT $_;
	}
	close(FILE);
	close(OUT);
	rename("$ENV{'PBROOTDIR'}/../$newver/$ENV{'PBPROJ'}.pb.new","$ENV{'PBROOTDIR'}/../$newver/$ENV{'PBPROJ'}.pb");

	pb_log(2,"Checkin $ENV{'PBROOTDIR'}/../$newver\n");
	pb_cms_checkin($scheme,"$ENV{'PBROOTDIR'}/../$newver");
}

#
# Return the list of VMs/VEs we are working on
# $all is a flag to know if we return all of them 
# or only some (if all we publish also tar files in addition to pkgs
#
sub pb_get_v {

my $vtype = shift;
my @v;
my $all = 0;
my $vlist;
my $pbv = 'PBV';

if ($vtype eq "vm") {
	$vlist = "vmlist";
} elsif ($vtype eq "ve") {
	$vlist = "velist";
}
# Get VM/VE list
if ((not defined $ENV{$pbv}) || ($ENV{$pbv} =~ /^all$/)) {
	my ($ptr) = pb_conf_get($vlist);
	$ENV{$pbv} = $ptr->{$ENV{'PBPROJ'}};
	$all = 1;
}
pb_log(2,"$vtype: $ENV{$pbv}\n");
@v = split(/,/,$ENV{$pbv});
return(\@v,$all);
}

# Function to create a potentialy missing pb account on the VM/VE, and adds it to sudo
# Needs to use root account to connect to the VM/VE
# pb will take your local public SSH key to access
# the pb account in the VM later on if needed
sub pb_setup_v {

my $vtype = shift;

my ($vm,$all) = pb_get_v($vtype);

# Script generated
my $pbscript = "$ENV{'PBDESTDIR'}/setupv";

foreach my $v (@$vm) {
	# Name of the account to deal with for VM/VE
	# Do not use the one passed potentially with -a
	my ($pbac) = pb_conf_get($vtype."login");
	my ($key,$zero0,$zero1,$zero2);
	my ($vmexist,$vmpid);

	if ($vtype eq "vm") {
		# Prepare the key to be used and transfered remotely
		my $keyfile = pb_ssh_get(1);
		
		my ($vmhost,$vmport) = pb_conf_get("vmhost","vmport");
		my $nport = $vmport->{$ENV{'PBPROJ'}};
		$nport = "$pbport" if (defined $pbport);
	
		# Launch the VM
		($vmexist,$vmpid) = pb_launchv($vtype,$v,0);

		# Skip that VM if something went wrong
		return if (($vmpid == 0) && ($vmexist == 0));
	
		# Store the pub key part in a variable
		open(FILE,"$keyfile.pub") || die "Unable to open $keyfile.pub";
		($zero0,$zero1,$zero2) = split(/ /,<FILE>);
		close(FILE);

		$key = "\Q$zero1";

		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\"","Copying local keys to $vtype. This will require the root password");
		# once this is done, we can do what we want on the VM remotely
	}
	
	# Prepare the script to be executed on the VM/VE
	# in $ENV{'PBDESTDIR'}/setupv
	
	open(SCRIPT,"> $pbscript") || die "Unable to create $pbscript";
	print SCRIPT << 'EOF';
#!/usr/bin/perl -w

use strict;
use File::Copy;

our $debug;
our $LOG;
our $synmsg = "pbscript";
pb_log_init($debug, $LOG);
pb_temp_init();

EOF
	if ($vtype eq "vm") {
		print SCRIPT << 'EOF';
# Removes duplicate in .ssh/authorized_keys of our key if needed
#
my $file1="$ENV{'HOME'}/.ssh/authorized_keys";
open(PBFILE,$file1) || die "Unable to open $file1";
open(PBOUT,"> $file1.new") || die "Unable to open $file1.new";
my $count = 0;
while (<PBFILE>) {
EOF
		print SCRIPT << "EOF";
	if (/ $key /) {
		\$count++;
	}
print PBOUT \$_ if ((\$count <= 1) || (\$_ !~ / $key /));
}
close(PBFILE);
close(PBOUT);
rename("\$file1.new",\$file1);
chmod 0600,\$file1;
EOF
	}
	print SCRIPT << 'EOF';

# Adds $pbac->{$ENV{'PBPROJ'}} as an account if needed
#
my $file="/etc/passwd";
open(PBFILE,$file) || die "Unable to open $file";
my $found = 0;
while (<PBFILE>) {
EOF
	print SCRIPT << "EOF";
	\$found = 1 if (/^$pbac->{$ENV{'PBPROJ'}}:/);
EOF
	print SCRIPT << 'EOF';
}
close(PBFILE);

if ( $found == 0 ) {
	if ( ! -d "/home" ) {
		pb_mkdir("/home");
	}
EOF
	print SCRIPT << "EOF";
pb_system("groupadd $pbac->{$ENV{'PBPROJ'}}","Adding group $pbac->{$ENV{'PBPROJ'}}");
pb_system("useradd $pbac->{$ENV{'PBPROJ'}} -g $pbac->{$ENV{'PBPROJ'}} -m -d /home/$pbac->{$ENV{'PBPROJ'}}","Adding user $pbac->{$ENV{'PBPROJ'}} (group $pbac->{$ENV{'PBPROJ'}} - home /home/$pbac->{$ENV{'PBPROJ'}}");
}

# allow ssh entry to build
#
mkdir "/home/$pbac->{$ENV{'PBPROJ'}}/.ssh",0700;
# Allow those accessing root to access the build account
copy("\$ENV{'HOME'}/.ssh/authorized_keys","/home/$pbac->{$ENV{'PBPROJ'}}/.ssh/authorized_keys");
chmod 0600,".ssh/authorized_keys";
pb_system("chown -R $pbac->{$ENV{'PBPROJ'}}:$pbac->{$ENV{'PBPROJ'}} /home/$pbac->{$ENV{'PBPROJ'}}/.ssh","Finish setting up the SSH env for $pbac->{$ENV{'PBPROJ'}}");

EOF
	print SCRIPT << 'EOF';
# No passwd for build account only keys
$file="/etc/shadow";
open(PBFILE,$file) || die "Unable to open $file";
open(PBOUT,"> $file.new") || die "Unable to open $file.new";
while (<PBFILE>) {
EOF
	print SCRIPT << "EOF";
	s/^$pbac->{$ENV{'PBPROJ'}}:\!\!:/$pbac->{$ENV{'PBPROJ'}}:*:/;
	s/^$pbac->{$ENV{'PBPROJ'}}:\!:/$pbac->{$ENV{'PBPROJ'}}:*:/;	#SLES 9 e.g.
EOF
	print SCRIPT << 'EOF';
	print PBOUT $_;
}
close(PBFILE);
close(PBOUT);
rename("$file.new",$file);
chmod 0640,$file;

# pb has to be added to portage group on gentoo

# Adapt sudoers
$file="/etc/sudoers";
open(PBFILE,$file) || die "Unable to open $file";
open(PBOUT,"> $file.new") || die "Unable to open $file.new";
while (<PBFILE>) {
EOF
	print SCRIPT << "EOF";
	next if (/^$pbac->{$ENV{'PBPROJ'}}   /);
EOF
	print SCRIPT << 'EOF';
	s/Defaults[ \t]+requiretty//;
	print PBOUT $_;
}
close(PBFILE);
EOF
	print SCRIPT << "EOF";
# This is needed in order to be able to halt the machine from the $pbac->{$ENV{'PBPROJ'}} account at least
print PBOUT "$pbac->{$ENV{'PBPROJ'}}   ALL=(ALL) NOPASSWD:ALL\n";
EOF
	print SCRIPT << 'EOF';
close(PBOUT);
rename("$file.new",$file);
chmod 0440,$file;

EOF
		
	my $SCRIPT = \*SCRIPT;
	
	pb_install_deps($SCRIPT);
	
	print SCRIPT << 'EOF';
# Suse wants sudoers as 640
if (($ddir eq "sles") || (($ddir eq "suse")) && ($dver ne "10.3")) {
	chmod 0640,$file;
}

# Sync date
#system "/usr/sbin/ntpdate ntp.pool.org";

pb_system("rm -rf perl-ProjectBuilder-* ; wget --passive-ftp ftp://ftp.mondorescue.org/src/perl-ProjectBuilder-latest.tar.gz ; tar xvfz perl-ProjectBuilder-latest.tar.gz ; cd perl-ProjectBuilder-* ; perl Makefile.PL ; make ; make install ; cd .. ; rm -rf perl-ProjectBuilder-* ; rm -rf project-builder-* ; wget --passive-ftp ftp://ftp.mondorescue.org/src/project-builder-latest.tar.gz ; tar xvfz project-builder-latest.tar.gz ; cd project-builder-* ; perl Makefile.PL ; make ; make install ; cd .. ; rm -rf project-builder-* ;","Building Project-Builder");
system "pb 2>&1 | head -5";
EOF
	if ((! $vmexist) && ($vtype eq "vm")) {
		print SCRIPT << 'EOF';
pb_system("sudo /sbin/halt -p","Halting the $vtype");
EOF
	}
	
	# Adds pb_distro_init from ProjectBuilder::Distribution
	foreach my $d (@INC) {
		my @f = ("$d/ProjectBuilder/Base.pm","$d/ProjectBuilder/Distribution.pm");
		foreach my $f (@f) {
			if (-f "$f") {
				open(PBD,"$f") || die "Unable to open $f";
				while (<PBD>) {
						next if (/^package/);
						next if (/^use Exporter/);
						next if (/^use ProjectBuilder::/);
						next if (/^our /);
					print SCRIPT $_;
				}
				close(PBD);
			}
		}
	}
	close(SCRIPT);
	chmod 0755,"$pbscript";

	# That build script needs to be run as root
	$pbaccount = "root";
	pb_script2v($pbscript,$vtype);
}
return;
}

sub pb_install_deps {

my $SCRIPT = shift;

print {$SCRIPT} << 'EOF';
# We need to have that pb_distro_init function
# Get it from Project-Builder::Distribution
my ($ddir, $dver, $dfam, $dtype, $pbsuf) = pb_distro_init(); 
print "distro tuple: ".join(',',($ddir, $dver, $dfam, $dtype, $pbsuf))."\n";

# Get and install pb
my $insdm = "rm -rf Date-Manip* ; wget http://search.cpan.org/CPAN/authors/id/S/SB/SBECK/Date-Manip-5.48.tar.gz ; tar xvfz Date-Manip-5.48.tar.gz ; cd Date-Manip* ; perl Makefile.PL ; make ; make install ; cd .. ; rm -rf Date-Manip*";
my $insmb = "rm -rf Module-Build* ; wget http://search.cpan.org/CPAN/authors/id/K/KW/KWILLIAMS/Module-Build-0.2808.tar.gz ; tar xvfz Module-Build-0.2808.tar.gz ; cd Module-Build* ; perl Makefile.PL ; make ; make install ; cd .. ; rm -rf Module-Build*";
my $insfm =	"rm -rf File-MimeInfo* ; wget http://search.cpan.org/CPAN/authors/id/P/PA/PARDUS/File-MimeInfo/File-MimeInfo-0.15.tar.gz ; tar xvfz File-MimeInfo-0.15.tar.gz ; cd File-MimeInfo* ; perl Makefile.PL ; make ; make install ; cd .. ; rm -rf File-MimeInfo*";
my $insfb = "rm -rf File-Basedir* ; wget http://search.cpan.org/CPAN/authors/id/P/PA/PARDUS/File-BaseDir-0.03.tar.gz ; tar xvfz File-BaseDir-0.03.tar.gz ; cd File-BaseDir* ; perl Makefile.PL ; make ; make install ; cd .. ; rm -rf File-BaseDir*";
my $cmtdm = "Installing Date-Manip perl module";
my $cmtmb = "Installing Module-Build perl module";
my $cmtfm = "Installing File-MimeInfo perl module";
my $cmtfb = "Installing File-Basedir perl module";
my $cmtall = "Installing required modules";

if ( $ddir eq "fedora" ) {
	pb_system("yum clean all","Cleaning yum env");
	#system "yum update -y";
	my $arch=`uname -m`;
	my $opt = "";
	chomp($arch);
	if ($arch eq "x86_64") {
		$opt="--exclude=*.i?86";
	}

	pb_system("yum -y $opt install rpm-build wget patch ntp sudo perl-DateManip perl-File-MimeInfo perl-ExtUtils-MakeMaker",$cmtall);
	if ($dver eq 4) {
		pb_system("$insmb","$cmtmb");
		pb_system("$insfm","$cmtfm");
		pb_system("$insfb","$cmtfb");
	}
} elsif (( $dfam eq "rh" ) || ($ddir eq "sles") || (($ddir eq "suse") && (($dver eq "10.1") || ($dver eq "10.0"))) || ($ddir eq "slackware")) {
	# Suppose pkg are installed already as no online mirror available
	pb_system("rpm -e lsb 2>&1 > /dev/null","Removing lsb package");
	pb_system("$insdm","$cmtdm");
	pb_system("$insmb","$cmtmb");
	pb_system("$insfm","$cmtfm");
	pb_system("$insfb","$cmtfb");
} elsif ($ddir eq "suse") { 
	# New OpenSuSE
	pb_system("$insmb","$cmtmb");
	pb_system("$insfm","$cmtfm");
	pb_system("$insfb","$cmtfb");
	pb_system("export TERM=linux ; liste=\"\" ; for i in make wget patch sudo perl-DateManip perl-File-HomeDir xntp; do rpm -q \$i 1> /dev/null 2> /dev/null ; if [ \$\? != 0 ]; then liste=\"\$liste \$i\"; fi; done; echo \"Liste: \$liste\" ; if [ \"\$liste\" != \"\" ]; then yast2 -i \$liste ; fi","$cmtall");
} elsif ( $dfam eq "md" ) {
		pb_system("urpmi.update -a ; urpmi --auto rpm-build wget sudo patch ntp-client perl-File-MimeInfo","$cmtall");
		if (($ddir eq "mandrake") && ($dver eq "10.1")) {
			pb_system("$insdm","$cmtdm");
		} else {
			pb_system("urpmi --auto perl-DateManip","$cmtdm");
		}
} elsif ( $dfam eq "du" ) {
	if (( $dver eq "3.1" ) && ($ddir eq "debian")) {
		#system "apt-get update";
		pb_system("$insfb","$cmtfb");
		pb_system("$insfm","$cmtfm");
		pb_system("apt-get -y install wget patch ssh sudo debian-builder dh-make fakeroot ntpdate libmodule-build-perl libdate-manip-perl","$cmtall");
	} else  {
		pb_system("apt-get update; apt-get -y install wget patch openssh-server dpkg-dev sudo debian-builder dh-make fakeroot ntpdate libfile-mimeinfo-perl libmodule-build-perl libdate-manip-perl","$cmtall");
	}
} elsif ( $dfam eq "gen" ) {
		#system "emerge -u system";
		pb_system("emerge wget sudo ntp DateManip File-MimeInfo","$cmtall");
} else {
	print "No pkg to install\n";
}
EOF
}

# Return the SSH key file to use
# Potentially create it if needed

sub pb_ssh_get {

my $create = shift || 0;	# Do not create keys by default

# Check the SSH environment
my $keyfile = undef;

# We have specific keys by default
$keyfile = "$ENV{'HOME'}/.ssh/pb_dsa";
if (!(-e $keyfile) && ($create eq 1)) {
	pb_system("ssh-keygen -q -b 1024 -N '' -f $keyfile -t dsa","Generating SSH keys for pb");
}

$keyfile = "$ENV{'HOME'}/.ssh/id_rsa" if (-s "$ENV{'HOME'}/.ssh/id_rsa");
$keyfile = "$ENV{'HOME'}/.ssh/id_dsa" if (-s "$ENV{'HOME'}/.ssh/id_dsa");
$keyfile = "$ENV{'HOME'}/.ssh/pb_dsa" if (-s "$ENV{'HOME'}/.ssh/pb_dsa");
die "Unable to find your public ssh key under $keyfile" if (not defined $keyfile);
return($keyfile);
}


# Returns the pid of a running VM command using a specific VM file
sub pb_check_ps {
	my $vmcmd = shift;
	my $vmm = shift;
	my $vmexist = 0;		# FALSE by default

	open(PS, "ps auxhww|") || die "Unable to call ps";
	while (<PS>) {
		next if (! /$vmcmd/);
		next if (! /$vmm/);
		my ($void1, $void2);
		($void1, $vmexist, $void2) = split(/ +/);
		last;
	}
	return($vmexist);
}


sub pb_extract_build_files {

my $src=shift;
my $dir=shift;
my $ddir=shift;
my @files;

if ($src =~ /tar\.gz$/) {
	pb_system("tar xfpz $src $dir","Extracting build files");
} elsif ($src =~ /tar\.bz2$/) {
	pb_system("tar xfpj $src $dir","Extracting build files");
} else {
	die "Unknown compression algorithm for $src";
}
opendir(DIR,"$dir") || die "Unable to open directory $dir";
foreach my $f (readdir(DIR)) {
	next if ($f =~ /^\./);
	move("$dir/$f","$ddir") || die "Unable to move $dir/$f to $ddir";
	pb_log(2,"mv $dir/$f $ddir\n");
	push @files,"$ddir/$f";
}
closedir(DIR);
# Not enough but still a first cleanup
pb_rm_rf("$dir");
return(@files);
}

sub pb_list_bfiles {

my $dir = shift;
my $pbpkg = shift;
my $bfiles = shift;
my $pkgfiles = shift;
my $supfiles = shift;

opendir(BDIR,"$dir") || die "Unable to open dir $dir: $!";
foreach my $f (readdir(BDIR)) {
	next if ($f =~ /^\./);
	$bfiles->{$f} = "$dir/$f";
	$bfiles->{$f} =~ s~$ENV{'PBROOTDIR'}~~;
	if (defined $supfiles->{$pbpkg}) {
		$pkgfiles->{$f} = "$dir/$f" if ($f =~ /$supfiles->{$pbpkg}/);
	}
}
closedir(BDIR);
}


# 
# Return the list of packages we are working on in a non CMS action
#
sub pb_get_pkg {

my @pkgs = ();

my ($var) = pb_conf_read("$ENV{'PBDESTDIR'}/$ENV{'PBPROJVER'}-$ENV{'PBPROJTAG'}.pb","pbpkg");
@pkgs = keys %$var;

pb_log(0,"Packages: ".join(',',@pkgs)."\n");
return(\@pkgs);
}

1;
