#!/bin/sh -efu
#
# Copyright (c) 2020-2023 The strace developers.
# All rights reserved.
#
# SPDX-License-Identifier: GPL-2.0-or-later

usage()
{
	cat >&2 <<EOF
Usage: $0 [<input>]

Generate secontext files from <input> list.
EOF
	exit 1
}

if [ $# -eq 0 ]; then
	input="${0%/*}/gen_tests.in"
else
	input="$1"
	shift
fi
dir="$(dirname "$input")"
[ $# -eq 0 ] || usage

{
	cat <<EOF
# Generated by $0 from $input; do not edit.

secontext_EXECUTABLES = \\
EOF
	sed -E -n 's/^([^#[:space:]]+--secontext(_full)?(_mismatch)?)[[:space:]].*/  \1 \\/p' < "$input"
	cat <<EOF
  #

EOF
	sed -E -n 's/-/_/g; s/^([^#[:space:]]+__secontext(_full)?(_mismatch)?)[[:space:]].*/\1_LDADD = \$(LDADD) \$(libselinux_LDADD)/p' < "$input"
} > "$dir/secontext.am"

sed -E -n 's/^([^#[:space:]]+--secontext)[[:space:]].*/\1/p' < "$input" |
while read -r name; do {
	cat <<-EOF > "$dir/$name.c"
		/*
		 * Copyright (c) 2021 The strace developers.
		 * All rights reserved.
		 *
		 * SPDX-License-Identifier: GPL-2.0-or-later
		 */

		#include "tests.h"

		#ifdef HAVE_SELINUX_RUNTIME

		# define TEST_SECONTEXT
		# include "${name%--secontext}.c"

		#else

		SKIP_MAIN_UNDEFINED("HAVE_SELINUX_RUNTIME")

		#endif
	EOF
} < /dev/null; done

sed -E -n 's/^([^#[:space:]]+--secontext_full)[[:space:]].*/\1/p' < "$input" |
while read -r name; do {
	cat <<-EOF > "$dir/$name.c"
		#define PRINT_SECONTEXT_FULL
		#include "${name%_full}.c"
	EOF
} < /dev/null; done

sed -E -n 's/^([^#[:space:]]+--secontext(_full)?_mismatch)[[:space:]].*/\1/p' < "$input" |
while read -r name; do {
	cat <<-EOF > "$dir/$name.c"
		#define PRINT_SECONTEXT_MISMATCH
		#include "${name%_mismatch}.c"
	EOF
} < /dev/null; done
