
# Copyright 2015-2023 Rivoreo

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
# IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE


# Test code, unused by other parts

ioctl() {
	local length=4 arg_length=4 arg_type
	OPTIND=0
	while getopts rl:a:s c
	do case $c in
		r)
			;;
		l)
			length="$OPTARG"
			;;
		a)
			arg_length="$OPTARG"
			#arg_type="C$((OPTARG))"
			;;
		s)
			arg_type=a
			;;
		\?)
			return 255
			;;
	esac done
	if [ $# -le $OPTIND ]; then
		echo "Usage: ioctl [<options>] <file> <request> [<arg> ...]" 1>&2
		return 255
	fi
	shift $((OPTIND-1))
	local f="$1" req="$2"
	shift 2
	local total_arg_len=$((arg_length*$#))
	[ $((length)) -lt $total_arg_len ] && length=$total_arg_len
	[ "$arg_type" != a ] && arg_type="C$((length))"
	perl -e 'my $buffer; $buffer = pack(@ARGV[2], splice(@ARGV, 3)) if $#ARGV > 2; my $res; open(HANDLE, "<@ARGV[0]") && ($res = ioctl(HANDLE, @ARGV[1], $buffer)) || die "@ARGV[0]: $!\n"; close(HANDLE); $res =~ s/ .+//; print STDOUT "$res\n"; my @r_buffer = unpack(@ARGV[2], $buffer); exit unless @r_buffer; print STDOUT "return:"; foreach $a (@r_buffer) { print STDOUT sprintf(" 0x%02x", $a); } print "\n";' -- "$f" $((req)) $arg_type "$@"
}
