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

if [ $# -ne 1 ]
then
  echo "Missing argument in call to $0, - $EXPORTS unchanged."
  exit 2
fi

if [ ! -f $EXPORTS ]
then
  echo "No $EXPORTS file found."
  exit 2
fi

# Find out file system of $1

FS2EXP=`wherelives -s $1`

RETCODE=$?
if [ $RETCODE -ne 0 ]
then
  exit $RETCODE
fi

#
# Is the file system exported to the world?
#
NFSCLIENTS=`egrep "^${FS2EXP}[	 ]+" $EXPORTS | \
	cut -d# -f1 | \
	sed -e "s%^${FS2EXP}[	 ]*%%" \
		-e '/root=/!s/[-,]ro[	 ]*//' \
		-e 's/[-,]async[	 ]*//' \
		-e 's/[-,]anon=[0-9]*[	 ]*//'`

if [ "x$NFSCLIENTS" = "x" ]
then
    exit 1
fi


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

if [ "x$LNUM" = "x" ]
then
    exit 1
fi


#
# remove the terminal name
#
sed \
	-e "${LNUM}s/[-,]access=${SHORTNAME}\([ 	]\)/\1/" \
	-e "${LNUM}s/[-,]access=${SHORTNAME}$//" \
	-e "${LNUM}s/\([-,]\)access=${SHORTNAME},/\1/" \
	-e "${LNUM}s/\([=:]\)${SHORTNAME}:/\1/" \
	-e "${LNUM}s/:${SHORTNAME}\([ 	]\)/\1/" \
	-e "${LNUM}s/:${SHORTNAME}$//" \
	-e "${LNUM}s/\([ 	]\)${SHORTNAME}[ 	]/\1/" \
	-e "${LNUM}s/[ 	]${SHORTNAME}$//" \
	$EXPORTS > $TMP/$$
if [ $? -ne 0 ]
then
  echo "sed failed (1) while updating $EXPORTS."
  exit 5
fi

#
# 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 [ "x$NFSCLIENTS" = "x" ]
then
      sed "${LNUM}d" $TMP/$$ > $TMP/tmp.$$
      cp $TMP/tmp.$$ $TMP/$$
      rm $TMP/tmp.$$
fi

cmp -s $EXPORTS $TMP/$$ 
if [ $? -eq 0 ]
then
      echo ""
      echo "There is an entry for $SHORTNAME in $EXPORTS for $FS2EXP,"
      echo "but this script is not smart enough to remove it."
      echo "Please edit $EXPORTS manually." 
      echo "" 
      exit 0
fi


#
# we seem to have to change /etc/exports. Better make a back-up
#

cp $EXPORTS $TMP/exports.$$
echo ""
echo "A copy of $EXPORTS has been saved in $TMP/exports.$$"

cp $TMP/$$ $EXPORTS 

if [ $? -ne 0 ]
then
  echo "copy to $EXPORTS failed"
  exit 1
fi

echo "$SHORTNAME removed from $EXPORTS"
echo ""

rm $TMP/$$

if [ -x /usr/etc/exportfs ]
then
  /usr/etc/exportfs -a
  RETCODE=$?
  if [ $RETCODE -ne 0 ]
  then
    echo "\"exports -a\" failed ($RETCODE)."
   exit 12
  fi
fi

exit 0
