#!/usr/bin/env bash
# Linux: Chrome with remote debugging so the Hub can run "Save session from Chrome (CDP)".
# Headless VPS: install Google Chrome + Xvfb — this script uses xvfb-run when DISPLAY is unset.
#
#   sudo apt update && sudo apt install -y xvfb wget
#   wget ... google-chrome-stable_current_amd64.deb && sudo apt install -y ./google-chrome-stable_*.deb
#   chmod +x start_chrome_cdp.sh && ./start_chrome_cdp.sh
#
# Verify port: curl -s http://127.0.0.1:9222/json/version | head -c 200
#
set -euo pipefail
ROOT="$(cd "$(dirname "$0")" && pwd)"
PROFILE="${ROOT}/.chrome_cdp_profile"
CHROME="${CHROME:-}"
for c in /usr/bin/google-chrome-stable /usr/bin/google-chrome /usr/bin/chromium-browser /usr/bin/chromium; do
  if [[ -x "$c" ]]; then CHROME="$c"; break; fi
done
if [[ -z "$CHROME" || ! -x "$CHROME" ]]; then
  echo "ERROR: Chrome/Chromium not found. Install e.g.:"
  echo "  sudo apt install -y chromium-browser"
  echo "Or set CHROME=/path/to/google-chrome"
  exit 1
fi

mkdir -p "$PROFILE"

CHROME_ARGS=(
  --remote-debugging-port=9222
  --user-data-dir="$PROFILE"
  --no-first-run
  --disable-gpu
  --no-sandbox
  "$@"
)

echo "Using: $CHROME"
echo "Profile: $PROFILE"
echo "Remote debugging: http://127.0.0.1:9222"
echo ""

# Headless Linux: no DISPLAY → Chrome exits immediately unless we use a virtual framebuffer.
if [[ "$(uname -s)" == Linux ]] && [[ -z "${DISPLAY:-}" ]]; then
  if command -v xvfb-run >/dev/null 2>&1; then
    echo "No DISPLAY — using xvfb-run (virtual screen). Chrome stays up; port 9222 should listen."
    echo "NOTE: You still cannot click Google in a invisible browser. For login on VPS use RDP/VNC,"
    echo "      or create smile_auth.json on your PC and upload it here."
    echo ""
    exec xvfb-run -a -s "-screen 0 1280x720x24" "$CHROME" "${CHROME_ARGS[@]}"
  fi
  echo "ERROR: No DISPLAY and xvfb-run is not installed."
  echo "  sudo apt install -y xvfb"
  echo "Then run this script again."
  exit 1
fi

echo "Then sign in at smile.one in this Chrome; in Hub Admin click Save session from Chrome (CDP)."
exec "$CHROME" "${CHROME_ARGS[@]}"
