#!/bin/bash

# Copyright (c) 2021-2023 Red Hat.
#
# This is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published
# by the Free Software Foundation; either version 3, or (at your
# option) any later version.
#
# It is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# Mimics the glibc stat.c test run by rpminspect

TEST_NAME=stat
. $srcdir/common.sh

# Use the same command line options that normal spec file will use,
# *except* that we disable the use of the annobin plugin, since this
# will pick up the one in the system directory, not the one just built

OPTS="$(rpm --eval '%undefine _annotated_build %build_cflags %build_ldflags')"

# The rpm macros may not be available, so if necessary use our own.

if ! [[ $OPTS == *"redhat-hardened-cc1"* ]];
then
    echo " $TEST_NAME: using built-in option selection instead"
    OPTS="-O2 -fexceptions -g -grecord-gcc-switches -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fPIE -fstack-protector-strong -fasynchronous-unwind-tables -fstack-clash-protection -Wl,-z,relro -Wl,--as-needed  -Wl,-z,now -pie"
fi

# Now add in our newly built plugin.
OPTS="$OPTS -fplugin=$PLUGIN"

start_test

COMMAND="$GCC $OPTS -o stat.exe $srcdir/stat.c"
$COMMAND
if [ $? != 0 ];
then
	echo " $TEST_NAME: FAIL: Could not compile source file"
	echo " $TEST_NAME: command: $COMMAND"
	end_test
	exit 1
fi

# Run annocheck

SKIPS="--skip-cf-protection --skip-property-note --skip-stack-realign --skip-entry --skip-dynamic-tags --skip-lto --skip-fortify --skip-warnings --skip-dynamic-tags --skip-not-dynamic-tags --skip-branch-protection --skip-not-branch-protection"
COMMAND2="$ANNOCHECK stat.exe $SKIPS --ignore-gaps"
$COMMAND2 > stat.out
grep -e "PASS" stat.out
if [ $? != 0 ];
then
    echo " $TEST_NAME: FAIL: annocheck did not PASS the test executable"
    echo " $TEST_NAME: gcc command: $COMMAND"
    echo " $TEST_NAME: annocheck command: $COMMAND2"
    echo " $TEST_NAME: annocheck output:"
    cat stat.out
    end_test
    exit 1
fi

end_test
