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

use strict;
use Coe;

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

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

sub useage {
   	print "Useage: $PRGM [options]   ";
	print "\"\" \n";
}

my $flag="false";
my $pscope="a";
my $profile="all";
my $userid="all";
my $uname="dummy";
my $username="dummy";
my $uscope="a";
my $arg1;
my $coedat;
my $COEDAT;

while (@ARGV > 0 ){
	$arg1=cleanString(shift,1);
	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;
	} else {
   		$userid=$arg1;
		$uscope=cleanString(shift,1);
		$profile=cleanString(shift,1);
		$pscope=cleanString(shift,1);
	}
}

# verify the user scope 
if ("$uscope" eq "l" || "$uscope" eq "local") {
	$uscope="local";
} elsif ("$uscope" eq "g" || "$uscope" eq "global") {
	$uscope="global";
} else {
	print "User scope must be one of \"g\" or \"l\"\n";
	exit 202;
}

# verify the profile scope 
if ("$pscope" eq "l" || "$pscope" eq "local") {
	$pscope="local";
} elsif ("$pscope" eq "g" || "$pscope" eq "global") {
	$pscope="global";
} else {
	print "Profile scope must be one of \"g\" or \"l\"\n";
	exit 202;
}

#- does this user exist
$flag="false";
$coedat=coeFileConv("COE_USER/$uscope/Profiles/.User.dat");
$COEDAT=readFile ($coedat);
while (<$COEDAT>) { if (/^$userid:/) { $flag="true"; }}
close $COEDAT;
if ("$flag" eq "false") {
	# user does not exist
	exit 203;
}

#- does this profile exist
$flag="false";
$coedat=coeFileConv("COE_USER/$pscope/Profiles/.Profile.dat");
$COEDAT=readFile ($coedat);
while (<$COEDAT>) { if (/^$profile:/) { $flag="true"; }}
close $COEDAT;
if ("$flag" eq "false") {
	# profile does not exist
	exit 204;
}

#- assign user to profile, save in the profiles scope
$flag="false";
$coedat=coeFileConv("COE_USER/$pscope/Profiles/.UserProfile.dat");
$COEDAT=readFile ($coedat);
while (<$COEDAT>) {chomp();if (/^$userid:$uscope:$profile$/) { $flag="true"; }}
close $COEDAT;

if ("$flag" ne "true") {
	open COEDAT, ">>$coedat" 
                   || die "Cannot open COEDAT $coedat: $!\n";
	print COEDAT "$userid:$uscope:$profile\n";
	close COEDAT;
} else {
	#- duplicate user/profile data
	exit 217;
}

# successful exit
exit 0;