###############
#
#  maintfrm
#
#    create/delete/edit form letters for the form letter email system.
#
#  usage:  maintfrm -[c|d|e] <form directory>
#
##################################################

#
#  Initialize variables
#
LOCALCMDS=/usr/local             # where local commands are stored
EDITCMD=/usr/local/e		 # which editor to use
TEMPFILE=`tmpname FORM`
#
#  extract parameters
#
option=$1
FORM_DIR=$2
#
#  trap interruptions, to remove temp file
#
trap "rm $TEMPFILE; exit" 1 2 3 13 15

#
#  according to option, perform operation
#
cd $FORM_DIR

case $option in
  -c)	echo
	echo "Enter form name (without .fml extension): \c"
	read form_name
	form_name=$form_name.fml
	[ -s $form_name ] && echo "maintfrm:  Form already exists" && exit
	[ "$form_name" = "" ] && echo "maintfrm:  no form name" && exit

	echo "Send to:" >$form_name   # include a "Send to:"(for convenience)

	while true
	do
		$EDITCMD $form_name
		count=`fgrep "Send to:" $form_name | wc -l`
		if [ $count -ne 1 ]; then
			echo "You must include single \"Send to:\" line."
			continue=`askyn "Continue"`
			if [ "$continue" = N ]; then
				rm $form_name >/dev/null 2>&1
				exit
			fi
		else
			echo "Form $form_name created."
			exit
		fi
	done
	exit ;;
  -d)	echo
	form_name=`dirmnu "Available Forms:" "Which to delete?" . "*.fml"`
	[ $form_name = ABORT ] && exit
	owner=`l $form_name | awk '{print $3}' `
	if [ "$owner" != `who am i` ]; then
		echo "You do not own that form!"
	else
		rm $form_name >/dev/null 2>&1
		echo "Form $form_name deleted."
	fi
	exit ;;
  -e)	echo
	form_name=`dirmnu "Available Forms:" "Which to delete?" . "*.fml"`
	[ $form_name = ABORT ] && exit
	cp $form_name $TEMPFILE
	owner=`l $form_name | awk '{print $3}' `
	if [ "$owner" != `who am i` ]; then
		echo "You do not own that form!"
	else
	while true
	do
		$EDITCMD $TEMPFILE
		count=`fgrep "Send to:" $TEMPFILE | wc -l`
		if [ $count -ne 1 ]; then
			echo "You must include single \"Send to:\" line."
			continue=`askyn "Continue"`
			if [ "$continue" = N ]; then
				rm $TEMPFILE >/dev/null 2>&1
				exit
			fi
		else
			cp $TEMPFILE $form_name
			rm $TEMPFILE >/dev/null
			echo "Form $form_name modified."
			exit
		fi
	done
	fi
	exit ;;
    *) echo "usage:  maintfrm -[c|d|e] <form_dir>" && exit;;
esac


	
