#! /bin/sh
# @(#)ed_moptions.sh	19.1 (ESO-IPG) 02/25/03 13:51:10
# .COPYRIGHT: Copyright (c) 1988 European Southern Observatory,
#                                         all rights reserved
# .TYPE           command
# .NAME           ed_make_options.sh
# .LANGUAGE       shell script
# .ENVIRONMENT    Unix Systems. Executable under SHELL and C-SHELL
# .COMMENTS       Editing the file make_options.
#
# .AUTHOR         Carlos Guirao
# .VERSION 1.1    17-Jul-1992:	Implementation
# .VERSION 2.1    20-Jan-1993:	"ex" instead of "ed" (for PC/Linux)
# .VERSION 3.1    990324        Checking EDITOR (default ex, otherwise ed)

if [ $# -lt 1 ]; then
	echo "Usage: $0 get/replace/add/delete key[=options]"
	exit 1
fi

if [ "$1" != "get" -a "$1" != "replace" -a "$1" != "add" -a "$1" != "delete" ]; then
	echo "Usage: $0 get/replace/add/delete key[=options]"
	exit 1
fi

if [ "$1" != "delete" -a $$ -lt 2 ]; then
	echo "Usage: $0 replace/add key=options"
	exit 1
fi

#
# Check if 'ex' editor exists otherwise use 'ed'
# "ed" is substituted by "ex" for PC/Linux except in SuSE
#
EDITOR=ex
which ex > /dev/null
if [ $? != 0 ]; then
   EDITOR=ed
fi

if [ -z "$MID_HOME" ]; then
    cd `echo $0 | sed -e 's/[^\/]*$//' -e 's/^$/./' -e 's/\/$//'`
    MID_INSTALL=`pwd`
    VERSDIR=`echo $MID_INSTALL | sed 's/\/install\/unix$//'`
    MIDVERS=`echo $VERSDIR | sed -e 's/^.*\///'`
    MIDASHOME=`echo $VERSDIR | sed -e 's/[^\/]*$//' -e 's/^$/./' -e 's/\/$//'`
    MID_HOME=$MIDASHOME/$MIDVERS
fi

file=$MID_HOME/local/make_options
op=$1
key=`echo $2 | awk -F= '{print $1}'`
options=`echo $2 | sed 's/^'$key'=//'`
options=`eval echo $options`
oldoptions=""

if [ -f $file ]; then
   oldoptions=`grep "^${key}=" $file | sed 's/^'$key'=//'`
fi

if [ -n "$oldoptions" ]; then
    echo $oldoptions
fi

if [ "$op" = "get" ]; then
   exit 0
fi

# Remove previous definition of $key if existed
$EDITOR $file << EOF >/dev/null 2>&1
1
/${key}=/d
w
q
EOF

if [ "$op" = "delete" ]; then
   exit 0
fi

if [ "$op" = "add" ]; then
     options=`eval echo $oldoptions $options`
fi

if [ -n "$options" ]; then
    echo "$key=$options" >> $file
fi
exit 0
