#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-2.0-or-later
# SPDX-FileCopyrightText: 2017-2021 Bartosz Golaszewski <bartekgola@gmail.com>

# Switch to v5.17.0 once released
MIN_KERNEL_VERSION="5.16.0"
BATS_SCRIPT="gpio-tools-test.bats"
SOURCE_DIR="$(dirname ${BASH_SOURCE[0]})"

die() {
	echo "$@" 1>&2
	exit 1
}

check_kernel() {
	local REQUIRED=$1
	local CURRENT=$(uname -r)

	SORTED=$(printf "$REQUIRED\n$CURRENT" | sort -V | head -n 1)

	if [ "$SORTED" != "$REQUIRED" ]
	then
		die "linux kernel version must be at least: v$REQUIRED - got: v$CURRENT"
	fi
}

check_prog() {
	local PROG=$1

	which "$PROG" > /dev/null
	if [ "$?" -ne "0" ]
	then
		die "$PROG not found - needed to run the tests"
	fi
}

# Check all required non-coreutils tools
check_prog bats
check_prog modprobe
check_prog timeout
check_prog egrep

# Check if we're running a kernel at the required version or later
check_kernel $MIN_KERNEL_VERSION

# The bats script must be in the same directory.
if [ ! -e "$SOURCE_DIR/$BATS_SCRIPT" ]
then
	die "testing script not found"
fi

BATS_PATH=$(which bats)

modprobe gpio-sim || die "unable to load the gpio-sim module"
mountpoint /sys/kernel/config/ > /dev/null 2> /dev/null || \
	die "configfs not mounted at /sys/kernel/config/"

exec $BATS_PATH -F tap $SOURCE_DIR/$BATS_SCRIPT ${1+"$@"}
