#!/bin/sh

# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2009-2014 Stephan Raue (stephan@openelec.tv)
# Copyright (C) 2016-present Team LibreELEC (https://libreelec.tv)
. /etc/profile
oe_setup_addon browser.chrome

# check if chrome is already successful installed
if [ ! -f "$ADDON_DIR/extract.ok" ]; then
  cd $ADDON_DIR
  chrome-downloader
fi

if [ -e $ADDON_HOME/env ]; then
  . $ADDON_HOME/env
fi

# fix file permissions (zip packaging)
chmod +x $ADDON_DIR/chrome-bin/chrome
chmod 4755 $ADDON_DIR/chrome-bin/chrome-sandbox

# make sure we use "own" gtk/pango/nss/etc
export LD_LIBRARY_PATH=$ADDON_DIR/lib.private

# configure pango/pixbuf
export PANGO_RC_FILE=$ADDON_DIR/config/pangorc
export GDK_PIXBUF_MODULE_FILE=$ADDON_DIR/config/pixbuf.loaders.cache

# font rendering in gtk widgets is broken with nvidia blob. use our Xdefaults
export XENVIRONMENT=$ADDON_DIR/config/Xdefaults

# start unclutter
if [ "$HIDE_CURSOR" == "true" ]; then
  unclutter &
  UNCLUTTER_PID=$!
fi

# vaapi
LIBVA_DRIVERS_PATH="/usr/lib/dri:$ADDON_DIR/lib.private"
LIBVA_DRIVER_NAME=''
case $VAAPI_MODE in
  'intel')
    LIBVA_DRIVER_NAME='i965'
    chrome_OPTS="$chrome_OPTS --use-gl=desktop --enable-features=VaapiVideoDecoder"
    ;;
  'amd')
    LIBVA_DRIVER_NAME='vdpau'
    chrome_OPTS="$chrome_OPTS --use-gl=desktop --enable-features=VaapiVideoDecoder"
    ;;
  'nvidia')
    LIBVA_DRIVER_NAME='vdpau'
    chrome_OPTS="$chrome_OPTS --use-gl=desktop --enable-features=VaapiVideoDecoder --allow-no-sandbox-job --disable-gpu-sandbox"
    ;;
  *)
    LIBGL_ALWAYS_SOFTWARE='1'
    export LIBGL_ALWAYS_SOFTWARE
    ;;
esac
export LIBVA_DRIVER_NAME LIBVA_DRIVERS_PATH

# windowed
case $WINDOW_MODE in
  'maximized')
    chrome_OPTS="$chrome_OPTS --start-maximized"
    ;;
  'kiosk')
    chrome_OPTS="$chrome_OPTS --kiosk"
    ;;
esac

# rasterization
case $RASTER_MODE in
  'off')
    chrome_OPTS="$chrome_OPTS --disable-accelerated-2d-canvas --disable-gpu-compositing"
    ;;
  'force')
    chrome_OPTS="$chrome_OPTS --enable-gpu-rasterization --enable-accelerated-2d-canvas --ignore-gpu-blacklist"
    ;;
esac

# alsa
if [ "$AUDIO_DEVICE_TYPE" == "ALSA" ]; then
  # stop pulseaudio when using an Alsa device
  systemctl stop pulseaudio
  if [ ! -z $ALSA_DEVICE ]; then
    chrome_OPTS="$chrome_OPTS --alsa-output-device=$ALSA_DEVICE"
  fi
fi

# dark mode
if [ "$DARK_MODE" == "true" ]; then
  chrome_OPTS="$chrome_OPTS --force-dark-mode"
fi

# User-Agent
if [ ! -z "$USER_AGENT" ]; then
  USER_AGENT="--user-agent=$USER_AGENT"
fi

# start chrome
LD_PRELOAD=/usr/lib/libGL.so $ADDON_DIR/chrome-bin/chrome \
  $chrome_OPTS \
  "$USER_AGENT" \
  --no-sandbox \
  --user-data-dir=$ADDON_HOME/profile \
  --test-type $@ \
  2>&1 | tee $ADDON_LOG_FILE

# kill unclutter
if [ "$HIDE_CURSOR" == "true" ]; then
  kill $UNCLUTTER_PID
fi

sleep 5
if [ "$AUDIO_DEVICE_TYPE" == "ALSA" ]; then
  # restart pulseaudio when using an Alsa device
  systemctl start pulseaudio
fi
