#!/bin/bash
#
# Deconfigures a zfcp lun.
#
# Following steps are required:
#
# 1.) set the SCSI ID offline
# 2.) delete the SCSI ID
# -> hotplug event scsi
# 

SCRIPTNAME=${0##*/}
HWDESC=$1

# Read in common functions
. ./scripts/functions
test -r ./config && . ./config

# Check for variables
if test -z "$SYSFS"; then
    message "sysfs not mounted, aborting."
    exit 1
fi

# Set defaults
if [ -z "$HWD_DEVICEPATH" ]; then
    HWD_DEVICEPATH=${SYSFS}/bus/ccw/devices/${HWD_BUSID}
fi

if [ ! -d "$HWD_DEVICEPATH" ]; then
    message "No hardware devicepath given, cannot configure"
    exit 1
fi

# Read in the configuration file
. ./hwcfg-${HWDESC}

# Set sysfs paths
_zfcp_dir=${HWD_DEVICEPATH}

# Delete all SCSI Ids
read _scsi_host_no < ${_zfcp_dir}/scsi_host_no

num_ids=0
for id in ${_zfcp_dir}/host$((_scsi_host_no))/*; do
    if [ -d $id ]; then
	echo "0" > ${id}/online
	echo "1" > ${id}/delete
	num_ids=$(expr $num_ids + 1)
    fi
done

# If no SCSI IDs has been found, no hotplug
# events have been generated either. So we need
# to deconfigure the adapter by hand.
if (($num_ids == 0)); then
    # No IDs found / configured
    # Tear down the adapter
    for tmp_wwpn in ${_zfcp_dir}/0x*; do
	if [ -d "$tmp_wwpn" ]; then
	    # Remove all luns
	    fcp_wwpn=${tmp_wwpn##*/}
	    for tmp_lun in ${tmp_wwpn}/0x*; do
		if [ -d "$tmp_lun" ]; then
		    fcp_lun=${tmp_lun##*/}
		    echo "$fcp_lun" > ${tmp_wwpn}/unit_remove
		    debug "Removing unit $fcp_wwpn:$fcp_lun"
		fi
	    done
	    # Recheck for failures
	    num_luns=0
	    for tmp_lun in ${tmp_wwpn}/0x*; do
		if [ -d "$tmp_lun" ]; then
		    num_luns=$(expr $num_luns + 1)
		fi
	    done
	    if (($num_luns == 0)); then
		echo "$fcp_wwpn" > ${_zfcp_dir}/port_remove
		debug "Removing port $fcp_wwpn"
	    else
		message "Error removing FCP port $fcp_wwpn: $num_luns units open"
	    fi
	fi
    done
    # Recheck for failures
    num_ports=0
    for tmp_wwpn in ${_zfcp_dir}/0x*; do
	if [ -d "$tmp_wwpn" ]; then
	    num_ports=$(expr $num_ports + 1)
	fi
    done
    if (($num_ports == 0)); then
	echo "0" > ${_zfcp_dir}/online
    else
	message "Error on deconfigure adapter $HWD_BUSID: $num_ports still open"
	exit 1
    fi
fi

# EOF
