#!/bin/sh

set -x
set -e

ARCH="$(uname -m)"
INSTALL_PREFIX="$DRONE_WORKSPACE/stage3-release"

export ZIG_GLOBAL_CACHE_DIR="$DRONE_WORKSPACE/zig-cache"

PREFIX="/deps/local"
ZIG="$PREFIX/bin/zig"
TARGET="$ARCH-linux-musl"
MCPU="baseline"

export CC="$ZIG cc -target $TARGET -mcpu=$MCPU"
export CXX="$ZIG c++ -target $TARGET -mcpu=$MCPU"

# The `CMAKE_AR` parameter will consider any spaces to
# be part of the executable path rather than CLI args, so we have
# to create wrapper scripts for `zig ar` and zig ranlib`.
cat <<'ENDFILE' >$PREFIX/bin/ar
#!/bin/sh
/deps/local/bin/zig ar $@
ENDFILE

cat <<'ENDFILE' >$PREFIX/bin/ranlib
#!/bin/sh
/deps/local/bin/zig ranlib $@
ENDFILE

chmod +x "$PREFIX/bin/ar"
chmod +x "$PREFIX/bin/ranlib"

# Make the `zig version` number consistent.
# This will affect the cmake command below.
git config core.abbrev 9
git fetch --unshallow || true
git fetch --tags

mkdir build
cd build
cmake .. \
  -DCMAKE_PREFIX_PATH="$PREFIX" \
  -DCMAKE_INSTALL_PREFIX="$INSTALL_PREFIX" \
  -DCMAKE_BUILD_TYPE=Release \
  -DCMAKE_AR="$PREFIX/bin/ar" \
  -DCMAKE_RANLIB="$PREFIX/bin/ranlib" \
  -DZIG_TARGET_TRIPLE="$TARGET" \
  -DZIG_TARGET_MCPU="$MCPU" \
  -DZIG_STATIC=ON \
  -GNinja

# Now CMake will use Zig as the C/C++ compiler. We reset the environment variables
# so that installation and testing do not get affected by them.
unset CC
unset CXX
samu install
