#!/bin/sh
# Windows build: the package compiles to wickra.dll, which would collide with the
# C ABI's own wickra.dll (the loader would resolve the import to the package
# itself). Stage a renamed copy, wickra_abi.dll, into src/ and build a mingw
# import library that references it by that name (objdump + dlltool, both shipped
# with Rtools — no gendef/pexports needed). install.libs.R then bundles the DLL.
#
# Self-contained by default: download the prebuilt wickra-c-<triple>.tar.gz
# release asset matching this package's version. Set WICKRA_INCLUDE_DIR +
# WICKRA_LIB_DIR to build against a locally built C ABI instead (dev override).
set -e

# A freshly-cut GitHub release can briefly return 404 while its assets propagate
# across the CDN, and a transient network blip should not fail the build either.
# Retry base R's download.file with a backoff (~2 min total) instead of giving up
# on the first miss.
wickra_download() {
  _url="$1"
  _dest="$2"
  _attempt=1
  while [ "${_attempt}" -le 6 ]; do
    if "${R_HOME}/bin/Rscript" -e "download.file('${_url}', '${_dest}', mode = 'wb', quiet = TRUE)"; then
      return 0
    fi
    echo "wickra: download attempt ${_attempt}/6 failed (${_url}); the release asset may still be propagating — retrying in 20s..."
    sleep 20
    _attempt=$((_attempt + 1))
  done
  echo "wickra: failed to download ${_url} after 6 attempts"
  return 1
}

if [ -n "${WICKRA_INCLUDE_DIR}" ] && [ -n "${WICKRA_LIB_DIR}" ]; then
  echo "wickra: using C ABI from WICKRA_INCLUDE_DIR / WICKRA_LIB_DIR (dev override)"
  inc="${WICKRA_INCLUDE_DIR}"
  lib="${WICKRA_LIB_DIR}"
else
  version=$(sed -n 's/^Version:[[:space:]]*//p' DESCRIPTION)
  arch=$(uname -m)
  case "${arch}" in
    x86_64) triple="x86_64-pc-windows-msvc" ;;
    aarch64 | arm64) triple="aarch64-pc-windows-msvc" ;;
    *) echo "wickra: unsupported Windows arch '${arch}' — set WICKRA_INCLUDE_DIR/WICKRA_LIB_DIR"; exit 1 ;;
  esac
  url="https://github.com/wickra-lib/wickra/releases/download/v${version}/wickra-c-${triple}.tar.gz"
  echo "wickra: downloading C ABI ${triple} for v${version}"
  wickra_download "${url}" "src/wickra-c.tar.gz" || exit 1
  "${R_HOME}/bin/Rscript" -e "untar('src/wickra-c.tar.gz', exdir = 'src/wickra-c')"
  inc="src/wickra-c/wickra-c-${triple}/include"
  lib="src/wickra-c/wickra-c-${triple}/lib"
fi

cp "${inc}/wickra.h" src/wickra.h
cp "${lib}/wickra.dll" src/wickra_abi.dll
{
  echo 'LIBRARY wickra_abi.dll'
  echo 'EXPORTS'
  objdump -p src/wickra_abi.dll | awk '/\[ *[0-9]+\]/ {print $NF}' | grep '^wickra_'
} > src/wickra_abi.def
dlltool --input-def src/wickra_abi.def --dllname wickra_abi.dll \
  --output-lib src/libwickra_abi.dll.a
exit 0
