#!/bin/sh
set -eu
RAKAZO_HOME="${HOME:-/home/rakazo}"
# start.sh exports the session bus for the whole desktop; the supervisor may
# launch this script with a minimal environment, so recover the bus address.
if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ] && [ -r /tmp/rakazo/dbus-session ]; then
  . /tmp/rakazo/dbus-session
fi
# Page-browser tools and desktop launchers share the assigned display profile.
DISPLAY_NUM="${DISPLAY:-:1}"
DISPLAY_NUM="${DISPLAY_NUM#:}"
DISPLAY_NUM="${DISPLAY_NUM%%.*}"
case "$DISPLAY_NUM" in
  ''|*[!0-9]*) DISPLAY_NUM=1 ;;
esac
# POSIX shell arithmetic treats a leading zero as octal.
while [ "${DISPLAY_NUM#0}" != "$DISPLAY_NUM" ]; do DISPLAY_NUM="${DISPLAY_NUM#0}"; done
DISPLAY_NUM="${DISPLAY_NUM:-0}"
DEBUG_PORT=$((9221 + DISPLAY_NUM))
if [ -n "${RAKAZO_BROWSER_PROFILE:-}" ]; then
  PROFILE="$RAKAZO_BROWSER_PROFILE"
elif [ -s "/tmp/rakazo/browser-profile-$DISPLAY_NUM" ]; then
  PROFILE="$(cat "/tmp/rakazo/browser-profile-$DISPLAY_NUM")"
else
  case "$DISPLAY_NUM" in
    1) PROFILE="$RAKAZO_HOME/.browser-profiles/chromium" ;;
    *) PROFILE="$RAKAZO_HOME/.browser-profiles/chromium-screen-$DISPLAY_NUM" ;;
  esac
fi
mkdir -p "$PROFILE"
# Ubuntu's chromium is a confined snap that cannot use these flags, so a
# snap is only the last resort. Google Chrome's .deb lives in /opt/google/chrome.
is_snap_browser() {
  case "$1" in /snap/*) return 0 ;; esac
  case "$(readlink -f "$1" 2>/dev/null || true)" in /snap/*|*/bin/snap) return 0 ;; esac
  # Ubuntu's /usr/bin/chromium-browser is a small script that runs the snap.
  [ "$(head -c 2 "$1" 2>/dev/null)" = "#!" ] && grep -qs '/snap/' "$1"
}
BIN=""
SNAP_BIN=""
for candidate in chromium chromium-browser google-chrome google-chrome-stable /opt/google/chrome/chrome brave-browser /opt/brave.com/brave/brave; do
  found="$(command -v "$candidate" || true)"
  [ -n "$found" ] && [ -x "$found" ] || continue
  if is_snap_browser "$found"; then
    [ -n "$SNAP_BIN" ] || SNAP_BIN="$found"
    continue
  fi
  BIN="$found"
  break
done
BIN="${BIN:-$SNAP_BIN}"
if [ -z "$BIN" ]; then
  echo "no browser found: install chromium, google-chrome or brave-browser" >&2
  exit 1
fi
USER_DATA_DIR_SET=0
ACTUAL_PROFILE="$PROFILE"
PREV_ARG_WAS_USER_DATA_DIR=0
for arg in "$@"; do
  if [ "$PREV_ARG_WAS_USER_DATA_DIR" -eq 1 ]; then
    ACTUAL_PROFILE="$arg"
    PREV_ARG_WAS_USER_DATA_DIR=0
  fi
  case "$arg" in
    --user-data-dir=*) ACTUAL_PROFILE="${arg#*=}"; USER_DATA_DIR_SET=1 ;;
    --user-data-dir) PREV_ARG_WAS_USER_DATA_DIR=1; USER_DATA_DIR_SET=1 ;;
  esac
done

clear_crash_state() {
  f="$1"
  [ -f "$f" ] || return 0
  sed -E \
    's/"exit_type"[[:space:]]*:[[:space:]]*"Crashed"/"exit_type":"Normal"/g; s/"exited_cleanly"[[:space:]]*:[[:space:]]*false/"exited_cleanly":true/g' \
    "$f" > "${f}.tmp" && mv "${f}.tmp" "$f"
}

