#!/bin/bash
set -euo pipefail

APP_ROOT="/home/ark/R36SHack"
ENV_ROOT="/home/ark/miniconda3/envs/r36s-dlna-browser"
LOG_FILE="/home/ark/MatHacks/r36s-dlna-browser.log"

cd "$APP_ROOT"

export HOME="/home/ark"
export PYTHONPATH="$APP_ROOT/src"
export LD_LIBRARY_PATH="$ENV_ROOT/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"

# Use system gstreamer1.0-libav (apt) to avoid conda-forge aarch64 ABI mismatches.
# libgomp must be preloaded to avoid "cannot allocate memory in static TLS block".
export GST_PLUGIN_PATH="/usr/lib/aarch64-linux-gnu/gstreamer-1.0"
export LD_PRELOAD="/usr/lib/aarch64-linux-gnu/libgomp.so.1"

# Enable Rockchip MPP hardware video decode (mppvideodec).
# NV12 frames are uploaded directly via SDL_UpdateNVTexture — no software
# colourspace conversion.  Requires librockchip_mpp.so + libgstrockchipmpp.so
# installed by deploy/arkos/setup_hw_decode.sh.
export R36S_HW_DECODE="1"

if [ -f "/storage/.config/SDL-GameControllerDB/gamecontrollerdb.txt" ]; then
  export SDL_GAMECONTROLLERCONFIG_FILE="/storage/.config/SDL-GameControllerDB/gamecontrollerdb.txt"
elif [ -f "/opt/inttools/gamecontrollerdb.txt" ]; then
  export SDL_GAMECONTROLLERCONFIG_FILE="/opt/inttools/gamecontrollerdb.txt"
fi

exec "$ENV_ROOT/bin/python" -m r36s_dlna_browser >>"$LOG_FILE" 2>&1
