#!/bin/bash
# Build pkgcraft-c library for bundling with pkgcraft python wheels.

set -e
env

doecho() {
	echo "\$ $*"
	"$@"
}

: ${CARGO_C_VERSION:=0.9.29}
: ${PKGCRAFT_C_REF:=main}
echo Building pkgcraft-c on ${OSTYPE} for ${HOSTTYPE}

# install rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
doecho source "${HOME}"/.cargo/env

# install required libs on linux
install_pkgs() {
	local -a packages=( clang )
	# git is required when not building against a tagged release
	[[ ${PKGCRAFT_C_REF} == "main" ]] && packages+=( git )

	# non-native targets require openssl headers to compile cargo-c
	if [[ ${HOSTTYPE} != "x86_64" ]]; then
		packages+=( openssl-devel )
	fi

	if [[ ${OSTYPE} == "linux-gnu" ]]; then
		doecho dnf makecache --refresh
		doecho dnf -y install ${packages[@]}
	elif [[ ${OSTYPE} == "linux-musl" ]]; then
		doecho apk update
		doecho apk add ${packages[@]}
	fi
}

[[ ${OSTYPE} == "linux-"* ]] && install_pkgs

# install binary cargo-c package if available
if [[ ${OSTYPE} == "linux-"* ]]; then
	if [[ ${HOSTTYPE} == "aarch64" ]]; then
		curl -L https://github.com/lu-zero/cargo-c/releases/download/v${CARGO_C_VERSION}/cargo-c-aarch64-unknown-linux-musl.tar.gz | tar xvzf - -C "${HOME}"/.cargo/bin
	elif [[ ${HOSTTYPE} == "x86_64" ]]; then
		curl -L https://github.com/lu-zero/cargo-c/releases/download/v${CARGO_C_VERSION}/cargo-c-x86_64-unknown-linux-musl.tar.gz | tar xvzf - -C "${HOME}"/.cargo/bin
	else
		SOURCE_CARGO_C=true
	fi
elif [[ ${OSTYPE} == "darwin"* ]]; then
	if [[ ${HOSTTYPE} == "x86_64" ]]; then
		curl -L https://github.com/lu-zero/cargo-c/releases/download/v${CARGO_C_VERSION}/cargo-c-macos.zip > cargo-c.zip
		unzip -o cargo-c.zip -d "${HOME}"/.cargo/bin
		rm cargo-c.zip
	else
		SOURCE_CARGO_C=true
	fi
fi

# manually build cargo-c for arches without native binaries
[[ -n ${SOURCE_CARGO_C} ]] && doecho cargo install cargo-c@${CARGO_C_VERSION}
# output cargo-c version
cargo cinstall --version

# build and install C library
doecho git clone --depth 1 -b ${PKGCRAFT_C_REF} --recurse-submodules https://github.com/pkgcraft/pkgcraft.git
cd pkgcraft && doecho cargo cinstall --profile release-strip -p pkgcraft-c
