#!/bin/bash

# Allow the user to override command-line flags, bug #357629.
# This is based on Debian's chromium-browser package, and is intended
# to be consistent with Debian.
for f in /etc/chromium/*; do
	# Skip backup files and hidden files #546394
	case "${f}" in
		*~|*.bak|*.old|*.swp|*.tmp|*/.*) continue ;;
	esac
	[[ -f "${f}" ]] && source "${f}"
done

# Prefer user defined CHROMIUM_USER_FLAGS (from env) over system
# default CHROMIUM_FLAGS (from /etc/chromium/default).
CHROMIUM_FLAGS=${CHROMIUM_USER_FLAGS:-"$CHROMIUM_FLAGS"}

# We rely on the slotted stub to provide CHROME_WRAPPER.
if [[ -z "${CHROME_WRAPPER}" ]]; then
	echo "ERROR: CHROME_WRAPPER is not set. The Chromium launcher stub is misconfigured." >&2
	exit 1
fi

PROGDIR=${CHROME_WRAPPER%/*}

case ":$PATH:" in
	*:$PROGDIR:*)
	# $PATH already contains $PROGDIR
	;;
	*)
	# Append $PROGDIR to $PATH
	export PATH="$PATH:$PROGDIR"
	;;
esac

if [[ ${EUID} == 0 && -O ${XDG_CONFIG_HOME:-${HOME}} ]]; then
	# Running as root with HOME owned by root.
	# Pass --user-data-dir to work around upstream failsafe.
	echo "Refusing to run as root is a safety feature. Running as root disables the sandbox." >&2
	CHROMIUM_FLAGS="--user-data-dir=${XDG_CONFIG_HOME:-${HOME}/.config}/chromium
		${CHROMIUM_FLAGS}"
fi

# Select session type and platform; var comes from the stub launcher.sh generated by the ebuild
if [[ ${OZONE_AUTO_SESSION} == true ]]; then
	platform=
	if [[ ${XDG_SESSION_TYPE} == x11 ]]; then
		platform=x11
	elif [[ ${XDG_SESSION_TYPE} == wayland ]]; then
		platform=wayland
	else
		if [[ -n ${WAYLAND_DISPLAY} ]]; then
			platform=wayland
		else
			platform=x11
		fi
	fi
	if ${DISABLE_OZONE_PLATFORM:-false}; then
		platform=x11
	fi
	CHROMIUM_FLAGS="--ozone-platform=${platform} ${CHROMIUM_FLAGS}"
fi

# Sanitise std{in,out,err} because they'll be shared with untrusted child
# processes (http://crbug.com/376567).
exec < /dev/null
exec > >(exec cat)
exec 2> >(exec cat >&2)

exec -a "/usr/bin/${CHROME_EXEC_NAME:-chromium-browser}" "$PROGDIR/chrome" --extra-plugin-dir=/usr/lib/nsbrowser/plugins ${CHROMIUM_FLAGS} "$@"
