#!/sbin/sh

################################################################################
#
# Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#	Copyright 1992-95 AT&T Global Information Solutions
#
# ident	"@(#)ludelete.sh	5.21	08/08/06 SMI"
#
# USAGE     : ludelete ( [-n] "be_name" )
# FUNCTION  : Deletes the specified boot environment.
#
################################################################################

LU_PROG_FULL_PATH="$0"
LU_PROG_NAME="`basename ${LU_PROG_FULL_PATH}`"; export LU_PROG_NAME

TMP_LUTAB="/tmp/.ludelete.lutab.$$"
TMPMNT="/tmp/.ludelete.mnt.$$"

# ALGORITHM:
# 1. Checks for "copy lock". If it exists, see to it that the copy lock is
#    not held for target BE.
# 2. Determine "be_name" is not the current_be and not the activated BE on
#    the next reboot.
# 3. Remove all references of "be_name" in lutab.
# 4. Call luupdall  to update the lutab.
# 5. Update device table to reflect that the devices which were part of
#    "be_name" to be free.

################################################################################
# Name:		usage
# Description:	output command line usage information; then call exit_script to 
#		terminate execution.
# Local Prefix:	<none>
# Arguments:	$1 = exit code for script ("" defaults to "3").
# Example:	usage 3
# Returns:	<none> 
################################################################################

usage()
{
  ${LUPRINTF} -p2 "`gettext 'USAGE: %s [ -X ] [ -l error_log ] [ -o outfile ] \
( [ -n ] BE_name )'`" "${LU_PROG_NAME}"
  ${LUPRINTF} -Ip2 "`gettext 'Any BE_name should be enclosed in single quotes.'`"
  if [ -z "$1" ] ; then
    exit_script 3 no
  fi
  exit_script "$1" no
}

################################################################################
# Name:		interruptHandler
# Description:	Handle an armed shell "trap"
# Local Prefix:	<none>
# Arguments:	<none>
# Example:      trap "interruptHandler" 1 2 3 9 15
# Returns:	call script cleanup function with exit code "4"
################################################################################

interruptHandler()
{
  # Reset all traps to be ignored so that termination can take place
  # without further interrupts

  # 1- SIGHUP (hangup)
  # 2- SIGINT (user interrupt)
  # 3- SIGQUIT (user quit)
  # 9- SIGKILL (kill process - can not be caught or ignored :)
  # 15- SIGTERM (software termination request)
  trap "" 1 2 3 9 15

  # Output indication of interrupt processed
  ${LUPRINTF} -Ilp2 "`gettext 'Interrupted (Signal received): cleaning up...'`"

  # We are not sure here as to whether the slices of $BE_NAME are marked free
  # or not. So we mark the slices as occupied.

  # There is a possibility that the entry corresponding to BE_NAME, removed
  # and  updated, So we again call luupdall ${LU_LUTAB_FILE}, after moving the 
  # original lutab 
  $LUBIN/luupdall ${LU_LUTAB_FILE}
  exit_script 1
}

################################################################################
# Name:		exit_script
# Description:	Perform cleanup operations and exit this script.
# Local Prefix:	<none>
# Arguments:	$1 = optional exit value for script ("" or none is = "0")
# Example:      exit_script "0"
# Returns:	<none>
################################################################################

exit_script()
{
  /bin/rm -f $TMP_LUTAB

  # Determine the exit status code.

  retcode="0"
  if [ -n "$1" ] ; then
    retcode="$1"
  fi

  # If we mounted the BE, then unmount it now.
  if [ "$ABE_mounted" = yes ]; then
      $LUBIN/luumount -f $BE_NAME
  fi

  # Output the exit status message if not suppressed. 
  if [ -z "$2" ] ; then
    if [ "${retcode}" -eq "0" ] ; then
      ${LUPRINTF} -lp1 "`gettext 'Boot environment <%s> deleted.'`" "${BE_NAME}"
    else
      ${LUPRINTF} -lp1 "`gettext 'Unable to delete boot environment.'`"
    fi
  fi

  exit "${retcode}"
}


################################################################################
# Name:		<main>
# Description:	Main code (outside of any function definitions) - executed at script startup.
# Local Prefix:	<none>
# Arguments:	$0...$n = All arguments specified by user on command line that invoked this script.
################################################################################

# Dot the defaults file.

