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

PORT=12352

# Test that it fails with a non existing cache directory
if "$BINNAME" -db site1 -p $PORT --cache "/tmp/fakecachedir" --index nonexisting; then
    exit 1
fi

SITE_DIR=$(mktemp -d)
CACHE_DIR=$(mktemp -d)
cp -r site1/* "$SITE_DIR"
"$BINNAME" -b "$SITE_DIR" -p $PORT --cache $CACHE_DIR --index nonexisting &
WEBORF_PID=$(jobs -p)

function cleanup () {
    kill -9 $WEBORF_PID
    ls "$CACHE_DIR"
    rm -rf "$CACHE_DIR"
    rm -rf "$SITE_DIR"
}
trap cleanup EXIT

curl -s http://localhost:$PORT/

[[ "$(ls $CACHE_DIR | wc -l)" = 1 ]]
curl -s http://localhost:$PORT/ | diff - $CACHE_DIR/*

sleep 1.1
touch "$SITE_DIR"/cachedir.test
sleep 1.1
ls $SITE_DIR
curl -s http://localhost:$PORT/
curl -s http://localhost:$PORT/ | grep cachedir.test

sleep 1.1
rm "$SITE_DIR"/cachedir.test
sleep 1.1
ls $SITE_DIR

if curl -s http://localhost:$PORT/ | grep cachedir.test; then
    exit 1
fi
[[ "$(ls $CACHE_DIR | wc -l)" = 3 ]]

curl --head http://localhost:$PORT/ | grep 200
