#!/bin/bash
#
# Deconfigures a zfcp lun.
#
# Should be called after the SCSI id
# has been removed
#
# Following steps are required:
#
# 1.) remove the LUN corresponding to the scsi id
# 2.) Check if the port corresponding to the scsi id
#     has no other ports open
#     -> If so, remove the port
# 3.) Check if the device has no other ports open
#     -> If so, deactivate the device
#     -> hotplug event scsi_host
# 

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

# Set sysfs paths
_zfcp_dir=${HWD_DEVICEPATH}

# Find corresponding fcp wwpn:lun
if [ -d ${_zfcp_dir} ] ; then
    read _zfcp_lun < ${_zfcp_dir}/fcp_lun
fi
path=${_zfcp_dir%%/host*}
_rport_dir=${_zfcp_dir%%/target*}
_rport_num=${_rport_dir##*/}
if [ -d ${_rport_dir}/fc_remote_ports:${_rport_num} ] ; then
    read _zfcp_wwpn < ${_rport_dir}/fc_remote_ports:${_rport_num}/port_name
fi

if [ "$_zfcp_wwpn" -a "$_zfcp_lun" ]; then
    # Find the fcp lun corresponding to the scsi lun
    if [ -d "${path}/${_zfcp_wwpn}/${_zfcp_lun}" ] ; then
	message "Removing fcp unit $_zfcp_wwpn:$_zfcp_lun"
	echo $_zfcp_lun > ${path}/${_zfcp_wwpn}/unit_remove
    fi
    # Recheck if the port still has luns open
    num_luns=0
    for tmp_lun in ${path}/${_zfcp_wwpn}/0x*; do
	if [ -d $tmp_lun ]; then
	    num_luns=$(expr $num_luns + 1)
	fi
    done
    if (($num_luns == 0)); then
	# No, remove the fcp port
	echo "$_zfcp_wwpn" > ${path}/port_remove
	message "Removing fcp port $wwpn"
    fi
fi

# Recheck for open ports
num_ports=0
for tmp_wwpn in ${path}/0x*; do
    if [ -d $tmp_wwpn ]; then
	num_ports=$(expr $num_ports + 1)
    fi
done
if (($num_ports == 0)); then
    # Deactivate this adapter
    echo "0" > ${path}/online
    message "Deactivating adapter $HWD_BUSID"
else
    debug "Could not deactivate adapter $HWD_BUSID: $num_ports ports open"
fi

# EOF
