#!/bin/sh

checkopt() {
  if test -x ocaml/"$1".opt; then
    printf '.opt'
  else
    printf '.byte'
  fi
}

# [path(solo5)] is important because it explains, from the user's point of
# view, where we could find the OCaml compiler to generate a Solo5 unikernel,
# but also where we could find the OCaml libraries (which is what findlib is
# all about).
#
# The current choice is to consider the artefacts available in an OPAM switch
# as possible solutions to the dependencies of a unikernel. For example, if a
# unikernel depends on the [fmt] library, we give the option of using
# [fmt.cmx{,a}] from [opam install fmt]. Reusing what may have been compiled by
# the host OCaml compiler and installed via OPAM poses no problem in principle,
# since we are not changing the way an OCaml file is compiled between the host
# OCaml compiler and our cross-compiler, which uses Solo5. In fact, the
# [*.cmx{,a}] files generated by the two compilers are strictly the same.
#
# However, the difference will be in the generation of the object files and the
# link, but the build-system can ensure that our compiler is used at these
# times.
#
# The only problem concerns the [*.a] archives installed via OPAM. These are
# not compiled with our C compiler for Solo5. The mirage tool takes care of
# downloading the sources of the unikernel dependencies so that if they contain
# C files, they can be compiled with our cross-compiler. However, this is a
# choice relating to the mirage tool that we should not impose at this level
# (that of simply offering a cross-compiler). We also know that with dune,
# primacy is given to the sources available in the dune environment rather than
# to the artefacts available via OPAM/findlib.
#
# So, compiling a project with our Solo5 toolchain gives the user the
# possibility of reusing what is available in OPAM and already installed. On
# the very specific question of [*.a] archives, it is up to the user to take
# care not to reuse the [*.a] files offered by OPAM/findlib but to recompile
# them themselves with our cross-compiler from the sources. In this case, the
# mirage tool takes care of this detail, using opam monorepo.

cat << EOF
path(solo5) = "$SYSROOT/lib/ocaml:$SYSROOT/lib:$PREFIX/lib"
destdir(solo5) = "$PREFIX/lib"
stdlib(solo5) = "$SYSROOT/lib/ocaml"
ocamlopt(solo5) = "$SYSROOT/bin/ocamlopt$(checkopt ocamlopt)"
ocamlc(solo5) = "$SYSROOT/bin/ocamlc$(checkopt ocamlc)"
ocamlmklib(solo5) = "$SYSROOT/bin/ocamlmklib"
ocamldep(solo5) = "$SYSROOT/bin/ocamldep$(checkopt tools/ocamldep)"
ocamlcp(solo5) = "$SYSROOT/bin/ocamlcp"
EOF
