#!/bin/bash
# Shared architecture detection for build scripts.
# Source this file, then call: resolve_arch [target_arch]
#
# Outputs (exported):
#   NFPM_ARCH    — nfpm arch name: "amd64" or "arm64"
#   RPM_ARCH     — RPM arch name: "x86_64" or "aarch64"
#   BUN_TARGET   — bun cross-compile target (empty if native build)
#   ARCH_SUFFIX  — filename suffix for cross-compiled binaries (empty if native)

_detect_native_arch() {
  case "$(uname -m)" in
    x86_64)  echo "amd64" ;;
    aarch64) echo "arm64" ;;
    arm64)   echo "arm64" ;;  # macOS reports arm64
    *)       echo "amd64" ;;  # fallback
  esac
}

_bun_target_for() {
  local arch="$1"
  case "$arch" in
    amd64) echo "bun-linux-x64" ;;
    arm64) echo "bun-linux-arm64" ;;
  esac
}

_nfpm_download_arch() {
  local arch="$1"
  case "$arch" in
    amd64) echo "x86_64" ;;
    arm64) echo "arm64" ;;
  esac
}

# resolve_arch [override]
#   override: "amd64" or "arm64" (optional, auto-detects if empty)
resolve_arch() {
  local requested="${1:-}"
  local native
  native="$(_detect_native_arch)"

  if [ -z "$requested" ]; then
    # Native build
    NFPM_ARCH="$native"
    BUN_TARGET=""
    ARCH_SUFFIX=""
  else
    NFPM_ARCH="$requested"
    if [ "$requested" = "$native" ]; then
      # Requesting our own arch — native build
      BUN_TARGET=""
      ARCH_SUFFIX=""
    else
      # Cross-compilation
      BUN_TARGET="$(_bun_target_for "$requested")"
      ARCH_SUFFIX="-${requested}"
    fi
  fi

  # RPM uses different arch names than deb/nfpm
  case "$NFPM_ARCH" in
    amd64) RPM_ARCH="x86_64" ;;
    arm64) RPM_ARCH="aarch64" ;;
    *)     RPM_ARCH="$NFPM_ARCH" ;;
  esac

  export NFPM_ARCH RPM_ARCH BUN_TARGET ARCH_SUFFIX
  echo "  Architecture: ${NFPM_ARCH} (native: ${native}${BUN_TARGET:+, cross-compiling via $BUN_TARGET})"
}
