#!/bin/sh -e

# launch-script adapted from https://github.com/darealshinji/AppImageKit-checkrt
# loads included libstdc++ if needed, then returns to real working directory

cd "$(dirname "$0")/usr"

exec="$PWD/bin/vipster"

#determine architecture

if [ -n "$APPIMAGE" ] && [ "$(file -b "$APPIMAGE" | cut -d, -f2)" != " x86-64" ]; then
  libc6arch="libc6"
else
  libc6arch="libc6,x86-64"
fi

#find out if included libstdc++ is needed

if [ -e "./optional/libstdc++/libstdc++.so.6" ]; then
  lib="$(PATH="/sbin:$PATH" ldconfig -p | grep "libstdc++\.so\.6 ($libc6arch)" | awk 'NR==1{print $NF}')"
  sym_sys=$(tr '\0' '\n' < "$lib" | grep -e '^GLIBCXX_3\.4' | tail -n1)
  sym_app=$(tr '\0' '\n' < "./optional/libstdc++/libstdc++.so.6" | grep -e '^GLIBCXX_3\.4' | tail -n1)
  if [ "$(printf "${sym_sys}\n${sym_app}"| sort -V | tail -1)" != "$sym_sys" ]; then
    cxxpath="$PWD/optional/libstdc++:"
  fi
fi

if [ -n "$cxxpath" ] ; then
  if [ -e "./optional/exec.so" ]; then
    export LD_PRELOAD="$PWD/optional/exec.so:${LD_PRELOAD}"
  fi
  export LD_LIBRARY_PATH="${cxxpath}${gccpath}${LD_LIBRARY_PATH}"
fi

# return to original path
cd $OWD

$exec $*
exit $?

