#!/bin/sh
# $ opam install zarith
# https://github.com/ocaml/Zarith/issues/77#issuecomment-991797884
#
# 'Opam install fails with OCaml 4.12 flambda musl static'
# https://github.com/nberth/mlgmpidl/issues/11#issuecomment-884881150
#
set -eu
cd "$(dirname "$0")" || exit 1

musl-gcc --version >/dev/null || {
  echo "install \$ sudo apt-get install musl-tools"
  exit 1
}
lzip --version >/dev/null || {
  echo "install \$ sudo apt-get install lzip"
  exit 1
}

readonly prefix="$HOME/.opam/$(opam switch show)/share/gmp-prefix"

# rm -r "$prefix" 2>/dev/null || true
mkdir -p "$prefix"
cd "$prefix" || exit 1

# MUSL-based GMP
ver="gmp-6.2.1"
if [ ! -r "${prefix}/lib/libgmp.a" ]
then
  curl --silent -LO "https://gmplib.org/download/gmp/${ver}.tar.lz" \
  && tar xaf "${ver}.tar.lz" \
  && cd "${ver}" \
  && CC=musl-gcc ./configure --enable-fat --prefix "$prefix" \
  && nice make \
  && nice make check \
  && make install \
  && cd ..
fi
# --enable-fat https://codeberg.org/seppo/seppo/issues/2
# https://discuss.ocaml.org/t/sigill-crash-in-mirage-crypto-pk-rsa-generate/12209

# https://github.com/ocaml/Zarith/issues/77#issuecomment-991797884
CPPFLAGS=-I"$prefix/include" LDFLAGS=-L"$prefix/lib" opam upgrade zarith --yes