if [ ! -s /etc/default/lu ] ; then
  echo "${LU_PROG_NAME}: ""`gettext 'ERROR: Live Upgrade not installed properly (/etc/default/lu not found).'`"
  exit 1
fi
. /etc/default/lu

LUBIN=${LUBIN:=/usr/lib/lu}
### LU_OPTFS=${LU_OPTFS:=/etc/lu/optfs}
COPYLOCK=${COPYLOCK:=/etc/lu/COPY_LOCK}
NEXT_ACTIVE=${NEXT_ACTIVE:=/etc/lu/.NEXT_ACTIVE}

# Dot the Live Upgrade library functions.

if [ ! -s $LUBIN/lulib ] ; then
  echo "${LU_PROG_NAME}: ""`gettext 'ERROR: The Live Upgrade product is not installed properly (${LUBIN}/lulib not found).'`"
  exit 1
fi

. $LUBIN/lulib

# Check for existence and non-zero size of lutab file.

if [ ! -f ${LU_LUTAB_FILE} -o ! -s ${LU_LUTAB_FILE} ] ; then
  ${LUPRINTF} -Eelp2 "`gettext 'No boot environments are configured on this system.'`"
  exit 1
fi

  ######################################################################################
  ##################### Command line option and argument processing ####################
  ######################################################################################

# Reset all command line parse flags to default values.
flag_f="" # -f - Force delete ABE even if last on its disk
flag_o="" # -o f - output file path.
flag_l="" # -l f - log file path.
flag_n="" # -n "n" - be name.
flag_x="" # -x n = set debug level to n (PRIVATE).

