#!/bin/zsh
#MISE description="Compile Linux binaries with Docker."
#USAGE flag "-v --verbose" help="enable verbose logging"
#USAGE flag "--static" help="build static release"
#USAGE flag "-p --podman" help="use podman instead of docker"
#USAGE flag "-A --arch <arch>" help="build for <arch>"
#USAGE flag "-B --bindist <path>" env="MDBIN_PATH" default="bindist" help="path to bindist tools within root"
#USAGE arg "<dist>" help="use container <dist>"

set -eo pipefail
ZSL_USAGE=1
. stdlib.zsh || exit 2

cleanup() {
	if [[ $CF ]]; then
		msg -dbg "removing $CF"
		rm -f "$CF"
	fi
}
trap cleanup EXIT INT TERM

if [[ -z $usage_bindist ]]; then
	die "no bindist location specified"
elif [[ ! -x "$usage_bindist/do-build.sh" ]]; then
	die "cannot find bindist at $usage_bindist"
else
	export MDBIN_PATH="${usage_bindist}"
fi

. "$MDBIN_PATH/pkg-info.sh"
msg "preparing to build [green]${PACKAGE_NAME} [magenta]${PACKAGE_VERSION}[reset]"

: ${DOCKER:=docker}

typeset -a rb_args=() db_args=() dr_args=()
if [[ $usage_static ]]; then
	rb_args+='--static'
fi
if [[ $usage_podman ]]; then
	DOCKER=podman
fi
out_name="$usage_dist"
if [[ $usage_arch ]]; then
	db_args+=(--platform linux/$usage_arch)
	dr_args+=(--platform linux/$usage_arch)
	out_name="$out_name-$usage_arch"
fi
base_name="$PACKAGE_NAME-build-base:$out_name"
img_name="$PACKAGE_NAME-build:$out_name"

(
	set -e
	msg -action "preparing base container [cyan]${usage_dist}"
	cd "$MDBIN_PATH"
	"$DOCKER" build "${db_args[@]}" -t "$base_name" -f "Dockerfile.$usage_dist" .
) || die "failed to build base container"

if [[ $OSTYPE = darwin* ]]; then
	CF="$(mktemp -t Dockerfile)"
else
	CF="$(mktemp -t Dockerfile.XXXXXXXX)"
fi
msg -dbg "creating docker file $CF"
cat >>"$CF" <<EOC
FROM $base_name
COPY . /src
EOC

msg -action "preparing build container [cyan]${usage_dist}"
mkdir -p target/dist
if [[ $DOCKER = *podman ]]; then
	dist_vol="$out_name-dist"
else
	dist_vol="$PWD/target/dist"
fi
"$DOCKER" build -t "$img_name" -f "$CF" "${db_args[@]}" .
"$DOCKER" run --rm -e "PACKAGE_NAME=$PACKAGE_NAME" -e "PACKAGE_VERSION=$PACKAGE_VERSION" \
	-v "$dist_vol:/dist" "${dr_args[@]}" \
	"$img_name" build:local-release "${rb_args[@]}"
if [[ $DOCKER = *podman ]]; then
	podman volume export "$dist_vol" | tar xvf - -C target/dist
fi
