#!/bin/sh
# check the go command and version
# copied from https://github.com/walkerke/pmtiles/blob/main/configure.win
# Detect architecture

# Restore flatbuf files from tools/ to vendor directory during installation
if [ -d "tools/flatbuf" ] && [ ! -d "inst/go/vendor/github.com/apache/arrow/go/v18/arrow/internal/flatbuf" ]; then
  echo "***********************************************************************"
  echo "Restoring flatbuf files from tools/flatbuf..."
  echo "***********************************************************************"
  mkdir -p inst/go/vendor/github.com/apache/arrow/go/v18/arrow/internal/flatbuf
  cp -r tools/flatbuf/* inst/go/vendor/github.com/apache/arrow/go/v18/arrow/internal/flatbuf/
  echo "Flatbuf files restored."
fi

if [ -z "$R_ARCH" ]; then
  # Try to detect from PROCESSOR_ARCHITECTURE or uname
  if [ -n "$PROCESSOR_ARCHITECTURE" ]; then
    ARCH="$PROCESSOR_ARCHITECTURE"
  else
    ARCH=$(uname -m)
  fi
else
  # R_ARCH is set (e.g., /x64 or /i386)
  ARCH="$R_ARCH"
fi

# Map to binary architecture
case "$ARCH" in
  *64*|*amd64*|*x86_64*|AMD64)
    BINARCH="amd64"
    ;;
  *arm64*|*aarch64*|ARM64)
    BINARCH="arm64"
    ;;
  *)
    BINARCH="amd64"  # Default to amd64
    ;;
esac
if ! command -v go >/dev/null 2>&1; then
echo "***********************************************************************"
  echo "Go is not found on your system."
  echo "Pre-compiled binaries are not available for ${BINARCH}."
  echo "Please install Go (>= 1.22) to build from source."
  echo "Visit https://golang.org/doc/install for installation instructions."
  echo "***********************************************************************"
  exit 1
fi
