#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
USER_DATA_DIR="$PROJECT_DIR/.chrome"
DEBUG_PORT="${CHROME_DEBUG_PORT:-9222}"

if [ ! -d "$USER_DATA_DIR" ]; then
  echo "Error: $USER_DATA_DIR does not exist. Copy your profile there first." >&2
  exit 1
fi

if curl -sf "http://127.0.0.1:${DEBUG_PORT}/json/version" >/dev/null 2>&1; then
  echo "Chrome already listening on port ${DEBUG_PORT}." >&2
  exit 0
fi

exec google-chrome \
  --remote-debugging-port="$DEBUG_PORT" \
  --user-data-dir="$USER_DATA_DIR" \
  "$@"
