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

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

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

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

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

my $arg1;
my $coedatstr;
my $coedat;
my $hostname;
my $mode;
my $profile;
my $pscope;
my $uid;
my $username;
my $flag;
my @profdata;
my $COEDAT;
my $date;
my $perm="0666";

$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 {
	$profile=$arg1;
	$pscope=cleanString(shift,3);
}

if ("$pscope" eq "l" || "$pscope" eq "local") {
	$pscope="local";
} elsif ("$pscope" eq "g" || "$pscope" eq "global" ) {
	$pscope="global";
} else {
	useage;
  	exit 202;
}

# get profile data
$_=coeFileConv("COE_HOME/bin/COE_get_profile_data");
$_=$_." -p \"$profile\" -s $pscope";
$_=coeExec($_);
$_=cleanString($_,3);
@profdata=split(':');

# if this profile does not exist, error exit
if (@profdata < 5) {
	exit 204;
}

# determine if the profile is locking or not
if ("$profdata[3]" eq "") {
	print "$0: Unknown profile - $profile, scope - $pscope\n";
	exit 204;
} elsif ("$profdata[3]" eq "0") {
	$mode="locking";
} else {
	$mode="nonlocking";
}

# set coedat to the locked profile directory
$coedat=coeFileConv "COE_USER/$pscope/Profiles/.LockedProfiles";

# set coedat to the locked file name
$coedat=cleanString("$coedat/$profdata[4]",3);

# get data to write into the lock file info
$username=cleanString($ENV{'LOGNAME'},0);

# get hostname
$hostname=hostname();

# get timestamp
$date = getTimeStamp("YYYYMMDDhhmmss");

# create file data
$coedatstr=cleanString("$username:$hostname:$date",3);

# if the lock file does not exist, create it and write the data
# else if the profile is non-locking, append the data
# else if the profile is locking, do nothing
if (! -e "$coedat") {
	open COEDAT, (">$coedat") 
		|| die "Cannot open file $coedat: $!\n";
	print COEDAT "$coedatstr\n"; 
	close COEDAT;
	chmod oct($perm), "$coedat";
} elsif ("$mode" eq "nonlocking" ) {
	$flag="false";
	$COEDAT = readFile ("$coedat");
	while (<$COEDAT>) { 
		if (/^$coedatstr:/) { 
			$flag="true"; 
		}
	}
	close $COEDAT;

	# if entry does not yet exist, add it
	if ("$flag" eq "false") {
		open COEDAT, (">>$coedat") 
			|| die "Cannot open file $coedat: $!\n";
		print COEDAT "$coedatstr\n"; 
		close COEDAT;
	}
}

exit 0;