#!/usr/bin/env bash
set -euo pipefail

if command -v sudo >/dev/null 2>&1 && sudo -n true 2>/dev/null; then
  echo "Installing Playwright system dependencies with apt (sudo)..."
  npx playwright install-deps chromium
  exit 0
fi

DEPS_DIR="${PLAYWRIGHT_DEPS_DIR:-$HOME/.local/playwright-deps}"
ROOT="$DEPS_DIR/root"
MARKER="$DEPS_DIR/.installed"

if [[ -f "$MARKER" && -f "$ROOT/usr/lib/x86_64-linux-gnu/libatk-1.0.so.0" ]]; then
  echo "Playwright local dependencies already installed at $ROOT"
  exit 0
fi

echo "No passwordless sudo — installing Playwright libs locally to $DEPS_DIR"

TMP_LIST="$(mktemp)"
npx playwright install-deps chromium --dry-run 2>&1 | sed -n '/^  /s/^  //p' > "$TMP_LIST"

mkdir -p "$DEPS_DIR/debs"
cd "$DEPS_DIR/debs"
ALL_PKGS="$(apt-cache depends --recurse --no-recommends --no-suggests --no-conflicts --no-breaks --no-replaces --no-enhances $(cat "$TMP_LIST") 2>/dev/null | grep -E '^[[:alnum:]]' | grep -v '^<' | sort -u)"
apt-get download $ALL_PKGS

rm -rf "$ROOT"
mkdir -p "$ROOT"
for deb in *.deb; do
  dpkg-deb -x "$deb" "$ROOT"
done

date -Iseconds > "$MARKER"
rm -f "$TMP_LIST"
echo "Done. Libraries installed to $ROOT"