# Match one argument in NUL-separated argv or in Chromium's space-joined title.
# The whole flag is the search string, so spaces and " --" inside a profile path stay intact.
cmdline_text() {
  tr '\0' '\n' <"/proc/$1/cmdline" 2>/dev/null || true
}
has_arg() {
  text=$(cmdline_text "$1")
  if printf '%s\n' "$text" | grep -Fx -- "$2" >/dev/null; then return 0; fi
  if printf ' %s ' "$text" | grep -F -- " $2 " >/dev/null; then return 0; fi
  return 1
}
has_prefix() {
  text=$(cmdline_text "$1")
  if [ $# -ge 3 ]; then
    case "$text" in
      *"$3"*) text="${text%%"$3"*}${text#*"$3"}" ;;
    esac
  fi
  if printf '%s\n' "$text" | grep -e "^$2" >/dev/null; then return 0; fi
  if printf ' %s ' "$text" | grep -F -- " $2" >/dev/null; then return 0; fi
  return 1
}

# A stale SingletonLock is not a live browser. Leaving exit_type=Crashed makes Chrome
# drop session cookies (account sign-in) on the next start while persistent cookies remain.
# kill -0 is not enough: the PID may have been reused by an unrelated process.
profile_lock_pid() {
  profile="$1"
  lock=$(readlink "$profile/SingletonLock" 2>/dev/null || true)
  pid=${lock##*-}
  case "$pid" in
    ''|*[!0-9]*) return 1 ;;
  esac
  printf '%s\n' "$pid"
}

# This script is a shell whose argv names rakazo-browser, including a relative
# path such as ./rakazo-browser. A browser binary is not that script. A flag
# assignment (--user-data-dir=.../rakazo-browser) is not the script path either.
is_wrapper_pid() {
  pid=$1
  exe=$(readlink "/proc/$pid/exe" 2>/dev/null || true)
  case "${exe##*/}" in
    chromium|chromium-browser|chrome|google-chrome|google-chrome-stable|brave|brave-browser) return 1 ;;
  esac
  cmdline_text "$pid" | grep -qE '^([^=]*/)?rakazo-browser$'
}

profile_lock_is_live() {
  profile="$1"
  pid=$(profile_lock_pid "$profile") || return 1
  kill -0 "$pid" 2>/dev/null || return 1
  [ -r "/proc/$pid/cmdline" ] || return 0
  is_wrapper_pid "$pid" && return 1
  has_arg "$pid" "--user-data-dir=$profile" || return 1
  if has_prefix "$pid" "--type=" "--user-data-dir=$profile"; then
    return 1
  fi
  return 0
}

# The lock often points at a wrapper, a renderer, or a reused PID while the
# debugger-owning browser is still running. Rewriting that profile or starting
# another Chromium drops the live session.
profile_browser_pid() {
  profile="$1"
  [ -d /proc ] || return 1
  # One pass selects cmdline files that contain the flag. Exact checks run only
  # on those candidates. The scan is capped so it cannot consume the spawn poll
  # that also has to cover the 1.6s live-tab forward.
  scan_status=0
  scan=$(timeout 0.4 sh -c 'grep -lsaF -- "$1" /proc/[0-9]*/cmdline 2>/dev/null' sh "--user-data-dir=$profile" 2>/dev/null) || scan_status=$?
  if [ "$scan_status" -eq 124 ]; then
    return 124
  fi
  [ -n "$scan" ] || return 0
  printf '%s\n' "$scan" |
    while IFS= read -r cmdline_file; do
      pid="${cmdline_file#/proc/}"
      pid="${pid%/cmdline}"
      case "$pid" in
        ''|*[!0-9]*) continue ;;
      esac
      kill -0 "$pid" 2>/dev/null || continue
      is_wrapper_pid "$pid" && continue
      has_arg "$pid" "--user-data-dir=$profile" || continue
      has_prefix "$pid" "--remote-debugging-port=" "--user-data-dir=$profile" || continue
      if has_prefix "$pid" "--type=" "--user-data-dir=$profile"; then
        continue
      fi
      printf '%s\n' "$pid"
      exit 0
    done
}

