#!/bin/bash
#
# agent-chrome: a signed-in Chrome for agents to drive.
#
# Runs real Google Chrome on its own profile folder, which is kept between
# runs. You sign in there once per site with `agent-chrome login`. Agents then
# attach with `agent-browser --cdp <port>`.
#
# Chrome is started here, not by agent-browser, so that it uses the real cookie
# key from the system keychain and can read the saved sign-ins.
#
#   agent-chrome start            start headless Chrome if needed; print the port
#   agent-chrome status           say whether it is running, and how
#   agent-chrome stop             stop it
#   agent-chrome login [url...]   stop it, then open a visible window to sign in
#
# AGENT_CHROME_DIR and AGENT_CHROME_PORT override the folder and the port.

set -u

DIR="${AGENT_CHROME_DIR:-$HOME/.agent-browser/agent-chrome}"
PORT="${AGENT_CHROME_PORT:-9333}"
APP="Google Chrome"
BIN="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"

# The main Chrome process running on this folder, if any.
chrome_pid() {
    ps -axo pid=,command= | grep -F -- "--user-data-dir=$DIR" | grep -F "$BIN" | grep -v -F "Helper" | awk 'NR==1 {print $1}'
}

chrome_mode() {
    ps -o command= -p "$1" 2>/dev/null | grep -q -- "--remote-debugging-port=$PORT" && echo "headless" || echo "visible"
}

port_answers() {
    curl -s -o /dev/null --max-time 2 "http://127.0.0.1:$PORT/json/version"
}

stop_chrome() {
    local pid
    pid="$(chrome_pid)"
    [ -z "$pid" ] && return 0
    kill "$pid" 2>/dev/null
    for _ in $(seq 1 20); do
        [ -z "$(chrome_pid)" ] && return 0
        sleep 0.5
    done
    echo "agent-chrome: Chrome (pid $pid) did not stop" >&2
    return 1
}

case "${1:-}" in
    start)
        pid="$(chrome_pid)"
        if [ -n "$pid" ] && [ "$(chrome_mode "$pid")" = "visible" ]; then
            echo "agent-chrome: the sign-in window is still open. Quit it, then run start again." >&2
            exit 1
        fi
        if [ -z "$pid" ]; then
            if [ ! -d "$DIR" ]; then
                echo "agent-chrome: no profile yet. Run: agent-chrome login" >&2
                exit 1
            fi
            if port_answers; then
                echo "agent-chrome: port $PORT is in use by something else. Set AGENT_CHROME_PORT." >&2
                exit 1
            fi
            # `open -n` hands Chrome to the system, so it outlives this shell.
            open -na "$APP" --args --user-data-dir="$DIR" --remote-debugging-port="$PORT" --headless=new \
                --no-first-run --no-default-browser-check --window-size=1440,1600 about:blank
        fi
        for _ in $(seq 1 30); do
            if port_answers; then
                echo "$PORT"
                exit 0
            fi
            sleep 0.5
        done
        echo "agent-chrome: Chrome did not open port $PORT" >&2
        exit 1
        ;;
    status)
        pid="$(chrome_pid)"
        if [ -z "$pid" ]; then
            echo "stopped"
        else
            echo "running ($(chrome_mode "$pid")), pid $pid, port $PORT"
        fi
        ;;
    stop)
        stop_chrome
        ;;
    login)
        shift
        stop_chrome || exit 1
        mkdir -p "$DIR" && chmod 700 "$DIR"
        # A plain window with no debugging port, so sign-in pages see an ordinary browser.
        open -na "$APP" --args --user-data-dir="$DIR" --no-first-run --no-default-browser-check "$@"
        echo "A Chrome window is open. Sign in, choose \"Use Chrome Without an Account\" if Chrome asks, then quit that window."
        ;;
    *)
        echo "usage: agent-chrome start|status|stop|login [url...]" >&2
        exit 2
        ;;
esac
