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

DATAFILE="$1"

function check_dcss() {
	local input="$1" id="$2" fid fn ft begin_page end_page type rest begin end size

	while IFS=' ' read -r fid fn ft begin_page end_page type rest ; do
		[[ "$ft" != "DCSSG" ]] && continue
		[[ "$fn" != "$id" ]] && continue

		printf -v begin "0x%x" $((0x$begin_page * 4096))
		printf -v end "0x%x" $((0x$end_page * 4096 + 4096))
		(( size = end - begin ))

		echo "dcss $fn:"
		echo "  name: $fn"
		echo "  begin: $begin"
		echo "  end: $end"
		echo "  size: $size"
		echo "  type: $type"
		break
	done <"$input"
}

function get_state() {
	local IFS=$'\n' total=0 count=0 tmpfile line id

	tmpfile=$(mktemp)
	if [[ -z "$tmpfile" ]] ; then
		echo "Could not create temporary file" >&2
		exit 1
	fi

	vmcp q nss map >"$tmpfile" 2>/dev/null

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

		(( total=total+1 ))
		check_dcss "$tmpfile" "$id" && (( count=count+1 ))
	done

	rm -f "$tmpfile"

	echo "dcss_count_available: $count"
	echo "dcss_count_total: $total"
}

function list_all() {
	local tmpfile fid fn ft rest

	tmpfile=$(mktemp)
	if [[ -z "$tmpfile" ]] ; then
		echo "Could not create temporary file" >&2
		exit 1
	fi

	vmcp q nss map >"$tmpfile" 2>/dev/null

	while read -r fid fn ft rest ; do
		[[ "$ft" != "DCSSG" ]] && continue

		echo "dcss $fn:"
	done <"$tmpfile"

	rm -f "$tmpfile"

	return 0
}

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

exit 0
