#!/bin/bash

# omarchy:summary=Let Chromium decode video on the video chip of Snapdragon laptops

set -euo pipefail

# The Snapdragon video chip is a V4L2 decoder. Omarchy's aarch64 Chromium
# compiles both VA-API and V4L2 (defaulting to VA-API) and needs ANGLE on GLES,
# AcceleratedVideoDecoder, and PreferV4L2VideoAcceleration to use V4L2. Arch
# Linux ARM's V4L2-only build ignores the extra feature flag. Other machines
# keep Chromium's defaults.

# Chromium's launcher splits each line into arguments, so a switch can share a
# line with others or end in a comment. Look for switches with comments removed.
chromium_args() {
  sed -E 's/(^|[[:space:]])#.*$//' "$1"
}

# Add a line, starting a new one first if the file doesn't end in a newline.
append_line() {
  if [[ -n $(tail -c1 "$1") ]]; then
    echo >>"$1" || return
  fi
  printf '%s\n' "$2" >>"$1"
}

# A --use-angle the user set stays as it is. Chrome and Chromium each read
# their own flags file, and one that can't be written doesn't hold back the other.
setup_chromium() {
  local conf status=0

  for conf in ~/.config/chromium-flags.conf ~/.config/chrome-flags.conf; do
    [[ -f $conf ]] || continue
    if ! chromium_args "$conf" | grep -E -- '(^|[[:space:]])--use-angle=' >/dev/null; then
      append_line "$conf" '--use-angle=gles-egl' || status=$?
    fi
  done

  omarchy-chromium-add-feature AcceleratedVideoDecoder || status=$?
  omarchy-chromium-add-feature PreferV4L2VideoAcceleration || status=$?
  return "$status"
}

if omarchy-hw-aarch64-qualcomm; then
  setup_chromium
fi
