#!/bin/bash

DIR="$(dirname "$(readlink -f "$0")")"

cd "$DIR"

LIB_DIR="$DIR/lib"

arch="$(uname -m)"
if [[ $arch == aarch64 ]]; then
  suffix="arm64"
elif [[ $arch == arm* ]]; then
  suffix="armhf"
elif [[ $arch == x86_64 ]]; then
  suffix="64"
else
  suffix="32"
fi

exec="./rvgl.${suffix}"
lib="lib${suffix}"

libnames=(
  "libenet.so.7"
  "libopenal.so.1"
  "libunistring.so.2"
)

ldd_out="$(ldd $exec)"
for file in "${libnames[@]}"; do
  if [ ! "$(echo "$ldd_out" | grep "$file" | grep "not found")" ]; then
    [ -e "$LIB_DIR/$lib/$file" ] && [ ! -e "$LIB_DIR/$file" ] && ln -s "$LIB_DIR/$lib/$file" "$LIB_DIR"
  else
    [ -e "$LIB_DIR/$file" ] && rm "$LIB_DIR/$file"
  fi
done

export LD_LIBRARY_PATH=$LIB_DIR:$LD_LIBRARY_PATH

$exec "$@"