while [ $# -ne 0 ] ; do
  while getopts fl:n:o:x:X c
  do
    case $c in
      f) # -f - force delete ABE even if last on its disk
	  flag_f=yes
	  ;;
      l) # -l f - error log file path.
	 # This overrides the LU_ERROR_LOG_FILE setting read from /etc/default/lu
	 lulib_cannot_duplicate_option "${flag_l}" "${OPTARG}" "-l"
	 ${LUPRINTF} -lp2D - "`gettext 'Verifying that the error log file <%s> specified can be created and appended to.'`" "${OPTARG}"
	 ERRMSG="`${LUPRINTF} -c \"${OPTARG}\" 2>&1`"
	 if [ $? -ne 0 ] ; then
	   [ -n "${ERRMSG}" ] && ${LUPRINTF} -elp2 '%s' "${ERRMSG}"
	   ${LUPRINTF} -Eelp2 "`gettext 'Argument <%s> to -l option may not be created or appended to.'`" "${OPTARG}"
	   exit_script 3
	 fi
	 flag_l="${OPTARG}"
	 lulib_set_error_log_file "${flag_l}"
	 ;;
      n) # -n "n" - be name.
	 lulib_cannot_duplicate_option "${flag_n}" "${OPTARG}" "-n"
	 flag_n="${OPTARG}"
	 ;;
      o) # -o f - output file path.
	 # This overrides the LU_SESSION_LOG_FILE setting read from /etc/default/lu
	 lulib_cannot_duplicate_option "${flag_o}" "${OPTARG}" "-o"
	 ${LUPRINTF} -lp2D -  "`gettext 'Verifying that the session log file <%s> can be created and appended to.'`" "${OPTARG}"
	 ERRMSG="`${LUPRINTF} -c \"${OPTARG}\" 2>&1`"
	 if [ $? -ne 0 ] ; then
	   [ -n "${ERRMSG}" ] && ${LUPRINTF} -elp2 '%s' "${ERRMSG}"
	   ${LUPRINTF} -Eelp2 "`gettext 'Argument <%s> to -o option may not be created or appended to.'`" "${OPTARG}"
	   exit_script 3
	 fi
	 flag_o="${OPTARG}"
	 lulib_set_session_log_file "${flag_o}"
	 ;;
      x) # -x n - set debug level to n (PRIVATE).
	 # This overrides the default setting read from /etc/default/lu
	 lulib_cannot_duplicate_option "${flag_x}" "${OPTARG}" "-x"
	 /bin/test "${OPTARG}" -ge 0 2>/dev/null
	 if [ $? -gt 1 ] ; then
	   ${LUPRINTF} -Eelp2 "`gettext 'Argument <%s> to -x option is not a number.'`" "${OPTARG}"
	   usage 3
	 fi
	 flag_x="${OPTARG}"
	 lulib_set_debug "${flag_x}"
	 ;;
      X) # -X - set XML output mode.
	  lulib_set_output_format 'xml'
	  ;;
      \?) # unknown - option.
	  usage 3
	  esac
  done

  # Found either end of arguments, +option, or non-option argument; shift out
  # what has been processed so far; if a non-option argument is present
  # capture it and continue processing the command line arguments.
  shift `/bin/expr $OPTIND - 1`
  OPTIND=1
  if [ $# -ne 0 -a "$1" = '+X' ] ; then
      # +X - set TEXT output mode.
      lulib_set_output_format 'text'
      shift
  else
    break
  fi
done

# Fixup debug, session log, and error log settings
lulib_fixup_startup_settings

  ######################################################################################
  ############ Validate all command line arguments and options as possible #############
  ######################################################################################

# Validate the number of arguments.
if [ $# -gt 1 ] ; then
  ${LUPRINTF} -Eelp2 "`gettext 'The boot environment name should be enclosed in single quotes, like %c%s%c.'`" "'" "$*" "'"
  usage 3
fi


  ######################################################################################
  ############## If x86, determine the location of the GRUB menu ###############
  ######################################################################################
if [ "$LU_SYSTEM_ARCH" = "i386" ]; then
   
   lulib_ask_for_menu_propagate
   if [ "$?" -eq 1 ]; then
      exit_script 2
   fi
fi
  ######################################################################################


# Determine the status of SDS
lulib_discover_sds_installation

# Name of target BE (ABE).
if [ -n "${flag_n}" -a -z "$1" ] ; then
  BE_NAME="${flag_n}"
elif [ -z "${flag_n}" -a -n "$1" ] ; then
  BE_NAME="$1"
elif [ -z "${flag_n}" -a -z "$1" ] ; then
  ${LUPRINTF} -Eelp2 "`gettext 'You must specify the BE to delete either with the <-n> option or by providing the BE name on the command line.'`"
  usage 3
else
  ${LUPRINTF} -Eelp2 "`gettext 'You must specify the BE to delete either with the <-n> option or by providing the BE name on the command line, but not both.'`"
  usage 3
fi

# Determine the name of Current BE.
CURR_BE=`lulib_lucurr`
if [ "$?" -ne "0" ] ; then
  ${LUPRINTF} -Eelp2 "`gettext 'Unable to determine the name of the current active BE.'`"
  exit_script 2
fi

# Make sure the target BE specified is valid.
lulib_is_be_name_inuse "${BE_NAME}"
if [ "$?" -ne "0" ] ; then
  ${LUPRINTF} -Eelp2 "`gettext 'Unable to delete boot environment <%s>.'`" "${BE_NAME}"
  usage
fi

# Issue a warning if the BE is currently mounted.
# Obtain status of BE to be deleted (in XML) from the "lustatus -X" command
# Lines from "lustatus -X" look like this:
# 	<beStatus name="c0t2d0s0" complete="yes" active="no" \
#	activeOnReboot="no" busy="no" status="" deletable="yes" \
#	mounted="yes" mountPoint="/a" />
# Extract mountPoint= value for the BE to be deleted
beMntpt=`${LUBIN}/lustatus -X "${BE_NAME}" 2>/dev/null \
	| /bin/grep '^<beStatus ' \
	| /bin/fgrep ' mounted="yes"' \
	| /bin/sed 's/.* mountPoint="//' \
	| /bin/cut -d'"' -f1 \
	| ${LUETCBIN}/ludo xml_decode_string`
if [ -n "${beMntpt}" ] ; then
  ${LUPRINTF} -Welp2 "`gettext 'Boot environment <%s> has one or more file \
systems mounted at <%s>.'`" "${BE_NAME}" "${beMntpt}"
fi

# Obtain the BE ID for the BE specified
ID="`${LUETCBIN}/ludo get_be_id \"$BE_NAME\" 2>&1`"
if [ $? != 0 -o -z "${ID}" ] ; then
  [ -n "${ID}" ] && ${LUPRINTF} -Eelp2 '%s' "${ID}"
  ${LUPRINTF} -Eelp2 "`gettext 'Unable to delete the boot environment <%s>.'`" "${BE_NAME}"
  usage
fi

# Verify that $BE_NAME is not the activated BE
if [ -s "$NEXT_ACTIVE" ] ; then
  ACTIVE="`/bin/cat $NEXT_ACTIVE 2>&1`"
  if [ "$?" -ne "0" ] ; then
    ${LUPRINTF} -Eelp2 '%s' "${ACTIVE}"
    ${LUPRINTF} -Eelp2 "`gettext 'Could not determine the next active BE.'`"
    exit_script 2
  fi
fi

if [ "$BE_NAME" = "$ACTIVE" ] ; then
  ${LUPRINTF} -Eelp2 "`gettext 'The boot environment <%s> is the next active BE. You are \
not allowed to delete the next active BE. To delete BE <%s>, please run \
luactivate with a BE other than <%s> and then run ludelete on <%s> again.'`" \
"${BE_NAME}" "${BE_NAME}" "${BE_NAME}" "${BE_NAME}"
  exit_script 1
fi

# Determine that $BE_NAME is not the current_be.

if [ "$CURR_BE" = "$BE_NAME" ] ; then
  ${LUPRINTF} -Eelp2 "`gettext 'The boot environment <%s> is the current BE.'`" "${CURR_BE}"
  ${LUPRINTF} -Eelp2 "`gettext 'You are not allowed to delete the current active BE.'`"
  exit_script 2
fi

# If user did not use the "force" flag, check if this is the last BE in the disk 
if [ "$LU_SYSTEM_ARCH" = i386 ]; then
   if [ -z "${flag_f}" ]; then
      ${LUPRINTF} -lp1 "`gettext 'Checking if last BE on any disk...'`"
      lulib_check_last_BE "$BE_NAME"
      if [ "$?" -ne 0 ]; then
         ${LUPRINTF} -Eelp2 "`gettext 'This boot environment <%s> is the last BE on the above disk.'`" "${BE_NAME}"
         ${LUPRINTF} -Eelp2 "`gettext 'Deleting this BE may make it impossible to boot from this disk.'`" 
         ${LUPRINTF} -Eelp2 "`gettext 'However you may still boot solaris if you have BE(s) on other disks.'`"
         ${LUPRINTF} -Eelp2 "`gettext 'You *may* have to change boot-device order in the BIOS to accomplish this.'`"
         ${LUPRINTF} -Eelp2 "`gettext 'If you still want to delete this BE <%s>, please use the force option (-f).'`" "${BE_NAME}"
         exit_script 2
      else
         ${LUPRINTF} -lp1 "`gettext 'BE <%s> is not the last BE on any disk.'`" "${BE_NAME}"
      fi
   fi
fi

#
# Delete the GRUB menu entry (if any) for the BE.
#
if [ "$LU_SYSTEM_ARCH" = i386 -o -x /sbin/zpool ]; then
   lulib_delete_menu_entry "${BE_NAME}" "$ID"
   if [ "$?" -ne 0 ]; then
      ${LUPRINTF} -Eelp2 "`gettext 'Unable to delete menu entry for deleted boot environment <%s>.'`" "${BE_NAME}"
      exit_script 1
   fi
fi

#
# Determine the block device and fstype for the root of the ABE.
# This is used to enumerate and deal with the zones in the ABE.
#
ABE_ICF="/etc/lu/ICF.$ID"
SAVEIFS="$IFS"

if [ -n "${beMntpt}" ] ; then
    ABE_mntpt="$beMntpt"
    lulib_zone_check "$ABE_mntpt" "exit_script 1"
    lulib_list_zones "$beMntpt" |
    while IFS=: read zoneid zonename state junk; do
	if [ "$state" = mounted ]; then
	    zoneadm -R "$beMntpt" -z $zonename unmount
	fi
    done
elif [ -f "$ABE_ICF" ]; then
    ABE_mntpt=`LU_OUTPUT_FORMAT=text ${LUBIN}/lumount -Zi "${ABE_ICF}"`
    if [ "$?" -ne 0 -o -z "${ABE_mntpt}" ] ; then
	${LUPRINTF} -Eelp2 "`gettext 'Cannot mount BE <%s>.'`" "${BE_NAME}"
	exit_script 1
    fi
    ABE_mounted=yes
    lulib_zone_check "$ABE_mntpt" "exit_script 1"
else
    if /bin/egrep -v "^[       ]*$ID[  ]*:.*$" $LU_LUTAB_FILE > $TMP_LUTAB
    then
	cp $TMP_LUTAB $LU_LUTAB_FILE
	exit_script 0
    fi
fi

lulib_list_zones -i "$ABE_mntpt" |
while IFS=: read zoneid zonename state path junk; do
    IFS="$SAVEIFS"
    [ $zonename = global ] && continue

    if [ "$state" != installed ]; then
	$LUPRINTF -Eelp2 "`gettext 'zone <%s> state is <%s>; cannot remove'`" \
	    $zonename "$state"
	continue
    fi

    $LUPRINTF -lp2D 2 "deleting zone <%s> path <%s>" $zonename "$path"

    # If storage for this zone was created on a shared mount point,
    # then remove it.  (Otherwise, for unshared mount points, we just
    # free up the device and we're done.)

    # First, find out if the target is read-only, because shared
    # mounts will be read-only.  Next, try to resolve via lofs.
    # Things that are administratively declared read-only will not
    # resolve.

    lulib_path_writable "$path"
    if [ $? -ne 1 ]; then
	$LUPRINTF -lp2D 2 "zone path <%s> is writable" "$path"
	continue
    fi
    rawpath=`lulib_resolve_lofs "$ABE_mntpt" "$path"`
    if [ "$rawpath" = "$path" ]; then
	$LUPRINTF -lp2D 2 "zone path <%s> is not lofs" "$path"
	continue
    fi

    # We now know we're dealing with a zone on a shared mount point.
    # Remove it.

    #
    # If the zone root is a ZFS dataset then destroy the clone as well as
    # the snapshot if there is one.
    #
    zone_dataset_name=`lulib_get_zfs_dataset_from_mntpt $rawpath`
    if [ -n "$zone_dataset_name" ] ; then
	# unmount the zone path before deleting it
	lulib_unmount_pathname $path

	lulib_destroy_BE_dataset $zone_dataset_name
	if [ $? != 0 ] ; then
		$LUPRINTF -lp2D 2 "Cannot destroy cloned dataset <%s>" \
		    "$zone_dataset_name"
	fi
    else
	$LUPRINTF -lp2D 2 "deleting path <%s>" "$rawpath"
	rm -rf "$rawpath"
    fi
done

ABE_root_logical_bdev=`${LUETCBIN}/lurootspec -m "${ABE_mntpt}"`
if [ "$?" -ne 0 -o -z "${ABE_root_logical_bdev}" ]; then 
	#
	# We must know what ABE_root_logical_bdev is. It is
	# is required later to determine if it contains the
	# GRUB information and if the root is zfs then it is 
	# needed to delete the BE datasets.
	#
	${LUPRINTF} -Eelp2 "`gettext 'Cannot determine root specification for BE <%s>.'`" "${BE_NAME}"
	exit_script 1
	else
	ABE_root_fstyp=`lulib_fstyp "$ABE_root_logical_bdev"`
	if [ "$?" -ne 0 -o -z "$ABE_root_fstyp" ]; then
	${LUPRINTF} -Welp2 "`gettext 'Cannot determine fstype for BE <%s>.'`" "${BE_NAME}"
	ABE_root_fstyp=""
	fi
fi

ABE_mounted=no
$LUBIN/luumount -f -i ${ABE_ICF} 2> /dev/null
if [ $? -ne 0 ]; then
    $LUPRINTF -Eelp2 "`gettext \
	'Unable to unmount file systems for boot environment <%s>.'`" \
	"${BE_NAME}"
    exit_script 1
fi

# 1. Call lulib_validate_lulock and check return code
# 2. If return code is 2, print that a scheduled job exists
# 3. If return code is 3, print a currently running job exists
# 4. If return code is 0, lock does not exist. Process BE delete
# 5. If return code is 1, lock was stale and process BE delete


lulib_validate_lulock

case "$?" in
	0) # COPY_LOCK doesn't exist
	   ${LUPRINTF} -lp2D - "`gettext 'No Copy Lock file <%s> exists.'`" "${COPYLOCK}" 
	   ${LUPRINTF} -lp2D - "`gettext 'No jobs are currently scheduled.'`"
           ;;

	1) #COPY_LOCK existed but was no longer valid and hence removed
	   ${LUPRINTF} -lp2D - "`gettext 'A previously existing copy lock <%s> was invalid and has been removed.'`" "${COPYLOCK}"
	   ${LUPRINTF} -lp2D - "`gettext 'No jobs are currently scheduled.'`"
	   ;;

	2) # COPY_LOCK exists and there is a valid scheduled job 
	   #DOT in INFO from COPY_LOCK
	   . $COPYLOCK
	   ${LUPRINTF} -lp2D - "`gettext 'A Copy Lock file <%s> exists: Status <%s> Source BE <%s> Target BE <%s>.'`" "${COPYLOCK}" "${CL_STATUS}" "${CL_SOURCE_BE}" "${CL_TARGET_BE}"
	   ${LUPRINTF} -Eelp2 "`gettext 'Copy Lock on this BE exists, cannot delete BE <%s>.'`" "${BE_NAME}"
	   exit_script 1
	   ;;

	3) #COPY_LOCK exists and a valid running job exists.
	   #DOT in INFO from COPY_LOCK
           . $COPYLOCK	
	   ${LUPRINTF} -lp2D - "`gettext 'A Copy Lock file <%s> exists: Status <%s> Source BE <%s> Target BE <%s>.'`" "$
{COPYLOCK}" "${CL_STATUS}" "${CL_SOURCE_BE}" "${CL_TARGET_BE}"
	   ${LUPRINTF} -Eelp2 "`gettext 'Currently running job exists, cannot delete BE <%s>.'`" "${BE_NAME}"
	   exit_script 1
	   ;; 

	*) #Unkown option
	   exit_script 1
	   ;;
