#!/usr/bin/env bash

set -Eeou pipefail

# This script installs Chromium/Puppeteer browser dependencies on RPM-based systems
# (CentOS, RHEL, Fedora, Amazon Linux, etc.).
#
# It uses dnf/yum's ability to install by RPM capability (Provides:) rather than
# hardcoded package names. This makes it resilient to package renames across distro
# versions (similar to how apt-get satisfy works on Debian).
#
# Dependencies are read from the rpm.deps file (shared with the packaging build).
# Lines wrapped in parentheses with " or " separators are treated as alternative
# groups — each alternative is tried in order until one succeeds.
#
# See https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md#chrome-headless-doesnt-launch-on-unix

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DEPS_FILE="${SCRIPT_DIR}/rpm.deps"

if [ ! -f "$DEPS_FILE" ]; then
  echo "Error: Dependency file not found at '$DEPS_FILE'" >&2
  echo "The rpm.deps file should be installed alongside this script." >&2
  exit 1
fi

# Detect package manager
if command -v dnf &> /dev/null; then
  PKG_MANAGER="dnf"
elif command -v yum &> /dev/null; then
  PKG_MANAGER="yum"
else
  echo "Error: Neither dnf nor yum found on this system." >&2
  exit 1
fi

echo "Using package manager: $PKG_MANAGER"

# Parse rpm.deps into regular deps and alternative groups.
# Lines like "(libcurl.so()(64bit) or libgtk-3.so.0()(64bit))" are alternatives.
DEPS=()
ALTERNATIVES=()

while IFS= read -r line; do
  # Skip comments and empty lines
  [[ "$line" =~ ^[[:space:]]*# ]] && continue
  [[ "$line" =~ ^[[:space:]]*$ ]] && continue

  # Skip RPM-internal capabilities (not installable via dnf/yum)
  [[ "$line" =~ ^rpmlib\( ]] && continue
  [[ "$line" =~ ^rtld\( ]] && continue

  # For .so entries, skip versioned symbols (e.g. libc.so.6(GLIBC_2.17)(64bit))
  # since the base entry (e.g. libc.so.6()(64bit)) already pulls in the same package.
  # This avoids redundant "already installed" noise from dnf.
  if [[ "$line" =~ \.so[.0-9]*\([A-Z_] ]]; then
    continue
  fi

  if [[ "$line" =~ ^\( && "$line" =~ \)$ && "$line" == *" or "* ]]; then
    # Strip outer parens, convert " or " to "|"
    line="${line#\(}"
    line="${line%\)}"
    alt_group="${line// or /|}"
    ALTERNATIVES+=("$alt_group")
  else
    DEPS+=("$line")
  fi
done < "$DEPS_FILE"

echo "Installing browser dependencies..."

failures=0

# Install the main dependency list
if ! $PKG_MANAGER install -y "${DEPS[@]}"; then
  echo "ERROR: Failed to install main dependency list"
  failures=$((failures + 1))
fi

# Handle alternative groups
for alt_group in "${ALTERNATIVES[@]}"; do
  IFS='|' read -ra alts <<< "$alt_group"
  installed=false
  for alt in "${alts[@]}"; do
    if $PKG_MANAGER install -y "$alt" 2>/dev/null; then
      echo "Installed alternative: $alt"
      installed=true
      break
    fi
  done
  if [ "$installed" = false ]; then
    echo "WARN: Could not install any alternative from group: $alt_group"
    failures=$((failures + 1))
  fi
done

# Update nss to latest (matches original script behavior)
$PKG_MANAGER update -y nss || true

echo
if [ $failures -eq 0 ]; then
  echo "Successfully installed browser dependencies"
  exit 0
else
  echo "WARN: Unable to install all browser dependencies on this system ($failures failure(s))"
  exit 1
fi
