#!/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
scsi_id=${$_zfcp_dir##*/}
saved_IFS="$IFS"
IFS=":"
set -- $scsi_id
scsi_host_num=$1
scsi_target_num=$3
scsi_lun_num=$4
IFS="$saved_IFS"

path=`echo $_zfcp_dir | sed "s@/host[0-9]\{1,\}/.*@@"`

# Find the fcp port corresponding to the scsi target
for tmp_wwpn in ${path}/0x*; do
    if [ -d $tmp_wwpn ]; then
	read tmp_target_num < $tmp_wwpn/scsi_id
	if (($tmp_target_num == $scsi_target_num)); then
	    wwpn=${$tmp_wwpn##*/}
	    break;
	fi
    fi
done

if [ "$wwpn" ]; then
    # Find the fcp lun corresponding to the scsi lun
    for tmp_lun in ${path}/$wwpn/0x*; do
	if [ -d $tmp_lun ]; then
	    read tmp_lun_num < $tmp_lun/scsi_lun
	    if (($tmp_lun_num == $scsi_lun_num)); then
		lun=${$tmp_lun##*/}
		break;
	    fi
	fi
    done
    # Remove if found
    if [ "$lun" ]; then
	message "Removing fcp unit $wwpn:$lun"
	echo "$lun" > ${path}/$wwpn/unit_remove
    fi
    # Recheck if the port still has luns open
    num_luns=0
    for tmp_lun in ${path}/$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 "$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
