#!/usr/local/bin/perl

# medit: lock and edit a Majordomo-managed file, then unlock when done.
#
# Copyright 1992, D. Brent Chapman.  All Rights Reserved.  For use by
# permission only.
#
# $Source: /sources/cvsrepos/majordomo/medit,v $
# $Revision: 1.3 $
# $Date: 1994/05/08 20:14:27 $
# $Author: rouilj $
# $State: Exp $
#
# $Locker:  $

# set our path explicitly
$ENV{'PATH'} = "/bin:/usr/bin:/usr/ucb";

# What shall we use for temporary files?
$tmp = "/tmp/medit.$$";

# Read and execute the .cf file
$cf = $ENV{"MAJORDOMO_CF"} || "/etc/majordomo.cf";
if ($ARGV[0] eq "-C") {
    $cf = $ARGV[1];
    shift(@ARGV); 
    shift(@ARGV); 
}
if (! -r $cf) {
    die("$cf not readable; stopped");
}
eval(`cat $cf`)  || die 'eval of majordomo.cf failed';

# All these should be in the standard PERL library
unshift(@INC, $homedir);
require "shlock.pl";		# NNTP-style file locking

# Here's where the fun begins...

chdir "$listdir" || &die("cannot access $listdir");


$editor = $ENV{"EDITOR"} || "vi";

foreach (@ARGV) {
    $lockfile = $_;
    $lockfile =~ s,([^/]*)$,L.$1,;
    for ($tries = 0 ; $tries < 60 ; $tries++) {
	if (&shlock($lockfile)) {
	    # got the lock
	    system("$editor $_");
	    unlink($lockfile);
	    last;
	} else {
	    if (($tries % 5) == 0) {
		print "Waiting for lock on $_...\n";
	    }
	    sleep(1);
	}
    }
    if ($tries > 60) {
	print "Giving up on lock for $_...\n";
    }
}
