#!/bin/sh

export TEST_SHELL=sh
# Enable unit tests - don't skip them
# export SKIP_UNIT=1

# Required for test environment permissions
export TEST_SSH_UNSAFE_PERMISSIONS=1

# Enable FIPS mode for tests (used by openssh-FIPS-wolfprov.patch)
export FIPS_MODE=1

cd regress

# copied from openssh-portable/.github/run_test.sh
output_failed_logs() {
    for i in failed*.log; do
        if [ -f "$i" ]; then
            echo -------------------------------------------------------------------------
            echo LOGFILE $i
            cat $i
            echo -------------------------------------------------------------------------
        fi
    done
}
trap output_failed_logs 0

sed -i "/\t\tagent-ptrace /d" Makefile

# wolfProvider CI style: run file-tests, interop-tests, extra-tests, and unit
# Skip t-exec as it takes too long
make -k BUILDDIR=`pwd`/.. .OBJDIR=`pwd` .CURDIR=`pwd` SUDO="" FIPS_MODE=1 \
        file-tests interop-tests extra-tests unit \
        | sed -u -e 's/^skipped/SKIP: /g' -e 's/^ok /PASS: /g' -e 's/^failed/FAIL: /g'

SSHAGENT=`which ssh-agent`
GDB=`which gdb`

if [ -z "${SSHAGENT}" -o -z "${GDB}" ]; then
       echo "SKIP: agent-ptrace"
       exit
fi

useradd openssh-test

eval `su -c "${SSHAGENT} -s" openssh-test` > /dev/null
r=$?
if [ $r -ne 0 ]; then
    echo "FAIL: could not start ssh-agent: exit code $r"
else
    su -c "gdb -p ${SSH_AGENT_PID}" openssh-test > /tmp/gdb.out 2>&1 << EOF
        quit
EOF
    r=$?
    if [ $r -ne 0 ]; then
        echo "gdb failed: exit code $r"
    fi
    egrep 'ptrace: Operation not permitted.|procfs:.*Permission denied.|ttrace.*Permission denied.|procfs:.*: Invalid argument.|Unable to access task ' >/dev/null /tmp/gdb.out
    r=$?
    rm -f /tmp/gdb.out
    if [ $r -ne 0 ]; then
        echo "FAIL: ptrace agent"
    else
        echo "PASS: ptrace agent"
    fi

    ${SSHAGENT} -k > /dev/null
fi
userdel openssh-test

