#!/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.10 $
# $Date: 1997/04/28 18:38:05 $
# $Author: cwilson $
# $State: Exp $
#
# $Locker:  $

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

# 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");
}
require "$cf";

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

# Here's where the fun begins...

(defined($listdir) && chdir "$listdir") 
    || die("can't access \$listdir $listdir");


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

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