#!/bin/sh
export WAYLAND_DISPLAY=weston-headless-0
#!/bin/sh

exec 2>&1

RTC_FLAG_FILE=/tmp/rtc_sync

retry_middleware_command()
{
    while [ "$(middleware-tool --"$1")" != "$1" ]; do
        sleep 2
    done
}

# clear out any libcef directory from previous installs - now lives in /usr/local/htc
if [ -d /usr/lib64/cef3 ]; then
    mount -o remount,rw /
    rm -rf /usr/lib64/cef3
    mount -o remount,ro /
fi

# exit if HTC.db not present or empty or manifest.txt isn't present
if [ ! -s /usr/local/htc/database/HTC.db -o ! -f /usr/local/htc/manifest.txt ]; then
    exit 1
fi

# if inhibit flag is present, exit
if [ -f /htc/inhibit ]; then
    exit 1
fi

# Ensure mdnsd is running, if present
if [ -f /etc/sv/mdnsd/run ]; then
    sv start mdnsd
fi

# Create the htcidentityd run directory if not present, since htc apps watch this dir
if [ -f /etc/sv/htcidentityd/run ]; then
    if [ ! -d /run/htcidentityd ]; then
        mkdir -p /run/htcidentityd
    fi
fi

# On EG4, we don't want to run htcidentityd if we are running the HTC apps
if [ $(hostname) == "hdl-eg4" ]; then
    sv stop htcidentityd
fi

# check psu-rtc-sync, if present - exit if not successful
if [ -f /etc/sv/psu-rtc-sync/run ]; then
    [[ -f $RTC_FLAG_FILE ]] || exit 1
fi

# if avahi is present, exit if it hasn't yet started
if [ -f /etc/init.d/avahi-daemon ]; then
    /etc/init.d/avahi-daemon status > /dev/null || exit 1
fi

# if mosquitto is present, exit if it hasn't yet started
if [ -f /etc/init.d/mosquitto ]; then
    /etc/init.d/mosquitto status > /dev/null || exit 1
fi

# Run the main HTC app

# Read the config
. /etc/htc/pathnames.sh

# Make the RO anbd RW database name up
HTCRODB=$CONFIG_PATH_DB_READONLY
HTCRWDB=$CONFIG_PATH_DB_READWRITE

# Check if the database exists; if so then check its integrity
if [ -f $HTCRWDB ]; then
    if sqlite3 $HTCRWDB 'pragma integrity_check'; then
        echo "$HTCRWDB: integrity test passed"
    else
        echo "$HTCRWDB: integrity test failed. Script will now delete and recreate."
        rm -f $HTCRWDB
    fi
fi

# Check if the read-write database exists; if not then create and initialise it.
if [ ! -f $HTCRWDB ]; then
    echo "$HTCRWDB: creating."
    mkdir -p $(dirname "$HTCRWDB")
    sqlite3 $HTCRWDB "CREATE TABLE Attributes (ID TEXT,SYMBOL TEXT,VALUE TEXT);"
fi

# Check if we need the run time AVL database
HTC_DATABASE_AVL=/tmp/AVL.db
AVL_DB_CHECK=/etc/htc/avl_db_check.sh
USE_DATABASE_AVL=$(sqlite3 $HTCRODB "select * from 'modules' where symbol='ERGBSC' or symbol='IO_ITXPT_TN';")
if [ -z "$USE_DATABASE_AVL" ] || [ ! -x "$AVL_DB_CHECK" ];
then
    echo "Not creating runtime AVL database."
else
    echo "creating runtime AVL database."
    $AVL_DB_CHECK $HTCRODB $HTC_DATABASE_AVL
    export HTC_DATABASE_AVL
fi

# Check if we need to restore the vehicle id file
VEHICLE_ID_FILE="$CONFIG_PATH_MEDIADIR/vehicle_id"
VEHICLE_ID_BACKUP="$VEHICLE_ID_FILE.bak"
if [ -s "$VEHICLE_ID_BACKUP" ] && [ ! -s "$VEHICLE_ID_FILE" ]; then
    echo "Restoring $VEHICLE_ID_FILE from $VEHICLE_ID_BACKUP"
    cp "$VEHICLE_ID_BACKUP" "$VEHICLE_ID_FILE"
fi

# Get Video Mode from database and apply
FBMODE=$(sqlite3 $HTCRODB "select value from 'parameters' where tag='videomode' and module_id = (select id  from modules where symbol = 'TFT_PRESENTATION_VGA' );")
if [ -z "$FBMODE" ];
then
    echo "Using default video mode"
else
    echo "Setting video mode:" $FBMODE
    fbset $FBMODE > /dev/null
fi

# If running on the STFT, enable the power and backlight, if weston is ready
if [ -x "$(command -v middleware-tool)" ]; then
    if [ ! -S /run/user/1000/wayland-1 ]; then
        echo "Weston socket not ready"
        exit 1
    fi
    retry_middleware_command "psu-b-enable-state=enabled"
    retry_middleware_command "backlight-status=on"
fi

# Set up required environment variables.
export PATH=$PATH:/usr/libexec/htc
export LUA_PATH="/usr/local/htc/scripts/?.lua;;"
export SDL_NOMOUSE=1
export XDG_RUNTIME_DIR=/run/user/0
export DISPLAY=:0

# changes needed for scarthgap
if [ -S /run/user/1000/wayland-1 ]; then
    export XDG_RUNTIME_DIR=/run/user/1000
    export WAYLAND_DISPLAY=wayland-1
    # allow CEF3 to render in xwayland from the root account
    su -c "xhost si:localuser:root" weston
fi

export MUSL_LOCPATH=/usr/share/i18n/locales/musl

export LIBVA_DRIVER_NAME=i965
export XDG_CACHE_HOME=/usr/local/htc/readwrite
export LD_LIBRARY_PATH=/usr/local/htc/cef3:$LD_LIBRARY_PATH
export PATH=/usr/local/htc/cef3:$PATH
# The following is needed because the CEF binaries are built with tcmalloc
export LD_PRELOAD=libcef.so
# Start the app
exec CController
