#!/bin/bash

# Copyright (c) 2021 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.

# See BZ 2010675

TEST_NAME=gaps
. $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+=" -fplugin=$PLUGIN"

start_test

# Compile source code.

COMMAND="$GCC $OPTS $srcdir/main.c -o main.exe"
$COMMAND
if [ $? != 0 ];
then
    echo " $TEST_NAME: FAIL: unable to compile test 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"
$ANNOCHECK main.exe $SKIPS > main.out
grep -e "PASS" main.out
if [ $? != 0 ];
then
    echo " $TEST_NAME: FAIL: using rpm build macros did not produce an executable that passes annocheck"
    echo " $TEST_NAME: compile command: $GCC $OPTS $srcdir/main.c -o main.exe"
    echo " $TEST_NAME: annocheck command: $ANNOCHECK main.exe $SKIPS"
    echo " $TEST_NAME: annocheck output (with verbose and notes enabled):"
    $ANNOCHECK main.exe $SKIPS --verbose --enable-notes
    end_test
    exit 1
fi

end_test
