#!/bin/bash

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

strip_libpaths() {
  local stripped=()
  local libpaths=()
  for arg in $1; do
    if [[ $arg == "-L"* ]]; then
      libpaths+=(${arg:2})
    else
      stripped+=($arg)
    fi
  done
  printf "%s\n%s\n" "${stripped[*]}" "${libpaths[*]}"
}

get_libs() {
  local libpath=$1
  local libname=$2
  local libsfound=
  if [[ "$OSTYPE" == "linux-gnu"* ]]; then
    libsfound="$(find "$libpath" -maxdepth 1 -regextype sed -regex ".*/lib${libname}\.\(so\|a\)")"
  elif [[ "$OSTYPE" == "darwin"* ]]; then
    libsfound="$(find -E "$libpath" -maxdepth 1 -regex ".*/lib${libname}\.(so|dylib|tbd|a)")"
  fi
  echo "$libsfound"
}

set -e

cd "${MESON_SOURCE_ROOT}"

if [[ -n "$BTLLIB_PYTHON_CFLAGS" ]]; then
  cflags="$BTLLIB_PYTHON_CFLAGS"
  ldflags="$BTLLIB_PYTHON_LDFLAGS"
else
  cflags="$(python3-config --cflags)"
  ldflags="$(python3-config --ldflags)"
fi

libpython_required=0
for flag in $ldflags; do
  if [[ $flag == "-lpython"* ]]; then
    libpython_required=${flag:2}
  fi
done

if [[ $libpython_required != 0 ]]; then
  stripped_libpaths="$(strip_libpaths "${ldflags}")"

  ldflags="$(echo "$stripped_libpaths" | head -n1)"
  libpaths="$(echo "$stripped_libpaths" | tail -n1)"

  sysconfig_libdir="$(python -c 'from distutils import sysconfig; print (sysconfig.get_config_var("LIBDIR"))')"
  libpaths+=" $sysconfig_libdir"

  found=0
  for libpath in ${libpaths}; do
    libsfound="$(get_libs $libpath $libpython_required)"
    if [[ -n "$libsfound" ]]; then
      found=1
      break
    fi
  done
  if [[ $found -eq 0 ]]; then
    echo "ERROR"
    echo "libpython (.so, .dylib, .tbd, or .a) not found!"
    exit 1
  fi

  param_libpaths=
  for libpath in ${libpaths}; do
    param_libpaths+="-L${libpath} "
  done
  ldflags="$param_libpaths $ldflags"
fi

echo "SUCCESS"
echo "$cflags"
echo "$ldflags"