#! /bin/sh
##  $Revision: 1.7 $
##  Run subst over a list of files.  Get files in and out of source control
##  if present.

##  Assume no source control.
MODE=none
PLAIN="$*"
CONTROLLED=
BASEDIRNAME=`basename \`pwd\``

if [ -d RCS -a ! -d SCCS ] ; then
    # Find out which files are under RCS control.
    MODE=rcs
    PLAIN=
    for I
    do
	if [ -f RCS/${I},v ] ; then
	    if co -l -q ${I}; then
		CONTROLLED="${CONTROLLED} ${I}"
		rm -f ${I}.bak
		cp ${I} ${I}.bak
	    else
		echo "unable to RCS checkout ${I}" 1>&2
		if [ ! -z "${CONTROLLED}" ]; then
		    co -u -q ${CONTROLLED}
		fi
		exit 1
	    fi
	else
	    PLAIN="${PLAIN} ${I}"
	    rm -f ${I}.bak
	    cp -p ${I} ${I}.bak
	fi
    done
fi
if [ -d SCCS -a ! -d RCS ] ; then
    # Find out which files are under SCCS control.
    MODE=sccs
    PLAIN=
    for I
    do
	if [ -f SCCS/s.${I} ] ; then
	    if sccs get -s -e "-G${I}" "SCCS/s.${I}"; then
		CONTROLLED="${CONTROLLED} ${I}"
		rm -f ${I}.bak
		cp ${I} ${I}.bak
	    else
		echo "unable to SCCS edit ${I}" 1>&2
		if [ ! -z "${CONTROLLED}" ]; then
		    for J in "${CONTROLLED}"; do
			sccs unget -s "SCCS/s.${J}"'
			sccs get -s "-G${J}" "SCCS/s.${J}"'
		    done
		fi
		exit 1
	    fi
	else
	    PLAIN="${PLAIN} ${I}"
	fi
    done
fi

##  Make sure we can write all non-controlled files.
test ! -z "${PLAIN}" && chmod u+w ${PLAIN}

##  Make the list of files, run config over it.
LISTOFFILES="../${BASEDIRNAME}/files.$$"
for I in ${PLAIN} ${CONTROLLED} ; do
    echo "../${BASEDIRNAME}/${I}"
done > "${LISTOFFILES}"
(cd ../config; make quiet FILE="${LISTOFFILES}" )
rm -f "${LISTOFFILES}"

##  Check files back into source control, if we have to.
if [ ! -z "${CONTROLLED}" ]; then
    for I in ${CONTROLLED}; do
	if cmp -s ${I} ${I}.bak; then
	    # no change was needed
	    case $MODE in
		sccs) test -f SCCS/s.${I} && sccs unedit ${I} ;;
		rcs) test -f RCS/${I},v && rcs -q -u ${I} ;;
	    esac
	else
	    # there was a change, check in the change
	    case $MODE in
		sccs) echo 'Ran subst from Makefile' | sccs delget -s ${I} ;;
		rcs) echo 'Ran subst from Makefile' | ci -u -q -f ${I} ;;
	    esac
	fi
	rm -f ${I}.bak
	chmod -w ${I}
    done
fi
  
##  Restore read-only to all non-controlled files.
if [ ! -z "${PLAIN}" ]; then
    for I in ${PLAIN}; do
	if cmp -s ${I} ${I}.bak; then
	    # no change was needed
	    rm -f ${I}.bak
	fi
	chmod -w ${I}
    done
fi

exit 0
