#!/usr/bin/env bash
set -euo pipefail

if [[ "$(uname -s)" == "Linux" && "$(uname -m)" == "x86_64" ]]; then
  export CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER=/usr/bin/cc
  export CC_x86_64_unknown_linux_gnu=/usr/bin/cc
  export CXX_x86_64_unknown_linux_gnu=/usr/bin/c++
fi

if [[ $# -ne 2 ]]; then
  echo "usage: scripts/smoke-dist ARTIFACT_DIRECTORY VERSION" >&2
  exit 2
fi

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
artifact_dir="$(cd "$1" && pwd)"
version="$2"
wheel="$(find "$artifact_dir" -maxdepth 1 -type f -name '*.whl' -print -quit)"
sdist="$(find "$artifact_dir" -maxdepth 1 -type f -name '*.tar.gz' -print -quit)"
if [[ -z "$wheel" || -z "$sdist" ]]; then
  echo "artifact directory must contain a wheel and source distribution" >&2
  exit 2
fi

smoke_root="$(mktemp -d)"
trap 'rm -rf "$smoke_root"' EXIT
mkdir "$smoke_root/run"

uv venv --python 3.10 "$smoke_root/wheel-env"
wheel_python="$smoke_root/wheel-env/bin/python"
uv pip install --python "$wheel_python" "$wheel"
(
  cd "$smoke_root/run"
  "$wheel_python" -I "$repo_root/scripts/smoke_installed.py" "$version"
  "$smoke_root/wheel-env/bin/foamwiki" --help >/dev/null
  "$wheel_python" -I -m foamwiki --help >/dev/null
)

uv venv --python 3.14 "$smoke_root/sdist-env"
sdist_python="$smoke_root/sdist-env/bin/python"
uv pip install --python "$sdist_python" "$sdist"
(
  cd "$smoke_root/run"
  "$sdist_python" -I "$repo_root/scripts/smoke_installed.py" "$version"
  "$smoke_root/sdist-env/bin/foamwiki" --help >/dev/null
)
