#!/bin/bash
# Start headless Chromium with auth from copied Chrome profile
# Run after logging into sites in headed Chrome

PROFILE_SRC="/tmp/chrome-clean"
PROFILE_DST="/tmp/chrome-headless"
PORT=9223

# Check if source profile exists
if [ ! -d "$PROFILE_SRC" ]; then
    echo "Error: Source profile $PROFILE_SRC doesn't exist"
    echo "Start headed Chrome first and log into your sites:"
    echo "  google-chrome --no-sandbox --remote-debugging-port=9222 --user-data-dir=$PROFILE_SRC"
    exit 1
fi

# Kill existing headless if running
pkill -f "remote-debugging-port=$PORT" 2>/dev/null

# Copy/refresh profile
rm -rf "$PROFILE_DST"
cp -r "$PROFILE_SRC" "$PROFILE_DST"
rm -f "$PROFILE_DST"/Singleton*

# Start headless
/home/johan/.cache/ms-playwright/chromium-1208/chrome-linux64/chrome \
    --headless=new \
    --no-sandbox \
    --disable-gpu \
    --remote-debugging-port=$PORT \
    --user-data-dir="$PROFILE_DST" &

sleep 2

# Verify
if curl -s "http://localhost:$PORT/json/version" | grep -q Browser; then
    echo "✓ Headless Chrome running on port $PORT"
else
    echo "✗ Failed to start headless Chrome"
    exit 1
fi
