#!/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_clear_profile_lock";
my $VERSION="1.1.4.1";

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

sub useage {
	print "Useage: COE_clear_profile_lock [options] <\"Profile Name\"> ";
	print "\n";
}

my $i;
my $arg1;
my $lockfile;
my $hostname;
my $mode;
my $profile;
my $profabbr;
my $pscope;
my $uid;
my $username;
my $coedat;
my $COEDAT;
my $coedatstr;
my $flag;
my @filedata;
my @profdata;

$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,1);
}

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

# run this now to clean env
$hostname=hostname();

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

# if no such profile, error exit
if (@profdata < 5) {
	exit 204;
}

# get profile locking mode
if ("$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=coeFileConv "$coedat/$profdata[4]";

# get username
$username=$ENV{'LOGNAME'};

# get hostname
$hostname=hostname();

# create the data string
$coedatstr=$username.":".$hostname;

# if the lockfile exists, read the data but drop the given profile
if (-e "$coedat" ) {
	$COEDAT = readFile ("$coedat");
	while (<$COEDAT>) { 
		if (! /^$coedatstr:/) { 
			$filedata[$i++]=cleanString($_,3); 
		} 
	}
	close $COEDAT;

	# if  there are other user locks on this profile, restore them
	# else remove the file
	if (@filedata > 0) {
		open COEDAT, ">$coedat" 
			|| die "Cannot open file $lockfile: $!\n";
		foreach (@filedata) { print COEDAT "$_\n"; }
		close COEDAT;
	} else {
		unlink ("$coedat") 
			|| die "Cannot unlink lock file $coedat: $!\n";
	}
	exit 0;

} else {
	exit 211;
}