#!/bin/sh
# Copyright (C) 2016 O.S. Systems Software LTDA.
# Copyright (C) 2016 Freescale Semiconductor

export PATH="/sbin:/usr/sbin:/bin:/usr/bin"

usage() {
	cat <<EOF
	$0 [<weston options>]
EOF
}

## Module support
modules_dir=@DATADIR@/weston-start

# Add weston extra argument
add_weston_argument() {
	weston_args="$weston_args $1"
}

## Add module to --modules argument
add_weston_module() {
	if [[ "x${weston_modules}" == "x" ]]; then
		weston_modules="--modules "
	fi;
	weston_modules+="${1},"
}

if [ -n "$WAYLAND_DISPLAY" ]; then
	echo "ERROR: A Wayland compositor is already running, nested Weston instance is not supported yet."
	exit 1
fi

if [ -n "$WESTON_USER" ]; then
	if [ -z "$WESTON_GROUP" ]; then
		# no explicit WESTON_GROUP given, therefore use WESTON_USER
		export WESTON_GROUP="${WESTON_USER}"
	fi
fi

weston_args=$*

# Load and run modules
if [ -d "$modules_dir" ]; then
	for m in "$modules_dir"/*; do
		# Skip backup files
		if [ "`echo $m | sed -e 's/\~$//'`" != "$m" ]; then
			continue
		fi

		# process module
		. $m
		if [[ x"{$weston_modules}" != "x" ]]; then
			add_weston_argument "${weston_modules}"
		fi;
	done
fi

if test -z "$XDG_RUNTIME_DIR"; then
	export XDG_RUNTIME_DIR=/run/user/`id -u ${WESTON_USER}`
	if test -d "$XDG_RUNTIME_DIR"; then
	    # Check permissions on existing directory
	    if [ "$(stat -c %u-%a "$XDG_RUNTIME_DIR")" != "$(id -u ${WESTON_USER})-700" ]; then
			echo "ERROR: $XDG_RUNTIME_DIR has incorrect permissions"
			exit 1
		fi
	else
		mkdir --mode 0700 --parents $XDG_RUNTIME_DIR
		if [ -n "$WESTON_USER" ]
		then
			chown $WESTON_USER:$WESTON_GROUP $XDG_RUNTIME_DIR
		fi
	fi
fi

su -c "XDG_RUNTIME_DIR=$XDG_RUNTIME_DIR weston $weston_args --log=/tmp/weston.log" $WESTON_USER
