#!/bin/ksh
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
#  
#  
# Licensed Materials - Property of IBM 
#  
# (C) COPYRIGHT International Business Machines Corp. 1997,2006 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG 
# @(#)23 1.82 src/avs/fs/mmfs/ts/admin/mmdelfs.sh, mmfs, avs_rgpfs24, rgpfs240610b 10/25/05 14:41:42
######################################################################
#
#  Usage:  mmdelfs Device [-p]
#
#    Device  - the device name of the filesystem to be deleted.
#
#    -p      - indicates that the disks are permanently damaged and
#              that the fs information should be removed from the sdr
#              even if tsdelfs fails.
#
######################################################################

# Include global declarations and service routines.
. /usr/lpp/mmfs/bin/mmglobfuncs
. /usr/lpp/mmfs/bin/mmsdrfsdef
. /usr/lpp/mmfs/bin/mmfsfuncs

sourceFile="mmdelfs.sh"
[[ -n $DEBUG || -n $DEBUGmmdelfs ]] && set -x
$mmTRACE_ENTER "$*"

# Local work files.  Names should be of the form:
#   fn=${tmpDir}fn.${mmcmd}.$$

LOCAL_FILES=" "


# Local variables
integer n=1
usageMsg=292
pflag=""



#######################
# Mainline processing
#######################


#######################################
# Process the command line arguments.
#######################################
[[ $arg1 = '-?' || $arg1 = '-h' || $arg1 = '--help' || $arg1 = '--' ]] &&  \
  syntaxError "help" $usageMsg

[[ $argc -lt 1  ]] &&  \
  syntaxError "missingArgs" $usageMsg

device=$arg1     # The first argument is always the file system name.
shift 1          # Move past the required positional parameters.

# Check validity of the flags.
while getopts :np OPT
do
  case $OPT in
    p) [[ -n $pflag ]] && syntaxError "multiple" $noUsageMsg "-$OPT"
       pflag=yes
       ;;
    :) syntaxError "missingValue" $usageMsg $OPTARG
       ;;
    +[p]) syntaxError "invalidOption" $usageMsg $OPT
       ;;
    *) syntaxError "invalidOption" $usageMsg $OPTARG
       ;;
  esac
done

shift OPTIND-1
[[ $# != 0 ]] && syntaxError "extraArg" $usageMsg $1


#######################################################################
# Set up trap exception handling and call the gpfsInit function.
# It will ensure that the local copy of the mmsdrfs and the rest of
# the GPFS system files are up-to-date and will obtain the sdr lock.
#######################################################################
trap pretrap HUP INT QUIT KILL
gpfsInitOutput=$(gpfsInit $lockId)
setGlobalVar $? $gpfsInitOutput


###########################################################
# Make sure the specified file system exists and is local.
###########################################################
findFSoutput=$(findFS "$device" $mmsdrfsFile)
[[ -z $findFSoutput ]] && cleanupAndExit

# Parse the output from the findFS function.
set -f ; set -- $findFSoutput ; set +f
fqDeviceName=$1
deviceName=$2
fsHomeCluster=$3

# Exit with a message if the command was invoked for a remote file system.
if [[ $fsHomeCluster != $HOME_CLUSTER ]]
then
  # Command is not allowed for remote file systems.
  printErrorMsg 106 $mmcmd $device $fsHomeCluster
  cleanupAndExit 1
fi


########################################################################
# Create the new version of the mmsdrfs file.
#
# It will have a new generation number and all references
# to the file system that is being deleted will be removed.
#
# Simultaneously, we will create a file with the names of the nodes
# that belong to the cluster.  This file will be used later for
# propagating the changes to the individual nodes.
########################################################################
$rm -f $newsdrfs $nodefile
IFS=":"
exec 3<&-
exec 3< $mmsdrfsFile
while read -u3 sdrfsLine
do
  # Parse the line.
  set -f ; set -A v -- - $sdrfsLine ; set +f

  IFS="$IFS_sv"    # Restore the default IFS settings.
  printLine=true   # Assume the line will be printed.

  # Change some of the fields depending on the type of line.
  case ${v[$LINE_TYPE_Field]} in

    $VERSION_LINE )
       # Increment the generation number.
       newGenNumber=${v[$SDRFS_GENNUM_Field]}+1
       v[$SDRFS_GENNUM_Field]=$newGenNumber
       ;;

    $MEMBER_NODE )
       # Add the reliable node name to nodefile.
       print -- "${v[$REL_HOSTNAME_Field]}" >> $nodefile
       checkForErrors "writing to file $nodefile" $?

       # If this is the line for the node that is executing
       # this command, set the preferredNode variable.
       [[ ${v[$NODE_NUMBER_Field]} = $ourNodeNumber ]] &&  \
         preferredNode=${v[$REL_HOSTNAME_Field]}
       ;;

    $SG_HEADR | $SG_ETCFS | $SG_MOUNT | $AUTHORIZED_FS )
       # If any of the above lines belongs to the file system
       # being deleted, remove the line from the mmsdrfs file.
       [[ ${v[$DEV_NAME_Field]} = $deviceName ]] &&  \
         printLine=false
       ;;

    $SG_DISKS )
       # If this disk belongs the file system being deleted, change
       # the SG_DISK line to indicate that the disk is now available.
       if [[ ${v[$DEV_NAME_Field]} = $deviceName ]]
       then
         # Reset relevant fields.
         v[$NODESETID_Field]=$FREE_DISK
         v[$DEV_NAME_Field]=$NO_DEVICE
         v[$LINE_NUMBER_Field]=0
         v[$EXCLUDE_Field]=$includedDisk
         v[$DISK_STATUS_Field]=""
       fi  # end if [[ ${v[$DEV_NAME_Field]} = $deviceName ]]
       ;;

    * )  # Pass all other lines without a change.
       ;;
  esac  # end Change some of the fields

  # Build and write the line to the new mmsdrfs file.
  if [[ $printLine = true ]]
  then
    print_newLine >> $newsdrfs
    checkForErrors "writing to file $newsdrfs" $?
  fi

  IFS=":"  # Change the separator back to ":" for the next iteration.

