#!/bin/sh

set -e

TWEEPER="/usr/share/php/tweeper/tweeper"
#TWEEPER="./tweeper"

check_result() {
  URL="$1"
  FILE="$2"
  RESULT="$3"

  echo "URL $URL"
  if [ "$RESULT" ];
  then
    echo "--> $FILE"
    echo "    exists"
  else
    echo "... $FILE"
    echo "    does not exist"
  fi
  echo
}

file_exists() {
  FILE="$1"
  URL="file://twitter.com/$FILE"
  OUTPUT=$($TWEEPER $URL)
  check_result "$URL" "$FILE" "$OUTPUT"
}

file_exists_on_server() {
  SERVER="$1"
  FILE="$2"
  URL="file://twitter.com/$FILE"
  OUTPUT=$(curl $SERVER/tweeper.php?src_url=$URL 2> /dev/null)
  check_result "$URL" "$FILE on $SERVER" "$OUTPUT"
}

file_exists /etc/passwd || true
file_exists /etc/file_with_an_unlikely_name || true

echo "Staring a test server"
echo

php -S localhost:8000 -t $(dirname $TWEEPER) > /dev/null 2>&1 &
SERVER_PID=$!
sleep 1

file_exists_on_server http://localhost:8000 /etc/passwd || true
file_exists_on_server http://localhost:8000 /etc/file_with_an_unlikely_name || true

echo "Shutting down the test server"
kill $SERVER_PID
