#!/bin/bash
# Copyright (c) 2000-2022 Synology Inc. All rights reserved.

source SynoBuildConf/_helpers

# prepare directory
install -dm755 $TmpInstDir/openssl-3-test

# copy necessary files for test
cp -a ./configdata.pm $TmpInstDir/openssl-3-test
cp -a ./Configure $TmpInstDir/openssl-3-test
cp -ar ./Configurations $TmpInstDir/openssl-3-test
cp -ar ./external $TmpInstDir/openssl-3-test
cp -ar ./util $TmpInstDir/openssl-3-test
find ./apps -type f -not -name '*.[acdo]' -exec cp -a --parents {} $TmpInstDir/openssl-3-test \;
find ./engines -type f -not -name '*.[acdo]' -exec cp -a --parents {} $TmpInstDir/openssl-3-test \;
find ./providers -type f -not -name '*.[acdo]' -exec cp -a --parents {} $TmpInstDir/openssl-3-test \;
find ./test -type f -not -name '*.[acdo]' -exec cp -a --parents {} $TmpInstDir/openssl-3-test \;

# make these files be templates for run.sh
mv $TmpInstDir/openssl-3-test/configdata.pm $TmpInstDir/openssl-3-test/configdata.pm.template
mv $TmpInstDir/openssl-3-test/util/wrap.pl $TmpInstDir/openssl-3-test/util/wrap.pl.template

# strip binary to reduce tarball size
find $TmpInstDir/openssl-3-test/test -type f -executable -name '*test' -exec $STRIP {} \;

# strip
if [ "x$NOSTRIP" != "xNOSTRIP" ]; then
	$STRIP $TmpInstDir/openssl-3-test/apps/openssl
	$STRIP $TmpInstDir/openssl-3-test/engines/*.so
	$STRIP $TmpInstDir/openssl-3-test/providers/*.so
fi

# write a runner script
cat <<-EOF > $TmpInstDir/openssl-3-test/run.sh
	#!/bin/bash

	SCRIPT="\$(realpath "\$0")"
	SCRIPT_DIR="\$(dirname "\${SCRIPT}")"

	cp -a "\${SCRIPT_DIR}/configdata.pm.template" "\${SCRIPT_DIR}/configdata.pm"
	cp -a "\${SCRIPT_DIR}/util/wrap.pl.template" "\${SCRIPT_DIR}/util/wrap.pl"

	sed -i "s%/source/openssl-3%\${SCRIPT_DIR}%g" "\${SCRIPT_DIR}/configdata.pm"
	sed -i "s%/source/openssl-3%\${SCRIPT_DIR}%g" "\${SCRIPT_DIR}/util/wrap.pl"

	env SRCTOP="\${SCRIPT_DIR}" BLDTOP="\${SCRIPT_DIR}" FIPSKEY=$(generate_fips_hmac_key) EXE_EXT= PERL=/bin/perl /bin/perl "\${SCRIPT_DIR}/test/run_tests.pl"
EOF
chmod a+x $TmpInstDir/openssl-3-test/run.sh
