#!/bin/sh
# Scan a local web server with feroxbuster and check what it reports.
# Prints a PASS/FAIL line for each check and a summary at the end.
set -u

cd "${AUTOPKGTEST_TMP:-$(mktemp -d)}" || exit 1
export HOME="$PWD" # ignore any ~/.config/feroxbuster/ferox-config.toml

passed=0
failed=0

check() {
    description=$1
    shift
    if "$@"; then
        echo "PASS: $description"
        passed=$((passed + 1))
    else
        echo "FAIL: $description"
        failed=$((failed + 1))
    fi
}

# Scan the test server, save the output in scan.txt and print it.
# python3 -m http.server only queues 5 pending connections, so use few
# threads: with the default 50, some requests get dropped and time out.
scan() {
    set -- --url "$URL" --threads 2 --silent "$@"
    echo
    echo "\$ feroxbuster $*"
    feroxbuster "$@" >scan.txt 2>&1
    sed '/^$/d; s/^/    /' scan.txt
}

found() { grep -qxF "$URL$1" scan.txt; }
not_found() { ! grep -qF "$URL$1" scan.txt; }

# Test web site
mkdir -p www/admin/backup
echo home >www/index.html
echo admin >www/admin/index.html
echo notes >www/notes.txt
printf '%s\n' admin backup notes doesnotexist >words.txt

# Serve it on a free port, taken from the server's startup message
python3 -u -m http.server --bind 127.0.0.1 --directory www 0 >server.log 2>&1 &
server=$!
trap 'kill $server 2>/dev/null' EXIT
for _ in $(seq 50); do
    port=$(sed -n 's/^Serving HTTP on .* port \([0-9]*\) .*/\1/p' server.log)
    [ -n "$port" ] && break
    sleep 0.1
done
if [ -z "$port" ]; then
    echo "ERROR: the web server did not start"
    cat server.log
    exit 1
fi
URL=http://127.0.0.1:$port

feroxbuster --version

scan --wordlist words.txt --extensions txt
check "finds directory /admin" found /admin
check "finds file /notes.txt (--extensions)" found /notes.txt
check "finds /admin/backup (recursion)" found /admin/backup
check "does not report /doesnotexist" not_found /doesnotexist

# No --wordlist: uses /usr/share/feroxbuster/raft-medium-directories.txt
scan --no-recursion
check "finds /admin with the default wordlist" found /admin

echo
echo "$passed passed, $failed failed"
[ "$failed" -eq 0 ]
