#!/bin/sh
# use interactive shell environment for machine specific env vars
. /etc/profile

if [ -e /dev/input/res-touchscreen ] && [ -e /dev/input/touchscreen0 ]; then
    if [ ! -e /etc/pointercal ]; then
        #res. touchscreen is not calibrate. We should do this first
        /usr/bin/ts_calibrate
    fi
    #forbid libinput when using resistive touchscreens
    export QT_QPA_EGLFS_NO_LIBINPUT=1
    export QT_QPA_FB_NO_LIBINPUT=1
    #enable tslib
    export QT_QPA_EGLFS_TSLIB=1
    export QT_QPA_FB_TSLIB=1
    export TSLIB_TSDEVICE="/dev/input/touchscreen0"
fi

# Disable Qt audio, when there is no audio device present.
# Two conditions must be met for successful audio, otherwise use
# fakesink:
# 1. at least one audio pcm device should be registered,
# 2. one of these audio devices should be available:
#    2.1 HDMI display is connected (audio over HDMI) or
#    2.2 external audio codec is present (assume alsa-utils are
#    installed in that case).

# check if any pcm device is available
ls -1 /dev/snd/pcm* > /dev/null 2>&1
pcm_status=$?
# check if HDMI display is connected
hdmi_status=`cat /sys/class/drm/*HDMI*/status | grep '^connected'`
# check if alsa-utils are installed
which aplay > /dev/null 2>&1
alsa_status=$?

if [ $pcm_status -ne 0 ] || ([ -z "$hdmi_status" ] && [ $alsa_status -ne 0 ]); then
    export QT_GSTREAMER_PLAYBIN_AUDIOSINK=fakesink
fi

export DISPLAY=:0.0
export QT_QPA_PLATFORM=eglfs
export QT_QPA_EGLFS_ALWAYS_SET_MODE="1"
export QT_QPA_EGLFS_KMS_CONFIG=/etc/eglfs_kms.config
export QT_WAYLAND_SHELL_INTEGRATION=xdg-shell

# Common Debug Settings
#export QT_DEBUG_PLUGINS=1
#export QT_LOGGING_RULES=qt.qpa.*=true

# For Wayland/Xwayland weston user
if [ `id -u weston 2>/dev/null` ]; then
    export WAYLAND_DISPLAY=/run/wayland-0
fi

if [ $# -eq 0 ]; then
    echo 'usage: qtLauncher <your_qt_application>'
else
    $@ #run the application
fi