esac


# Determine the devices to be marked free.

${LUPRINTF} -lp1 "`gettext 'Determining the devices to be marked free.'`"

# Get configuration for CBE - exit with an error if that cannot be determined.

CBE_ICF="`$LUBIN/lumk_iconf -F \"$CURR_BE\"`"
if [ "$?" -ne "0" -o -z "${CBE_ICF}" ] ; then
  ${LUPRINTF} -Eelp2 "`gettext 'Unable to determine disk partition configuration information for BE <%s>.'`" "${CURR_BE}"
  exit_script 1
fi

# Get configuration for the target ABE - pass in -E to lumk_iconf
# which means dont return an error if the configuration is missing -
# this allow deletion of incomplete BEs.

BE_ICF="`$LUBIN/lumk_iconf -F -E \"$BE_NAME\"`"
if [ "$?" -ne "0" -o -z "${BE_ICF}" ] ; then
  ${LUPRINTF} -Welp2 "`gettext 'Unable to determine disk partition configuration information for BE <%s>.'`" "${BE_NAME}"
  BE_ICF="/etc/lu/ICF.{ID}"
  [ ! -f "${BE_ICF}" ] && BE_ICF=''
fi

# Determine the slices/datasets to be freed.
free_dev=''
if [ -f "${BE_ICF}" -a -s "${BE_ICF}" ] ; then
  free_dev=`${LUETCBIN}/ludo filter_shared_and_swap $CBE_ICF < $BE_ICF | /bin/awk -F: '{ printf("%s ", $3) }'`
