#!/bin/bash
set -o pipefail
AppName="${BASH_SOURCE[0]##*/}"
AppDir="/usr/lib64/${AppName}"
FlagsFile="${XDG_CONFIG_HOME:-$HOME/.config}/${AppName}-flags.conf"

export PATH="${AppDir}:${PATH}"
export LD_LIBRARY_PATH="${AppDir}/swiftshader:${AppDir}/lib:${LD_LIBRARY_PATH}"
export ELECTRON_IS_DEV=0
export ELECTRON_FORCE_IS_PACKAGED=true
export ELECTRON_DISABLE_SECURITY_WARNINGS=true
export NODE_ENV=production

declare -a UserFlags WaylandFlags FlagsA FlagsB
WaylandFlags=(
    '--enable-features=UseOzonePlatform,WaylandWindowDecorations,VaapiVideoDecodeLinuxGL' # VaapiVideoDecodeLinuxGL??
    '--ozone-platform=wayland'
)

if [ -f "${FlagsFile}" ]; then
    mapfile -t UserFlags < <(sed -r "/^( *#|$)/d;s% %\n%g" "$FlagsFile")
fi

if [ "${XDG_SESSION_TYPE}" = "wayland" ]; then
    unset DISPLAY
    FlagsA+=('--enable-features=UseOzonePlatform' '--ozone-platform=wayland')
    FlagsB+=("${WaylandFlags[@]}")
else
    export ELECTRON_RUN_AS_NODE=1
fi

exec electron "${AppDir}/out/cli.js" "${FlagsA[@]}" "${AppDir}/${AppName}.js" "${UserFlags[@]}" "${FlagsB[@]}" "$@"
