#!/usr/bin/perl -w
#
# Creates common environment 
#
# $Id$
#
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(set_env);

use lib qw (lib);
use pb qw (pb_init);
use strict;
use File::Basename;
use ExtUtils::Command;
use File::Temp qw /tempdir/;
use vars qw (%defpkgdir %extpkgdir %version);

$ENV{'PBCONF'} = "/etc/pb";

sub set_env {

my $proj=shift;
my $ver;
my $tag;

# Check project name
if ((defined $ENV{'PBPROJ'}) &&
	(not (defined $proj))) {
	$proj = $ENV{'PBPROJ'};
}
die "No project defined - use env var PBPROJ or -p proj" if (not (defined $proj));

# Use project configuration file
pb_init("$ENV{'PBCONF'}/$proj.pb");

# Check content
die "PBROOT doesn't exist in $ENV{'PBCONF'}/$proj.pb" if (not (defined $ENV{'PBROOT'}));
die "defpkgdir doesn't exist in $ENV{'PBCONF'}/$proj.pb" if (not (defined %defpkgdir));

# Set temp directory
if (not defined $ENV{'TMPDIR'}) {
	$ENV{'TMPDIR'}="/tmp";
}
$ENV{'PBTMP'} = tempdir( "pb.XXXXXXXXXX", DIR => $ENV{'TMPDIR'}, CLEANUP => 1 );

# Get global VERSION
open(VER, "$ENV{'PBROOT'}/VERSION") || die "Unable to open $ENV{'PBROOT'}/VERSION: $?";
$ver = <VER>;
chomp($ver);
die "Invalid version name $ver in $ENV{'PBROOT'}/VERSION" if ($ver !~ /[0-9.]+/) || (defined $version{$ver});
$ENV{'PBVER'}=$ver;
close(VER);

#Get global TAG
open(TAG, "$ENV{'PBROOT'}/TAG") || die "Unable to open $ENV{'PBROOT'}/TAG: $?";
$tag = <TAG>;
chomp($tag);
die "Invalid version tag $tag in $ENV{'PBROOT'}/TAG" if ($tag !~ /[0-9]+/);
$ENV{'PBTAG'}=$tag;
close(TAG);

# Adapt to your needs
# Set delivery directory
$ENV{'PBTOPDIR'}="$ENV{'PBROOT'}/../delivery";
$ENV{'PBDESTDIR'}=$ENV{'TOPDIR'}."/".$ENV{'PBVER'}."-".$ENV{'PBTAG'};
mkpath $ENV{'PBDESTDIR'};

umask 0022
}
1;