fi

if [ -z "${free_dev}" ] ; then
  ${LUPRINTF} -Welp2 "`gettext 'Unable to determine the devices/datasets to be freed for BE <%s>.'`" "${BE_NAME}"
fi

# Create mount_list which specifies the devices that are mounted. This is
# basically to verify later that the devices of ABE are not mounted.

mount_list=`/usr/sbin/mount | /bin/awk '{ printf("%s ", $3) }'`

if [ $? != 0 ] ; then
  ${LUPRINTF} -Eelp2 "`gettext 'Unable to determine the mounted devices.'`"
  exit_script 1
fi

# Verify that ABE devices are not mounted.

mounted=0
mountsFound=""
for i in $free_dev ; do
  echo " $mount_list" | /bin/egrep " $i "  > /dev/null 2>&1
  if [ "$?" -eq "0" ] ; then
    mounted=`expr $mounted + 1`
    if [ -z "${mountsFound}" ] ; then
      mountsFound="$i"
    else
      mountsFound="${mountsFound} $i"
    fi
  fi
done

# If any slices belonging to the BE to delete are mounted, warn the user
# but go ahead and allow the delete - this is to allow for deleting of BEs
# that may no longer be valid because customer reused slices belonging to
# original BE.
if [ "$mounted" -ne 0 ] ; then
  ${LUPRINTF} -Welp2 "`gettext 'Slices <%s> belonging to boot environment <%s> are currently mounted.'`" "${mountsFound}" "${BE_NAME}"
