#!/bin/bash

FC_SYSFS="/sys/class/fc_host"

## 
# Show information about FC devices in format:
# symbolic name | fc_host | wwpn | fc_id | state | [neighbour wwpn] | [neighbour fc_id]
# NOTE: the same information can be obtained by a `systool` util ftom sysfsutils
function fc_list_hba() {
	host_list=`ls -1 /sys/class/fc_host 2>/dev/null`
	[ $? -ne 0 ] && return 0
	
	for h in $host_list; do
		name=`cat $FC_SYSFS/$h/symbolic_name`
		[ $? -ne 0 ] && name=???
		
		wwpn=`cat $FC_SYSFS/$h/port_name`
		[ $? -ne 0 ] && wwpn=???
		
		fc_id=`cat $FC_SYSFS/$h/port_id`
		[ $? -ne 0 ] && fc_id=???
		
		state=`cat $FC_SYSFS/$h/port_state`
		[ $? -ne 0 ] && state=???
		
		# neighbour may not exist
		neigh_wwpn=`cat $FC_SYSFS/$h/device/rport-*/fc_remote_ports/rport-*/port_name 2>/dev/null` && \
			neigh_fc_id=`cat $FC_SYSFS/$h/device/rport-*/fc_remote_ports/rport-*/port_id 2>/dev/null`
			
		if [ $? -eq 0 ]; then
			echo "$name | $h | $wwpn | $fc_id | $state | $neigh_wwpn | $neigh_fc_id"
		else
			echo "$name | $h | $wwpn | $fc_id | $state"
		fi
		
	done 

	return 0 
}

function fc_hba_wwpn() {
	local fc_devs=`fc_list_hba`
	[ $? -ne 0 ] && return 1
	
	echo "$fc_devs" | cut -d '|' -f3 | sed "s/^[ \t]0x*//"
	return 0
}

# --------------------------------------------------------------------------------------
# vstorage scsi target interface

function fc_validate_addr() {
	local wwn=$1
	echo $wwn | cut -d 'x' -f2 | grep '^[[:xdigit:]]\{16\}$'
	return $?
}

function fc_init_host() {
	return 0
}

function fc_remove_addr() {
	return 0
}

function fc_add_addr() {
	return 0
}

function fc_get_initiators() {
	local port=$1

	fc_devs=`fc_list_hba`
	[ $? -ne 0 ] && return 1

	if [ -z "$port" ]; then
		echo "$fc_devs" | cut -d '|' -f6 | cut -d 'x' -f2
		return 0
	fi

	dev=`echo "$fc_devs" | grep $port`
	if [ $? -ne 0 ]; then
		echo "No FC HBA found with wwpn '$port'"
		return 2
	fi

	echo "$dev" | cut -d '|' -f6 | cut -d 'x' -f2
	return 0
}
