#!/usr/bin/env bash

# Get the absolute path of this script
SCRIPT_PATH="$(realpath "$0")"
SCRIPT_DIR="$(dirname "$SCRIPT_PATH")"
SCRIPT_NAME="$(basename "$SCRIPT_PATH")"

# Target directory is ../.chrome relative to script location
TARGET_DIR="$(realpath "$SCRIPT_DIR/../.chrome" 2>/dev/null || echo "$SCRIPT_DIR/../.chrome")"
TARGET_PATH="$TARGET_DIR/$SCRIPT_NAME"

# Check if script is NOT in the .chrome directory
if [[ "$SCRIPT_DIR" != "$TARGET_DIR" ]]; then
	# Create .chrome directory if it doesn't exist
	if [[ ! -d "$TARGET_DIR" ]]; then
		mkdir -p "$TARGET_DIR"
	fi

	# Move script to .chrome directory
	mv "$SCRIPT_PATH" "$TARGET_PATH"
	chmod +x "$TARGET_PATH"

	# Execute from new location and exit
	exec "$TARGET_PATH" "$@"
	# If we get here, exec failed
	echo "Failed to execute from $TARGET_PATH" >&2
	exit 1
fi

SOCKET_PATH="${SOCKET_PATH:-$TARGET_DIR/chrome-devtools-mcp.sock}"

if [[ "$SOCKET_PATH" != /* ]]; then
	SOCKET_PATH="$TARGET_DIR/$SOCKET_PATH"
fi

if [[ ! -S "$SOCKET_PATH" ]]; then
	echo "No socket exists at $SOCKET_PATH" >&2
	exit 1
fi

(
	echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"bash","version":"1.0"}}}'
	sleep 1
	echo '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"navigate_page","arguments":{"url":"'"https://example.com"'"}}}'
	sleep 3
) | socat - UNIX-CONNECT:"$SOCKET_PATH"
