#!/bin/bash

if [ -z "${MESON_SOURCE_ROOT}" ]; then
  echo "[ERROR] This script can only be ran with meson!"
  exit 1
fi

set -e

# Remove old wrapper files
rm -f ${MESON_SOURCE_ROOT}/wrappers/python/btllib.py

# Generate python swig files
cd ${MESON_SOURCE_ROOT}

include_files=$(scripts/get-files include)

echo "%module btllib

%{
#define SWIG_FILE_WITH_INIT
" > wrappers/python/btllib.i

for file in ${include_files}; do
  relative=$(scripts/get-include-relative ${file})
  path="${relative}/$(basename ${file})"
  echo "#include \"$path\"" >> wrappers/python/btllib.i
done

echo "%}

%include <stdint.i>
%include <typemaps.i>
%include <pyprimtypes.swg>
%include <pyopers.swg>
%include <std_common.i>
%include <cstring.i>
%include <std_string.i>
%include <exception.i>
%include <std_iostream.i>
%include <carrays.i>
%include <std_vector.i>
%include <stl.i>

%include \"../extra_common.i\"
%include \"extra.i\"
" >> wrappers/python/btllib.i

for file in ${include_files}; do
  relative=$(scripts/get-include-relative ${file})
  path="${relative}/$(basename ${file})"
  echo "%include \"$path\"" >> wrappers/python/btllib.i
done

ln -sf $PWD/include wrappers/python/
cd wrappers/python
swig -python -py3 -fastproxy -fastdispatch -builtin -c++ -Iinclude btllib.i
rm -f include

# The following line is necessary because SWIG produces inconsistent code that cannot be compiled on all platforms. On some platforms, uint64_t is unsigned long int and unsigned long long int on others.
sed -i'.tmp' 's~unsigned long long~uint64_t~g' btllib_wrap.cxx
rm -f btllib_wrap.cxx.tmp