fi

ERRMSG="`/bin/cp -p \"${LU_LUTAB_FILE}\" \"$TMP_LUTAB\" 2>&1`"
if [ "$?" -ne "0" ] ; then
  [ -n "${ERRMSG}" ] && ${LUPRINTF} -Eelp2 '%s' "${ERRMSG}"
  ${LUPRINTF} -Eelp2 "`gettext 'Unable to save backup copy of <%s>.'`" "${LU_LUTAB_FILE}"
  exit_script 1
fi

# signal handling for cleanup.
# 1- SIGHUP (hangup)
# 2- SIGINT (user interrupt)
# 3- SIGQUIT (user quit)
# 9- SIGKILL (kill process - can not be caught or ignored :)
# 15- SIGTERM (software termination request)
trap "interruptHandler" 1 2 3 9 15

# 3. Remove all references of $BE_NAME in ${LU_LUTAB_FILE}

${LUPRINTF} -lp1 "`gettext 'Updating boot environment configuration database.'`"

/bin/egrep -v "^[       ]*$ID[  ]*:.*$" $TMP_LUTAB > ${LU_LUTAB_FILE}

if [ "$?" -ne "0" ] ; then
  ${LUPRINTF} -Eelp2 "`gettext 'Unable to remove BE configuration database <%s> entries of BE <%s>.'`" "${LU_LUTAB_FILE}" "${BE_NAME}"
  /bin/mv -f $TMP_LUTAB ${LU_LUTAB_FILE}
  exit_script 1
