#!/usr/bin/env bash

set -euo pipefail

# shellcheck source=script/fetch_tarball.sh
. "$(dirname "${BASH_SOURCE[0]:-$0}")/fetch_tarball.sh"

if  [[ -z "${BABASHKA_STATIC:-}" ]]; then
    echo "BABASHKA_STATIC wasn't set, skipping musl installation."
    exit 0
fi

if [[ -z "${BABASHKA_MUSL:-}" ]]; then
    echo "BABASHKA_MUSL wasn't set, skipping musl installation."
    exit 0
fi

if [[ "${BABASHKA_ARCH:-"x86_64"}" != "x86_64" ]]; then
    echo "GraalVM only supports building static binaries on x86_64."
    exit 1
fi

# Build musl from source instead of taking the distro's musl-tools, which
# pins bullseye's musl 1.2.2 from 2021 and changes with the build image.
# The version follows the musl toolchain that the setup-graalvm GitHub
# action installs, currently 1.2.5, except that this pin does not move back
# past a fixed advisory: 1.2.5 is covered by one that 1.2.6 fixes.
MUSL_VERSION="1.2.6"
MUSL_SHA256="d585fd3b613c66151fc3249e8ed44f77020cb5e6c1e635a616d3f9f82460512a"

fetch_tarball "musl-${MUSL_VERSION}.tar.gz" "$MUSL_SHA256" \
    "https://musl.libc.org/releases/musl-${MUSL_VERSION}.tar.gz" \
    "https://sources.buildroot.net/musl/musl-${MUSL_VERSION}.tar.gz" \
    "https://sources.openwrt.org/musl-${MUSL_VERSION}.tar.gz" \
    "http://deb.debian.org/debian/pool/main/m/musl/musl_${MUSL_VERSION}.orig.tar.gz"

tar xf "musl-${MUSL_VERSION}.tar.gz"

cd "musl-${MUSL_VERSION}"
./configure --prefix=/usr/local/musl
make -j"$(nproc)"
make install
cd ..

# kernel headers are not part of musl; the distro musl-tools wires them in,
# a source build needs the classic symlinks. Debian keeps asm under the
# multiarch dir.
ln -sfn /usr/include/linux /usr/local/musl/include/linux
ln -sfn /usr/include/asm-generic /usr/local/musl/include/asm-generic
ln -sfn "/usr/include/$(gcc -print-multiarch)/asm" /usr/local/musl/include/asm

ln -sf /usr/local/musl/bin/musl-gcc /usr/bin/musl-gcc

ZLIB_VERSION="1.2.13"
ZLIB_SHA256="b3a24de97a8fdbc835b9833169501030b8977031bcb54b3b3ac13740f846ab30"

fetch_tarball "zlib-${ZLIB_VERSION}.tar.gz" "$ZLIB_SHA256" \
    "https://zlib.net/fossils/zlib-${ZLIB_VERSION}.tar.gz" \
    "https://github.com/madler/zlib/releases/download/v${ZLIB_VERSION}/zlib-${ZLIB_VERSION}.tar.gz"

tar xf "zlib-${ZLIB_VERSION}.tar.gz"

arch=${BABASHKA_ARCH:-"x86_64"}
echo "ARCH: $arch"

# into the musl sysroot: that is the library path musl-gcc.specs adds, so
# native-image finds -lz there
cd "zlib-${ZLIB_VERSION}"
CC=musl-gcc ./configure --static --prefix="/usr/local/musl"
make CC=musl-gcc
make install
cd ..

# the distro musl-tools used to put it here; keep it for anything that
# still looks in the old location
install -Dm644 "/usr/local/musl/lib/libz.a" "/usr/lib/$arch-linux-musl/libz.a"

ln -s /usr/bin/musl-gcc /usr/bin/x86_64-linux-musl-gcc
