#!/bin/bash
# SPDX-License-Identifier: MIT
#
# tape - collect state for tape resources.
#
# Copyright IBM Corp. 2025
#
# Usage: tape [<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

CCWDRV="/sys/bus/ccw/drivers"

shopt -s nullglob

function get_tape_dir() {
	local _var="$1" _id="$2" _dir

	for _dir in $CCWDRV/tape_*/$_id; do
		eval "$_var=$_dir"
		break
	done
}

function check_char_dev() {
	local dir="$1" indent="$2" type="$3" cdev

	[[ -e "$dir" ]] || return

	dir="$(readlink -f "$dir")"

	cdev=${dir##*/}

	echo "${indent}${type}_char_dev:"
	echo "${indent}  cdev: $cdev"
}

function check_tape() {
	local id="$1" busid sysfs online state medium_state cutype devtype

	canonical_ccwdev_id busid $id || return 1
	get_tape_dir sysfs $busid

	# No output if tape doesn't exist
	[[ -e "$sysfs" ]] || return 1

	# Get additional data
	read online <$sysfs/online
	read state <$sysfs/state
	read medium_state <$sysfs/medium_state
	read cutype <$sysfs/cutype
	read devtype <$sysfs/devtype

	# Create output
	echo "tape $busid:"
	echo "  busid: $busid"
	echo "  type: ccw"
	echo "  sysfs: $sysfs"
	echo "  state: $state"
	echo "  medium_state: $medium_state"
	# Create CCW-specific output
	echo "  ccw:"
	echo "    online: $online"
	echo "    cutype: $cutype"
	echo "    devtype: $devtype"

	check_ccwdev_chpids "$busid" "    " "_tela_copy ../../../chpid " 1 ""

	# Character device information
	check_char_dev $sysfs/rewinding "  " "r"
	check_char_dev $sysfs/non-rewinding "  " "n"

	# Default values for meta-attributes
	echo "  allow_write: 0"

	return 0
}

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

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

		check_tape "$id" && ((count = count + 1))
	done
	echo "tape_count_available: $count"
}

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

	for sysfs in $CCWDRV/tape_*/[0-9a-f]*.*.*; do
		id=${sysfs##*/}
		((count = count + 1))
		[[ $do_list == 1 ]] && echo "tape $id:"
	done

	[[ $do_list == 0 ]] && echo "tape_count_total: $count"
}

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

exit 0
