#!/bin/bash
. testsuite/functions.sh

PORT=12343
run_weborf -b site1 -p $PORT --yesexec --cgi .py,/usr/bin/python3 -m

# 404 error works
curl --head http://127.0.0.1:$PORT/file_inventato | head -1 | grep 404

# 1 response per request
responses=$(printf "HEAD /sub1/ HTTP/1.1\r\nConnection: close\r\n\r\n" | nc localhost $PORT | grep ^HTTP/ | wc -l)
if [[ $responses -ne 1 ]]; then
    exit 1
fi

# normal files
curl --head http://127.0.0.1:$PORT/sub1/index.txt | grep "Content-Length: 11"
if curl --head http://127.0.0.1:$PORT/sub1/index.txt | grep "lollellero"; then
    exit 1
fi
curl --head http://127.0.0.1:$PORT/sub1/index.txt | grep "text/plain"

# directories work
curl --head http://127.0.0.1:$PORT/sub1 | head -1 | grep 301
curl --head http://127.0.0.1:$PORT/sub1/ | grep "Content-Length: "
curl --head http://127.0.0.1:$PORT/sub1/ | grep "ETag: "
curl --head http://127.0.0.1:$PORT/sub1/ | grep "Content-Type: text/html"
if curl --head http://127.0.0.1:$PORT/sub1/ | grep "body"; then
    exit 1
fi

# Check head of a cgi script, should not be allowed
curl --head -s http://127.0.0.1:$PORT/cgi.py | grep 405

# etag and range on files
etag=$(curl --head http://127.0.0.1:$PORT/sub1/index.txt | grep ETag | cut -d\   -f 2)
curl --head http://127.0.0.1:$PORT/sub1/index.txt -H "If-None-Match: ${etag}" | grep 304

curl --head -H "If-Range: ${etag}" --range 0-2 http://localhost:$PORT/sub1/index.txt | grep 206
curl --head -H "If-Range: ${etag}" --range 5000-900000 http://localhost:$PORT/sub1/index.txt | grep 416

# etag and range on directories
curl --head -H "If-Range: ${etag}" --range 0-2 http://localhost:$PORT/sub1/ | grep 200\ OK
curl --head -H "If-Range: ${etag}" --range 5000-900000 http://localhost:$PORT/sub1/ | grep 200\ OK
