#!/bin/bash -e
# Build rejig for the container's native platform(s).  Used by the
# Containerfile when running on podman farm nodes.  Produces Linux
# binaries always and tries to produce Windows ones as well using a
# MinGW cross-build toolchain for that same architecture.

OUTPUT_DIR="${OUTPUT_DIR:-/artifacts}"
BIN_DIR="$OUTPUT_DIR/bin"
mkdir -p "$BIN_DIR"

# Detect native arch from uname
case "$(uname -m)" in
x86_64)  GOARCH=amd64 ;;
aarch64) GOARCH=arm64 ;;
*)       echo "unsupported arch: $(uname -m)" >&2; exit 1 ;;
esac

ldflags="-s -w"
[ -n "$BRANCH" ]      && ldflags="$ldflags -X rejig/mode.Branch=$BRANCH"
[ -n "$COMMIT" ]      && ldflags="$ldflags -X rejig/mode.Commit=$COMMIT"
[ -n "$COMMIT_TIME" ] && ldflags="$ldflags -X rejig/mode.CommitTime=$COMMIT_TIME"
[ -n "$PRIOR" ]       && ldflags="$ldflags -X rejig/mode.PriorVersion=$PRIOR"
[ -n "$VERSION" ]     && ldflags="$ldflags -X rejig/mode.Version=$VERSION"

# --- Linux (native) ---
export GOOS=linux
export GOARCH
export CGO_LDFLAGS="-Wl,--gc-sections"

go build -buildvcs=false -ldflags "$ldflags" ./cmd/rejig
cp rejig "$BIN_DIR/rejig"
tar cJf "$OUTPUT_DIR/rejig-linux-$GOARCH.tar.xz" rejig
rm -f rejig

# --- Windows (cross, best-effort) ---
export GOOS=windows
export CGO_LDFLAGS=""

case "$GOARCH" in
amd64) CC=x86_64-w64-mingw32-gcc ;;
arm64) CC=aarch64-w64-mingw32-gcc ;;
*)     CC= ;;
esac

if [ -n "$CC" ] && command -v "$CC" >/dev/null 2>&1; then
    export CC
    if go build -buildvcs=false -ldflags "$ldflags" ./cmd/rejig 2>/dev/null; then
        cp rejig.exe "$BIN_DIR/rejig.exe"
        zip -q "$OUTPUT_DIR/rejig-windows-$GOARCH.zip" rejig.exe
        rm -f rejig.exe
    fi
fi
