#!/bin/bash
# SPDX-License-Identifier: MIT
#
# qeth - collect state for qeth resources.
#
# Copyright IBM Corp. 2023
#
# Usage: qeth [<datafile>]
#
# If a YAML datafile was specified, determine characteristics of all mentioned
# resources. Otherwise list all available resources.
#

DATAFILE="$1"

LIBEXEC="${TELA_FRAMEWORK:-$(readlink -f $(dirname $0)/../../..)}"/src/libexec
source $LIBEXEC/lib/common.bash || exit 1
source $LIBEXEC/lib/common-network.bash || exit 1

QETH="/sys/bus/ccwgroup/drivers/qeth"

shopt -s nullglob

function check_attr() {
	local sysfs="$1" attr="$2" indent="$3" value

	read value 2>/dev/null <"$sysfs/$attr" || return
	[[ "$value" =~ ' ' ]] && value="\"$value\""
	[[ -z "$indent" ]] && indent=0
	printf "%*s%s: %s\n" $indent "" $attr $value
}

function check_qeth() {
	local id="$1" sysfs online if_name

	canonical_ccwdev_id id $id || return 1
	sysfs="$QETH/$id"

	[[ -e "$sysfs" ]] || return 1

	# Create output
	echo "qeth $id:"
	echo "  busid: $id"
	echo "  sysfs: $sysfs"

	check_ccwdev_chpids "$id" "  " "_tela_copy ../../chpid " 1 ""
	check_attr $sysfs online 2
	check_attr $sysfs layer2 2
	check_attr $sysfs card_type 2
	check_attr $sysfs portno 2

	read if_name 2>/dev/null <$sysfs/if_name
	if [[ -n "$if_name" ]] ; then
		echo "  netdev:"
		echo "    if_name: $if_name"
		check_attr $sysfs/net/$if_name/ speed 4
		check_netdev_ip "$if_name"
	fi

	return 0
}

function get_state() {
	local IFS=$'\n' count=0

	while read -r line ; do
		[[ ${line:0:5} != "qeth " ]] && continue
		id=${line:5}
		id="${id%:}"

		check_qeth "$id" && (( count=count+1 ))
	done
	echo "qeth_count_available: $count"
}

function get_all() {
	local do_list=$1 sysfs base count=0

	for sysfs in $QETH/* ; do
		base=${sysfs##*/}

		# Note: [.] needed due to inconsistent behavior of older Bash
		if [[ $base =~ [.] ]] ; then
			(( count=count+1 ))
			[[ $do_list == 1 ]] && echo "qeth $base:"
		fi
	done
	[[ $do_list == 0 ]] && echo "qeth_count_total: $count"
}

if [ -n "$DATAFILE" ] ; then
	# Get state for resources specified in datafile
	get_state <"$DATAFILE"
	get_all 0
else
	# Get list of all available resources
	get_all 1
fi

exit 0
