#!/bin/sh
# Check that evil-winrm builds and sends WinRM requests through the
# ruby-winrm stack, using a stub HTTP server on the loopback interface
# that rejects every request with 401. Nothing leaves localhost.
set -eu

testdir=$(dirname "$(readlink -f "$0")")
cd "${AUTOPKGTEST_TMP:-$(mktemp -d)}"
export HOME="$PWD"

fail() { echo "FAIL: $*" >&2; exit 1; }

# run <args...>: connection attempts must fail with exit code 1, cleanly
run() {
    rc=0
    timeout 120 evil-winrm -n "$@" </dev/null >out 2>&1 || rc=$?
    if [ "$rc" -ne 1 ]; then
        cat out
        fail "evil-winrm $* exited with $rc, expected 1"
    fi
    if grep -Eq '\.rb:[0-9]+:in ' out; then
        cat out
        fail "evil-winrm $* printed a Ruby backtrace"
    fi
    grep -qF "Cannot establish connection to remote endpoint" out \
        || { cat out; fail "missing connection error message"; }
}

echo "Test: connection refused"
# Port 1 (tcpmux) is privileged and not expected to be listening
run -i 127.0.0.1 -P 1 -u user -p pass
grep -qF "Connection refused" out || { cat out; fail "expected 'Connection refused'"; }

echo "Test: request sent to a stub WinRM endpoint"
rm -f port requests.log
python3 -I "$testdir/winrm-stub.py" port requests.log &
stub=$!
trap 'kill $stub 2>/dev/null || true' EXIT
i=0
while [ ! -s port ]; do
    i=$((i + 1))
    [ $i -le 50 ] || fail "stub server did not start"
    sleep 0.1
done

run -i 127.0.0.1 -P "$(cat port)" -u user -p pass -U /custom-wsman -a autopkgtest-agent
cat requests.log
grep -qx "POST /custom-wsman UA=autopkgtest-agent AUTH=Negotiate" requests.log \
    || fail "stub did not receive the expected NTLM negotiate request"

echo "All connection tests passed"
