# -*- shell-script -*-

# 27device_scsi_sysfs - SCSI device support using sysfs.

# This file is part of the Linux lsvpd package.

# (C) Copyright IBM Corp. 2004, 2005

# Maintained by Martin Schwenke <martins@au.ibm.com>

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
    
# $Id: 27device_scsi_sysfs,v 1.23 2005/06/14 04:24:03 martins Exp $

[ -n "$sysfs_dir" ] || return 0

# This should work with Linux >= 2.6.2.
[ -d "${sysfs_dir}/class/scsi_generic" ] || modprobe sg >/dev/null 2>&1
[ -d "${sysfs_dir}/class/scsi_generic" ] || return 0

######################################################################

add_device_hook_scsi ()
{
    # Uses: bus_info, device_adapter_name
    # Sets: device_bus_dir, yl

    sysfs_add_device_hook_common || sysfs_scsi_usb_hack || return 1

    # FIXME: this may not be correct for USB.
    device_set_yl "scsi"
}

remove_device_hook_scsi ()
{
    # Uses: device_bus_dir
    # Sets: bus_info

    local dn="${device_bus_dir%/*}" # dirname
    # FIXME: Gross hack, just to make it work for now...
    local t
    read t < "${device_bus_dir}/linux,vpd/000/YL"
    t="${t##*/}"
    bus_info="scsi/${t}"
}

######################################################################

sysfs_scsi_usb_hack ()
{
    # Uses: device_adapter_name, bus_info
    # Sets: adapter_bus_dir

    local sysfs_adapter_class
    set_sysfs_adapter_class "$scsi"
    local l="${sysfs_dir}/class/${sysfs_adapter_class}/${device_adapter_name}/device"

    if [ -L "$l" ] && cd -P "$l" ; then
       
	local t="$PWD"
	cd "$OLDPWD"

	case "$t" in
	    */usb*/${device_adapter_name})
		device_adapter_name="${t#*/usb}"
		device_adapter_name="usb${device_adapter_name%%/*}"

		# Yuck!
		local old_bus_info="$bus_info"
		local bus_info="usb/${bus_info#scsi/}"
		add_device_hook_common || return 1

		t="${t#*/${device_adapter_name}/}"
		device_bus_dir="${adapter_bus_dir}/${t}"
		bus_alias_set "$old_bus_info" \
		    "${device_bus_dir#${db_bus_dir}/}"

		device_backlink_adapter_bus_dir \
		    "$device_bus_dir" "$adapter_bus_dir"
		;;
	esac
    fi

    return 0
}
