#!/usr/bin/env bash
set -uo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
DIST_DIR="${ROOT_DIR}/dist"

mkdir -p "${DIST_DIR}"
: "${GOCACHE:=/tmp/go-build}"
mkdir -p "${GOCACHE}"

TARGETS=(
  "darwin amd64"
  "darwin arm64"
  "linux amd64"
  "linux arm64"
  "windows amd64"
)

host_os="$(go env GOOS)"
host_arch="$(go env GOARCH)"
build_failed=0

for target in "${TARGETS[@]}"; do
  read -r goos goarch <<<"${target}"

  ext=""
  if [[ "${goos}" == "windows" ]]; then
    ext=".exe"
  fi

  output="${DIST_DIR}/ztorrent-${goos}-${goarch}${ext}"
  rm -f "${output}"
  echo "Building ${output}"

  if [[ "${goos}" == "${host_os}" ]]; then
    if ! GOCACHE="${GOCACHE}" CGO_ENABLED=1 GOOS="${goos}" GOARCH="${goarch}" go build -o "${output}" ./cmd/torrent-client; then
      echo "Failed to build local target ${goos}/${goarch}"
      build_failed=1
    fi
    continue
  fi

  echo "Skipping ${goos}/${goarch}: native GUI build requires building on that target OS/arch (or a configured cross C toolchain)."
done

if [[ "${build_failed}" -ne 0 ]]; then
  exit 1
fi

echo "Build complete. Artifacts are in ${DIST_DIR}"
