#!/bin/zsh
# Main build script, invoked locally and within Docker containers.

. stdlib.zsh || exit 2
: ${MDBIN_STATIC:=0}

LOC="$(dirname "$(realpath "$0")")"
. "$LOC/pkg-info.sh"
if [[ -z $PACKAGE_NAME || -z $PACKAGE_VERSION ]]; then
	die "missing package name/version"
fi
msg "preparing to build [green]${PACKAGE_NAME} [magenta]${PACKAGE_VERSION}[reset]"

: ${BUILD_DIR:=target/release}
: ${PACKAGE_DIST:=target/dist}

typeset -a build_args=()
if [[ $MDBIN_TARGET ]]; then
	TARGET="$MDBIN_TARGET"
	build_args+=(--target "$MDBIN_TARGET")
	BUILD_DIR="target/$TARGET/release"
else
	TARGET="$(rustc -vV | sed -n 's/host:[[:space:]]*//p')"
fi

PACKAGE_FILE="$PACKAGE_NAME-$PACKAGE_VERSION-$TARGET.tgz"

msg "building for [cyan]$TARGET"
if [[ $OSTYPE == darwin* ]]; then
	: ${MACOSX_DEPLOYMENT_TARGET:=10.12}
	export MACOSX_DEPLOYMENT_TARGET
	msg "MacOS target version: $MACOSX_DEPLOYMENT_TARGET"
fi

if [[ $usage_static ]]; then
	msg "enabling static build"
	export RUSTFLAGS='-C target-feature=+crt-static'
fi

msg -action "compiling release build"
cargo build --release "${build_args[@]}" || die "cargo build failed"

msg -action "bundling binary"
mkdir -p "$PACKAGE_DIST"
tar czf "$PACKAGE_DIST/$PACKAGE_FILE" -C "$BUILD_DIR" "$PACKAGE_NAME" ||
	die "packaging failed"
msg -success "created [yellow]${PACKAGE_FILE}"
