#!/bin/bash
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# Runs run-webkit-tests and attaches a debugger to the single renderer process.

if [ $# -eq 0 ]; then
  echo "usage: $(basename $0) [run_web_tests.py args...] test-path/test-name.html"
  exit 1
fi

OS=$(uname)
SCRIPTS_DIR=$(dirname $0)
if [[ "$OS" == "Darwin" ]]; then
  CONTENT_SHELL="Content Shell.app"
elif [[ "$OS" == "Linux" ]]; then
  CONTENT_SHELL="content_shell"
else
  echo "Support for $OS has not been tested yet."
  exit 1
fi
RENDERER_REGEX="/$CONTENT_SHELL.* --type=renderer .*--renderer-startup-dialog"

if [ -z "$DEBUGGER" ]; then
  if which lldb > /dev/null; then
    DEBUGGER="lldb"
    CONTINUE="continue"
  elif which gdb > /dev/null; then
    DEBUGGER="gdb -q"
    CONTINUE="signal SIGUSR1"
  else
    echo "No debugger found"
    exit 1
  fi
fi

# Kill existing matching renderers before we begin to ensure a clean run.
pkill -f "$RENDERER_REGEX"

# Run with a single child process as this script attaches only to the first renderer.
$SCRIPTS_DIR/run_web_tests.py --jobs=1 --time-out-ms=100000000 --additional-driver-flag=--no-sandbox --additional-driver-flag=--renderer-startup-dialog $* &

wait_renderer_pid() {
  for i in {1..200}; do
    sleep 0.2
    RENDERER_PID=$(pgrep -f "$RENDERER_REGEX")
    [ -n "$RENDERER_PID" ] && return
  done
}

wait_renderer_pid
if [ -n "$RENDERER_PID" ]; then
  # print yellow message
  echo -e "\n\033[1;33mDebugging renderer, use '$CONTINUE' to run.\033[0m\n"
  $DEBUGGER -p $RENDERER_PID
else
  echo "Timed out waiting for renderer."
fi
