#!/bin/bash
#
# Run a test with the WebRTC Chromium build.
# Should work on any machine with a camera.
#
# Pass the argument --xvfb-and-screenshots to run in a xvfb environment and
# capture screenshots from inside the virtual environment. If you don't what
# that is, never mind and run this script without arguments.
#
# Pass the argument --chrome-binary <binary> to provide a custom chrome binary.
#
# Method:
# - Start peerconnection_server.
# - Start serving webrtc_test.html off a local web server.
# - Start 2 browser tabs.
# - Tab 1 connects to the server.
# - Tab 2 connects to the server and calls tab 1.
# - Both tabs will capture the webcam you have on the system and start
#   sending to each other.
#

set -e

if [ ! -x run_sanity_check ]; then
  echo "Error: This script must run from its own directory"
  exit 1
fi

# Tweakable parameters:
URLBASE=localhost:3000
CALLEE="$URLBASE/webrtc_test.html?name=test1&autoconnect=yes"
CALLER="$URLBASE/webrtc_test.html?name=test2&autocall=test1"
FLAGS="--enable-media-stream"
CHROME_BINARY=google-chrome

# Parse parameters:
while (( "$#" )); do
  if [ "$1" == "--xvfb-and-screenshots" ]; then
    RUN_WITH_XVFB_AND_SCREENSHOTS=1
  fi
  if [ "$1" == "--chrome-binary" ]; then
    shift
    CHROME_BINARY=$1
  fi
  shift
done

run_chrome_for_user() {
  # Run the binary straight up and proceed with cleanup when the user closes
  # the browser.
  ${CHROME_BINARY} $CALLEE $CALLER $FLAGS --user-data-dir=temp/user1
}

run_chrome_in_xvfb_with_screenshots() {
  # Run chrome in a virtual window environment and capture screenshots.
  # It will run for 30 seconds and then exit.
  Xvfb :17 -screen 0 1024x768x24 &
  XVFB=$!
  DISPLAY=:17 ${CHROME_BINARY} $CALLEE $CALLER $FLAGS --user-data-dir=temp/user1 &
  CHROME=$!

  sleep 2

  for (( i = 0; i < 6; i++ )) do
    FILENAME="IMAGE${i}.png"
    DISPLAY=:17 import -window root $FILENAME
    sleep 5
  done
  kill $CHROME || echo "No Chrome process."
  kill $XVFB || echo "No XVFB process."
}

PROJECT_ROOT=../..

if which lighttpd; then
  LOCAL_WEB_SERVER_BINARY=$(which lighttpd)
else
  echo "Error: You must install lighttpd first (sudo apt-get install lighttpd)"
  exit 1
fi

SERVER_BINARY=${PROJECT_ROOT}/../../peerconnection/trunk/out/Debug/peerconnection_server
if [ ! -e "$SERVER_BINARY" ]; then
  echo "Error: You must build peerconnection_server first."
  echo "I expected to find a binary at $SERVER_BINARY but found none."
  exit 1
fi

# Launch the web server and make it serve the local www/html directory
${LOCAL_WEB_SERVER_BINARY} -D -f lighttpd.conf &
LOCAL_WEB_SERVER=$!

${SERVER_BINARY} &
SERVER=$!
echo "Started server as $SERVER"

# Launch a browser with two tabs:
if [ -z "$RUN_WITH_XVFB_AND_SCREENSHOTS" ]; then
  run_chrome_for_user
else
  run_chrome_in_xvfb_with_screenshots
fi

echo "Test finished, cleaning up"

kill $SERVER || echo "No peerconnection_server"
kill $LOCAL_WEB_SERVER || echo "No local web server"