# Computer control treats a launcher still running after its spawn poll as success.
# 1.6s fits a cold python start and urllib import, then /json/new while the debugger
# comes up. A dropped response is reconciled with /json/list before another
# /json/new, so one open cannot leave a second tab. A slow listing does not skip
# that open. A socket that accepts and never answers fails on the 0.5s request cap.
# The profile scan above is capped at 0.4s. The spawn poll is those two bounds plus
# a little shell, so a forward that fails after the scan is still reported.
open_live_browser_url() {
  timeout 1.6 /usr/bin/python3 -I - "$@" <<'PY'
import json
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

pid, profile, url = sys.argv[1:]
# /json/new does not apply omnibox fixup. A scheme-less host opens about:blank,
# and host:port is parsed as an unknown scheme. Absolute paths are files.
lowered = url.lower()
if "://" not in url and not lowered.startswith(
    ("about:", "chrome:", "data:", "file:", "javascript:", "view-source:")
):
    url = "file://" + url if url.startswith("/") else "http://" + url
data = open("/proc/" + pid + "/cmdline", "rb").read().replace(b"\0", b" ")
if profile:
    data = data.replace(b"--user-data-dir=" + profile.encode(), b" ", 1)
key = b"--remote-debugging-port="
start = len(data)
port = None
while True:
    start = data.rfind(key, 0, start)
    if start < 0:
        break
    if start == 0 or data[start - 1:start] == b" ":
        digits = bytearray()
        index = start + len(key)
        while index < len(data) and 48 <= data[index] <= 57:
            digits.append(data[index])
            index += 1
        if digits:
            port = int(digits)
            break
if port is None:
    raise SystemExit(1)

deadline = time.monotonic() + 1.0
seen = set()
# /json/new may have created a tab even though the response was lost.
create_uncertain = False
confirm_misses = 0


def remaining():
    return deadline - time.monotonic()


def failure_reason(error):
    if isinstance(error, urllib.error.HTTPError):
        return error
    if isinstance(error, urllib.error.URLError):
        return error.reason
    return error


def read_http(path, method):
    if remaining() < 0.05:
        raise SystemExit(1)
    req = urllib.request.Request("http://127.0.0.1:" + str(port) + path, method=method)
    try:
        with urllib.request.urlopen(req, timeout=min(0.5, remaining())) as resp:
            return resp.status, resp.read(1024 * 1024 + 1)
    except urllib.error.HTTPError as error:
        return error.code, b""
    except Exception as error:
        reason = failure_reason(error)
        if isinstance(reason, TimeoutError) or isinstance(error, TimeoutError):
            raise SystemExit(1)
        raise


def list_pages():
    if remaining() < 0.05:
        raise SystemExit(1)
    try:
        status, body = read_http("/json/list", "GET")
    except SystemExit:
        # A timed-out snapshot must not skip /json/new while time remains.
        if remaining() < 0.05:
            raise
        return None
    except Exception:
        return None
    if status != 200 or len(body) > 1024 * 1024:
        return None
    try:
        parsed = json.loads(body.decode("utf-8"))
    except (UnicodeError, json.JSONDecodeError):
        return None
    if not isinstance(parsed, list):
        return None
    return parsed


def url_matches(current):
    if not isinstance(current, str) or current == "":
        return False
    if current == url:
        return True
    return "://" in url and current.rstrip("/") == url.rstrip("/")


def navigation_pending(current):
    if current in (None, "", "about:blank"):
        return True
    return isinstance(current, str) and current.startswith("chrome://newtab")


def fresh_pages(pages):
    found = []
    for page in pages:
        if not isinstance(page, dict) or page.get("type") not in (None, "page"):
            continue
        ident = page.get("id")
        if not isinstance(ident, str) or ident in seen:
            continue
        found.append(page)
    return found


def remember(pages):
    global seen
    seen = set()
    for page in pages:
        if isinstance(page, dict) and isinstance(page.get("id"), str):
            seen.add(page["id"])


def open_new():
    path = "/json/new?" + urllib.parse.quote(url, safe="")
    refused = False
    rejected = False
    for method in ("PUT", "GET"):
        try:
            status, _body = read_http(path, method)
        except SystemExit:
            raise
        except Exception as error:
            reason = failure_reason(error)
            if isinstance(reason, ConnectionRefusedError):
                refused = True
                continue
            # The request may have been applied. Do not try the other verb.
            return "uncertain"
        if status == 200:
            return "ok"
        # 400/404/405 reject the verb or the endpoint and do not create a tab.
        if status in (400, 404, 405):
            rejected = True
            continue
        return "uncertain"
    if rejected and not refused:
        return "fail"
    return "retry"


while True:
    if remaining() < 0.05:
        raise SystemExit(1)
    pages = list_pages()
    if pages is not None:
        fresh = fresh_pages(pages)
        if create_uncertain and any(
            url_matches(page.get("url"))
            or (len(fresh) == 1 and navigation_pending(page.get("url")))
            for page in fresh
        ):
            raise SystemExit(0)
        if create_uncertain:
            if fresh:
                time.sleep(0.05)
                continue
            confirm_misses += 1
            if confirm_misses < 2:
                time.sleep(0.05)
                continue
            create_uncertain = False
        remember(pages)
    elif create_uncertain:
        time.sleep(0.05)
        continue
    result = open_new()
    if result == "ok":
        raise SystemExit(0)
    if result == "fail":
        raise SystemExit(1)
    if result == "uncertain":
        create_uncertain = True
        confirm_misses = 0
    time.sleep(0.05)
PY
}

