#!/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"

#find out if we can use system's python or need included

if X_PYBIN_X -V &> /dev/null ; then
    retval=$(X_PYBIN_X -c "
from distutils import sysconfig as s;
from os import path as p;
v = s.get_config_vars();
print(p.join(v['LIBDIR'], v['LDLIBRARY']))")
fi
if [ -f "${retval}" ]; then
    echo "Using system python"
    export LD_PRELOAD=${retval}
else
    echo "Using bundled python"
    export PYTHONHOME=$(dirname "$0")X_PYROOT_X
    export LD_LIBRARY_PATH="$PWD/optional/python":${LD_LIBRARY_PATH}
fi

#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' < "$exec" | grep -e '^GLIBCXX_3\.4' | sort -V | 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}:${LD_LIBRARY_PATH}"
fi

# return to original path
cd $OWD

$exec $*
exit $?