done  # end while read -u3 sdrfsLine

IFS="$IFS_sv"  # Restore the default IFS settings.

# Sort the new version of the mmsdrfs file.
LC_ALL=C $SORT_MMSDRFS $newsdrfs -o $newsdrfs


#############################################
# Lock the gpfs object to prevent mounts
# from taking place during the commit phase.
#############################################
[[ $getCredCalled = no ]] && getCred
setRunningCommand "$mmcmd" $primaryServer
checkForErrors setRunningCommand $?
gpfsLocked=yes


##############################################
# Call tsdelfs to mark the disks as free.
# The function will be performed only if the
# file system is not mounted anywhere.
##############################################
$mmcommon onactive $preferredNode $nodefile $NO_FILE_COPY $fqDeviceName  \
                   $CHECK_ALL $NO_LINK tsdelfs "$fqDeviceName"
rc=$?

# If the file system is still mounted, give up (msg already issued).
[[ $rc -eq $MM_FsMounted ]] &&  \
  cleanupAndExit

if [[ $rc -ne 0 ]]
then
  # tsdelfs failed.  If -p is not specified, the mmdelfs command fails too.
  # Otherwise, the tsdelfs error is ignored and the fs is removed from the sdr.
  if [[ -z $pflag ]]
  then
    printErrorMsg 104 $mmcmd tsdelfs
    cleanupAndExit
  else
    # Issue a warning.
    printErrorMsg 267 $mmcmd
  fi
fi  # end of if [[ $rc -ne 0 ]]


#################################################################
# Put the mmsdrfs file back.  This deletes the file system for
# newly-started daemons - they will not see the file system.
#################################################################
trap "" HUP INT QUIT KILL   # Disable until mmsdrfs update is done.
gpfsObjectInfo=$(commitChanges  \
   $fsHomeCluster $nsId $gpfsObjectInfo $newGenNumber $newsdrfs $primaryServer)
rc=$?
if [[ $rc -ne 0 ]]
then
  # Cannot replace file in the sdr.
  printErrorMsg 381 $mmcmd
  cleanupAndExit
fi


###################################################################
# The file system was successfully deleted.  Unlock the sdr.
###################################################################
[[ $sdrLocked = yes ]] &&  \
  freeLockOnServer $primaryServer $ourNodeNumber >/dev/null
sdrLocked=no
trap posttrap HUP INT QUIT KILL


######################################################################
# Propagate the changes to all affected nodes.  This will include
# removing of the stanza for the file system from /etc/filesystems,
# and removing the device name and mount point.
######################################################################
propagateSdrfsFile async $nodefile $newsdrfs $newGenNumber


###################################################
# If installed, invoke the syncfsconfig user exit.
###################################################
if [[ -x $syncfsconfig ]]
then
   print -- "$mmcmd:  Starting $syncfsconfig ..."
   $syncfsconfig
   print -- "$mmcmd:  $syncfsconfig finished."
fi

cleanupAndExit 0

