#
# removes the specified sync files after obtaining the directory lock
# $Id: remove_sync_files,v 1.2 1997/09/24 00:35:58 naamato Exp $

if ( $#ARGV < 0 ) {
	print "usage: $0 syncfiles ...\n";
	exit 1;
}

#
# get args
#
( @sync_files ) = @ARGV;

#
# find sync directory
#
$gated_sync_dir=$ENV{"gated_sync_dir"};
if ($gated_sync_dir eq "") {
	die "\$gated_sync_dir must be set";
}

#
# obtain lock
#
if (! open(LOCK_FILE, ">>$gated_sync_dir/flockfile")) {
	die "Can't open sync file $gated_sync_dir/flockfile"; 
}
if (&lock_file(*LOCK_FILE) != 0) {
	die "Can't get flock";
}

#
# remove files 
#
foreach $file ( @sync_files ) {
	if ( ! -e $file ) {
		next;
	}
	if ( unlink($file) != 1 ) {
		die "can't remove sync file $file";
	}
}

#
# release lock
#
if (&unlock_file(*LOCK_FILE) != 0) {
	die "Can't release flock";
}
close(LOCK_FILE);

#
# subroutines
#

use Fcntl;

sub lock_file ()
{
	local ( $FILE ) = @_;
	local ( $arg );
        
	# short: l_type, l_whence; long: l_start, l_len, l_pad[6]
	$arg = pack("ssllllllll", &F_WRLCK, 0, 0, 1, 0, 0, 0, 0, 0, 0);

	fcntl($FILE, &F_SETLKW, $arg);
}

sub unlock_file ()
{
	local ( $FILE ) = @_;
	local ( $arg );
        
	# short: l_type, l_whence; long: l_start, l_len, l_pad[6]
	$arg = pack("ssllllllll", &F_UNLCK, 0, 0, 1, 0, 0, 0, 0, 0, 0);

	fcntl($FILE, &F_SETLKW, $arg);
}
