#!/bin/posix/sh
#@(#)HP X Station Admin Scripts
#
# xtutil_RemoveFromExports	Remove X station from a line in /etc/exports
#

set -u				# Find undefined variables
set -a				# Export all new variables
. xtutil_scriptInit
set +a

if [ $# -ne 1 ]
then
  $NLECHO "missingArgNFS RemoveFromExports $EXPORTS"
  exit 1
fi

terminalName=$1
fileToExport=$terminalDirectory

if [ ! -f $EXPORTS ]
then
  $NLECHO "noExports"
  exit 1
fi

# Find out local file system of $1

FS2EXP=`xtutil_wherelives $fileToExport`	; exitIfNonZero $? 1 "$FS2EXP"
#
# Is the file system exported to the world?
#
NFSCLIENTS=`xtutil_nfsClients $FS2EXP`

if [ "$NFSCLIENTS" = "" ]
then
    exit 0
fi


#
# Is file system exported to this terminal?
# Calculate which line.
#
LNUM=`cut -f1 -d# $EXPORTS |
	egrep -n "^${FS2EXP}.*[ 	=:]${terminalName}([ 	:,]|$)" | \
	head -1 | \
	cut -f1 -d:`

if [ "$LNUM" = "" ]
then
    exit 0
fi


#
# remove the terminal name
#
sed \
	-e "${LNUM}s/[-,]access=${terminalName}\([ 	]\)/\1/" \
	-e "${LNUM}s/[-,]access=${terminalName}$//" \
	-e "${LNUM}s/\([-,]\)access=${terminalName},/\1/" \
	-e "${LNUM}s/\([=:]\)${terminalName}:/\1/" \
	-e "${LNUM}s/:${terminalName}\([ 	]\)/\1/" \
	-e "${LNUM}s/:${terminalName}$//" \
	-e "${LNUM}s/\([ 	]\)${terminalName}[ 	]/\1/" \
	-e "${LNUM}s/[ 	]${terminalName}$//" \
	$EXPORTS > $TMP/$$

exitIfNonZero $? 1 `$NLECHO "sedNFS $EXPORTS"`

#
# See if the deletion left the file system alone on the line
# thus exporting the file system to the world.
# If so remove the line.
#
NFSCLIENTS=`sed -n -e "${LNUM}p" $TMP/$$ | \
	cut -d# -f1 | \
	sed	-e "s%^${FS2EXP}[	 ]*%%" \
		-e 's/[-,]root=//' \
		-e 's/[-,]ro[	 ]*//' \
		-e 's/[-,]async[	 ]*//' \
		-e 's/[-,]anon=[0-9]*[	 ]*//'`

if [ "$NFSCLIENTS" = "" ]
then
      sed "${LNUM}d" $TMP/$$ > $TMP/tmp.$$
      cp $TMP/tmp.$$ $TMP/$$
      rm $TMP/tmp.$$
fi

cmp -s $EXPORTS $TMP/$$ 
exitIfZero $? 0 `$NLECHO "tooDumbRemoveNFS $terminalName $EXPORTS $FS2EXP"`

#
# make a back-up before modifying $EXPORTS
#
cp $EXPORTS /tmp/`basename $EXPORTS`.$$
$NLECHO "copyNFS $EXPORTS /tmp/`basename $EXPORTS`.$$"

cp $TMP/$$ $EXPORTS 
exitIfNonZero $? 1 `$NLECHO "couldntCopy $TMP/$$ $EXPORTS"`

$NLECHO "removedNFS $terminalName $EXPORTS"

rm $TMP/$$

osExportFS $FS2EXP $terminalName

exit $?