fi

# Cleanup/rename and compare databases

#copy the parent files (with BE_NAME as child) )if grandchildren exist
# with a parent name of BE_NAME

if [ -d "${LU_COMPARE_DATABASE_DIR}" ] ; then
	OLD_PWD=`/bin/pwd`
	cd ${LU_COMPARE_DATABASE_DIR}
	rmlist=""
	BE_NAME2=`echo $BE_NAME | sed 's/ /___/g;s%/%_:_%g'`
	for gc in `/bin/ls "${BE_NAME2}":* 2> /dev/null | /bin/awk -F":" ' { print $2 } '`
	do
		/bin/ls *:"{$BE_NAME2}" > /dev/null 2>&1
		if [ "$?" != "0" ] ; then
			continue
		fi
		gp=`/bin/ls *:"${BE_NAME2}" | /bin/awk -F":" ' { print $1 } '`
		/bin/cp "${gp}:${BE_NAME2}" "${gp}:${gc}"
	done

	#remove all remaining databases with BE_NAME as child
	/bin/rm -f "${BE_NAME2}":* *:"${BE_NAME2}"
	lulib_update_compare

	cd ${OLD_PWD}
fi

# Update lutab and description to all defined BE's.
trap "" 1 2 3 9 15

# Remove any settings from the global database file
${LUETCBIN}/ludo remove_file_from_xml_db "${LU_DB_GLOBAL}" "${ID}" 'beFilterFile'
${LUETCBIN}/ludo remove_setting_from_xml_db "${LU_DB_GLOBAL}" "${ID}" 'beFilterSpecifications' 'integrityCheck'

# Remove any description for this BE.
$LUBIN/ludesc -d "${ID}"

# Remove all databases for this BE.
/bin/rm -f "/etc/lu/ICF.$ID" "/etc/lu/INODE.$ID" "/etc/lu/vtoc.$ID" 2>/dev/null 1>&2

# Update the ${LU_LUTAB_FILE} file on all BEs.
${LUPRINTF} -lp1 "`gettext 'Updating all boot environment configuration databases.'`"
$LUBIN/luupdall ${LU_LUTAB_FILE}
if [ $? != 0 ] ; then
  ${LUPRINTF} -Eelp2 "`gettext 'Unable to propagate the files <%s> to all boot environments.'`" "${LU_LUTAB_FILE}"
  exit_script 1
fi

# If the ABE root is zfs then destroy the BE datasets if they aren't mounted
if [ "$ABE_root_fstyp" = "zfs" -a "$mounted" -eq "0" ] ; then

	# first destroy any zones associated with the BE
	lulib_list_zone_datasets "$BE_NAME" | while read dataset; do
		lulib_demote_and_destroy_dataset "$dataset"
	done

	# then destroy all the datasets in the BE
	lulib_demote_and_destroy_dataset "$ABE_root_logical_bdev"
fi

# Successful...
exit_script 0
