#!/h/COE/Comp/PERL5/bin/perl -T -I/h/COE/lib  -U
#-
 # Copyright (C) 2002, Federal Linux Systems
 # License: GNU Lesser General Public License, v2.1
#- 

#- need -U to force file write in linked directories
#- drop -w for warning file open for LastProfiles

use strict;
use Coe;
use Sys::Hostname;

my $PRGM="COE_set_current_profiles";
my $VERSION="1.1.4.1";

if (@ARGV == 0) {
	&useage;
	exit 202;
} 

sub useage {
	print "Useage: COE_set_current_profiles [options] ";
	print "\":\" [\":\"]*\n";
}

my $append="false";
my $arg1;
my $flagprof;
my $i;
my $home;
my $hostname;
my $lastprofiles;
my $pcnt=0;
my $profile;
my $pscope;
my $pinfo;
my $display;
my @profile;
my @pscope;
my $COEDAT;
my @tmp;


while (@ARGV > 0) {
	$arg1=cleanString(shift,3);
	if ("$arg1" eq "-h") {
		useage;
   		exit 0;
	} elsif ("$arg1" eq "-H") {
		coeMan("COE_COMP/UserMgmt/docs/man/$PRGM");
   		exit 0;
	} elsif ("$arg1" eq "-V") {
		print "VERSION: $VERSION\n";
   		exit 0;
	} elsif ("$arg1" eq "-a") {
		$append="true";
	} else {
		$_=$arg1;
		@tmp=split(':');
		$profile[$pcnt] = $tmp[0];
		#$pscope[$pcnt] = cleanString(shift,1);
		$pscope[$pcnt] = $tmp[1];
		if ("$pscope[$pcnt]" eq "l" || "$pscope[$pcnt]" eq "local") {
			$pscope[$pcnt]="l";	
		} elsif ("$pscope[$pcnt]" eq "g" || "$pscope[$pcnt]" eq "global") {
			$pscope[$pcnt]="g";	
		} else {
			useage;
			exit 202;
		}
		$pcnt++;
	}
}

# define path/file info
$home=$ENV{'HOME'};

$hostname=hostname();

$_=$ENV{'DISPLAY'};
s/^.*://;
s/\..*$//;
$display=$_;
if ("$display" eq "" ) {
	$display="0";
}

#- place the LastProfiles file into the users home directory, unless DII COE
$lastprofiles = coeFileConv("$home/LastProfiles_".$hostname."_".$display, 3);

#- if strict DII COE is needed, use the following
#$lastprofiles = coeFileConv("$home/../LastProfiles_".$hostname."_".$display, 3);

if ("$append" eq "true") {
	# append the LastProfiles file with unique profile data
	for (my $i=0; $i<$pcnt; $i++) {
		
		# set string to insert into LastProfiles_x_0
		$pinfo="$profile[$i]:$pscope[$i]";

		# check to see if Profile is already present
		if (-e $lastprofiles) {
			open COEDAT, "$lastprofiles"
				|| die "Cannot open file $lastprofiles: $!\n";
			while () { if (/^$pinfo$/) { $flagprof="true"; } }
			close COEDAT;
		}
	
		# if Profile is not already present, add it
		if ("$flagprof" ne "true") {
			open COEDAT, (">>$lastprofiles") 
				|| die "Cannot open file $lastprofiles: $!\n";
			print COEDAT "$pinfo\n"; 
			close COEDAT;
		}
	}
} else {
	# overwrite existing files with the new profile data
	open COEDAT, ">$lastprofiles" 
		|| die "Cannot open file $lastprofiles: $!\n";

	for (my $i=0; $i<$pcnt; $i++) {
		
		# set string to insert into LastProfiles_x_0
		$pinfo="$profile[$i]:$pscope[$i]";

		# if Profile is not already present, add it
		print COEDAT "$pinfo\n"; 
	}

	close COEDAT;
}

exit 0;