#! /bin/sh
#
# led		--- a locking editor for shared files
#
# Prevents multiple users from simultaneously editing files.
#
# For this to work, you should set the environment variable
# $LED to your favourite editor, and alias the name of
# your editor to led.  (Also set $EDITOR to led.)  For example:
#
# alias vi	'setenv EDITOR led ; setenv LED /usr/ucb/vi ; led'
# alias emacs	'setenv EDITOR led ; setenv LED /local/bin/emacs ; led'
#
# Revised: Oscar Nierstrasz @ cui.unige.ch Jan 1989

u="Usage: led [-f(orce)] [-c(hmod)] [-<vi flag> ...] <file>"
ln=/usr/5bin/ln

case $LED in
"" )	LED=vi ;;
esac

for arg
do
	case $arg in
	-f )	force=y ;;
	-c )	chmod=y ;;
	[-+]*)	flags="$flags $arg" ;;
	* )	case $file in
		"" )	file=$arg ;;
		* )	echo "$u" 1>&2 ; exit ;;
		esac ;;
	esac
done

case $file in
"" )	echo "$u" 1>&2 ; exit ;;
esac

l=$file.lock
w=$file.who

trap : 1 2

case $force in
y )	rm -f $w $l ;;
esac

if ($ln $file $l) 2> /dev/null
then
	break # success, so normal case
else
	if test -f $l
	then
		echo "Sorry, `cat $w` is editing the file!" 1>&2
		exit
	else
		# create new file:
		touch $file
		$ln $file $l
	fi
fi

case $chmod in
y ) chmod +w $file;;
esac

echo ${USER}@`hostname` > $w
$LED $flags $file
rm -f $w $l

case $chmod in
y ) chmod -w $file;;
esac

if test ! -s $file
then
	echo "led: $file has size 0 -- removed" 1>&2
	rm -f $file
fi

exit

