#!/usr/bin/perl -w
#
# Creates common environment 
#
# $Id$
#

use strict;
use lib qw (lib);
use pb qw (pb_init);
use File::Basename;
use File::Path;
use File::Temp qw /tempdir/;
use Data::Dumper;

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

sub env_init {

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{'PBETC'}/$proj.pb");

#
# Check content
#
if (not defined $confparam{"pbroot"}) {
	die "confparam pbroot doesn't exist in $ENV{'PBETC'}/$proj.pb";
} else {
	$ENV{'PBROOT'} = $confparam{"pbroot"}; 
}
if (defined $confparam{"cvsroot"}) {
	$ENV{'CVSROOT'} = $confparam{"cvsroot"}; 
}

die "defpkgdir doesn't exist in $ENV{'PBETC'}/$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 );

#
# Check pb conf compliance
#
$ENV{'PBCONF'} = "$ENV{'PBROOT'}/pbconf";
die "Project $ENV{'PBPROJ'} not ProjectBuild compliant. Please populate $ENV{'PBCONF'}" if ( not -d "$ENV{'PBCONF'}");

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

#
#Get global TAG
#
open(TAG, "$ENV{'PBCONF'}/TAG") || die "Unable to open $ENV{'PBCONF'}/TAG: $?";
$tag = <TAG>;
chomp($tag);
die "Invalid tag name $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{'PBTOPDIR'}/$ENV{'PBVER'}-$ENV{'PBTAG'}";
pbrm_rf($ENV{'PBDESTDIR'}) if (-d "$ENV{'PBDESTDIR'}");
pbmkdir_p($ENV{'PBDESTDIR'}) || die "Unable to recursively create $ENV{'PBDESTDIR'}";

umask 0022;
return($proj);
}

sub pbmkdir_p {
	my @dir = @_;
	my $ret = mkpath(@dir, 0, 0755);
	return($ret);
}

sub pbrm_rf {
	my @dir = @_;
	my $ret = rmtree(@dir, 0, 0);
	return($ret);
}

1;