live_pid=""
lock_pid=""
if [ -d "$ACTUAL_PROFILE" ]; then
  scan_status=0
  live_pid=$(profile_browser_pid "$ACTUAL_PROFILE") || scan_status=$?
  if [ "$scan_status" -eq 124 ]; then
    echo "browser profile scan timed out" >&2
    exit 1
  fi
  lock_pid=$(profile_lock_pid "$ACTUAL_PROFILE" || true)
  if ! profile_lock_is_live "$ACTUAL_PROFILE" && [ -z "$live_pid" ]; then
    rm -f "$ACTUAL_PROFILE/SingletonLock" "$ACTUAL_PROFILE/SingletonCookie" "$ACTUAL_PROFILE/SingletonSocket" 2>/dev/null || true
    find "$ACTUAL_PROFILE" \( -name Preferences -o -name 'Local State' \) -type f 2>/dev/null |
      while IFS= read -r f; do
        clear_crash_state "$f" 2>/dev/null || rm -f "${f}.tmp"
      done || true
  fi
  # Reuse the debugger browser unless the lock names that same process.
  # A live wrapper, renderer, or reused PID must not start another Chromium.
  if [ -n "$live_pid" ] && [ "$lock_pid" != "$live_pid" ]; then
    target_url=""
    skip_value=0
    for arg in "$@"; do
      if [ "$skip_value" -eq 1 ]; then
        skip_value=0
        continue
      fi
      case "$arg" in
        --user-data-dir) skip_value=1 ;;
        --*) ;;
        *) target_url=$arg ;;
      esac
    done
    if [ -n "$target_url" ]; then
      open_live_browser_url "$live_pid" "$ACTUAL_PROFILE" "$target_url" || exit 1
    fi
    exit 0
  fi
fi

# Chromium's singleton hand-off hangs with the image's NSS wrapper loaded.
# Match the per-screen launcher: preserve other space- or colon-separated preload entries.
if [ -n "${LD_PRELOAD:-}" ]; then
  _kept=""
  _rest="$LD_PRELOAD"
  while [ -n "$_rest" ]; do
    case "$_rest" in
      *[:\ ]*) _entry="${_rest%%[: ]*}"; _rest="${_rest#*[: ]}" ;;
      *) _entry="$_rest"; _rest="" ;;
    esac
    case "$_entry" in
      *libnss_wrapper.so|"") ;;
      *) _kept="${_kept:+$_kept:}$_entry" ;;
    esac
  done
  if [ -n "$_kept" ]; then export LD_PRELOAD="$_kept"; else unset LD_PRELOAD; fi
  unset _kept _rest _entry
fi

# This container has no GPU. --disable-gpu keeps Chromium from probing one.
# WebGL still needs SwiftShader: --disable-software-rasterizer blocks it, and
# current Chromium allows that fallback only with --enable-unsafe-swiftshader.
# The account's language arrives as LANGUAGE, which Chrome on Linux reads for its
# own language (it ignores --lang). For the languages pages see, it reads LANGUAGE
# only when it creates a profile and keeps that profile's list afterwards, so a
# saved profile gets the account's language through --accept-lang on each start.
LANGUAGE_FLAGS=""
language="${LANGUAGE:-}"
language="$(printf '%s' "${language%%:*}" | tr _ -)"
case "$language" in
  ''|-*|*[!A-Za-z0-9-]*) ;;
  *)
    base="${language%%-*}"
    languages="$language"
    [ "$base" = "$language" ] || languages="$languages,$base"
    [ "$base" = en ] || languages="$languages,en-US,en"
    LANGUAGE_FLAGS="--accept-lang=$languages"
    ;;
esac
FLAGS="--test-type --no-sandbox --disable-dev-shm-usage --disable-gpu --enable-unsafe-swiftshader $LANGUAGE_FLAGS --no-first-run --no-default-browser-check --disable-session-crashed-bubble --hide-crash-restore-bubble --password-store=basic --restore-last-session --start-maximized --remote-debugging-address=127.0.0.1 --remote-debugging-port=$DEBUG_PORT"
if [ "$USER_DATA_DIR_SET" -eq 0 ]; then
  exec "$BIN" $FLAGS --user-data-dir="$PROFILE" "$@"
fi
exec "$BIN" $FLAGS "$@"
