#!/bin/bash
# Basic regression tests for httpdito.
set -e

portnum=8086
get() {
    (echo "GET $1 HTTP/1.0"$'\r'; echo $'\r') | nc localhost "$portnum"
}

at() {
    tested_url=$1
    diff -u <(get "$1" | cat -vte) <(cat -vte)
}

expect_err404() {
    cat <<EOF
HTTP/1.0 404 Not found$cr
Content-type: text/html; charset=utf-8$cr
$cr
<title>404 not found</title>
<p>Actually, there was just some arbitrary error.  Maybe
your request was bad.
EOF
}

cd "$(dirname "$0")"

./server &
server_pid="$!"

sleep .01                       # we need GNU sleep or better here

if ! kill -0 "$server_pid"; then
    wait
    echo "server startup failed" >&2
    exit 1
fi

trap 'kill $server_pid; echo "testing failed at $tested_url"' 0

cr=$'\r'

at / < <(expect_err404)

at /server.s <<EOF
HTTP/1.0 200 OK$cr
Content-Type: text/plain; charset=utf-8$cr
$cr
$(cat server.s)
EOF

at /xhtml <<EOF
HTTP/1.0 200 OK$cr
Content-Type: text/plain; charset=utf-8$cr
$cr
$(cat xhtml)
EOF

at /test.html <<EOF
HTTP/1.0 200 OK$cr
Content-Type: text/html; charset=utf-8$cr
$cr
$(cat test.html)
EOF

# % handling

at /test%2ehtml <<EOF
HTTP/1.0 200 OK$cr
Content-Type: text/html; charset=utf-8$cr
$cr
$(cat test.html)
EOF

at /test%2Ehtml <<EOF
HTTP/1.0 200 OK$cr
Content-Type: text/html; charset=utf-8$cr
$cr
$(cat test.html)
EOF

at /.test < <(expect_err404)
at /check/../../../../../../../../etc/passwd < <(expect_err404)
at //etc/passwd < <(expect_err404)

# All tests succeeded; remove failure explanation
kill $server_pid
trap '' 0
