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

if command -v spacectl >/dev/null 2>&1; then
  spacectl version || true
  exit 0
fi

if ! command -v curl >/dev/null 2>&1; then
  echo "::error ::curl is required to install spacectl" >&2
  exit 1
fi
if ! command -v tar >/dev/null 2>&1; then
  echo "::error ::tar is required to install spacectl" >&2
  exit 1
fi

os="$(uname -s | tr '[:upper:]' '[:lower:]')"
arch="$(uname -m)"
case "$arch" in
  x86_64|amd64) arch="amd64" ;;
  aarch64|arm64) arch="arm64" ;;
  *)
    echo "::error ::Unsupported arch for spacectl: ${arch}" >&2
    exit 1
    ;;
esac

if [[ "$os" != "linux" && "$os" != "darwin" ]]; then
  echo "::error ::Unsupported OS for spacectl: ${os}" >&2
  exit 1
fi

version="${SPACECTL_VERSION:-v0.5.0}"
version_num="${version#v}"
asset="spacectl_${version_num}_${os}_${arch}.tar.gz"
url="https://github.com/namespacelabs/spacectl/releases/download/${version}/${asset}"
tmp_dir="${RUNNER_TEMP:-${TMPDIR:-/tmp}}/burrow-spacectl.$$"
install_dir="${RUNNER_TEMP:-${TMPDIR:-/tmp}}/spacectl-bin"
mkdir -p "$tmp_dir" "$install_dir"
trap 'rm -rf "$tmp_dir"' EXIT

curl -fsSL -o "${tmp_dir}/${asset}" "$url"
tar -xzf "${tmp_dir}/${asset}" -C "$tmp_dir"

bin="${tmp_dir}/spacectl"
if [[ ! -x "$bin" ]]; then
  bin="$(find "$tmp_dir" -maxdepth 3 -type f -name spacectl -perm -111 | head -n1 || true)"
fi
if [[ -z "${bin}" || ! -x "${bin}" ]]; then
  echo "::error ::Failed to locate spacectl binary in ${asset}" >&2
  exit 1
fi

install -m 0755 "$bin" "${install_dir}/spacectl"
if [[ -n "${GITHUB_PATH:-}" ]]; then
  echo "${install_dir}" >> "${GITHUB_PATH}"
fi
export PATH="${install_dir}:$PATH"
spacectl version || true
