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

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

if ! command -v curl >/dev/null 2>&1; then
  echo "::error ::curl is required to install nsc" >&2
  exit 1
fi
if ! command -v tar >/dev/null 2>&1; then
  echo "::error ::tar is required to install nsc" >&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 nsc: ${arch}" >&2
    exit 1
    ;;
esac

if [[ "$os" != "linux" ]]; then
  echo "::warning ::nsc bootstrap is only supported on Linux; relying on the runner or Nix shell for ${os}."
  exit 1
fi

version="${NSC_VERSION:-0.0.520}"
expected_sha256=""
case "${version}/${arch}" in
  0.0.506/amd64) expected_sha256="4a093e0269878a9514e7c00d99b88a924f307ad15fb9d1595ee5f6582f99a0f0" ;;
  0.0.506/arm64) expected_sha256="6acf074b67fcbaaf59a4437f6bd40da7e38438c427849c1b5fcf4621ce75aee2" ;;
esac

asset="nsc_${version}_linux_${arch}.tar.gz"
url="https://get.namespace.so/packages/nsc/v${version}/${asset}"
tmp_dir="${RUNNER_TEMP:-${TMPDIR:-/tmp}}/burrow-nsc.$$"
install_dir="${RUNNER_TEMP:-${TMPDIR:-/tmp}}/nsc-bin"
mkdir -p "$tmp_dir" "$install_dir"
trap 'rm -rf "$tmp_dir"' EXIT

curl -fsSL -o "${tmp_dir}/${asset}" "$url"
if [[ -n "$expected_sha256" ]] && command -v sha256sum >/dev/null 2>&1; then
  actual_sha256="$(sha256sum "${tmp_dir}/${asset}" | awk '{print $1}')"
  if [[ "$actual_sha256" != "$expected_sha256" ]]; then
    echo "::error ::nsc ${asset} sha256 mismatch: expected ${expected_sha256}, got ${actual_sha256}" >&2
    exit 1
  fi
fi

tar -xzf "${tmp_dir}/${asset}" -C "$tmp_dir"
for bin in nsc bazel-credential-nsc docker-credential-nsc; do
  if [[ -x "${tmp_dir}/${bin}" ]]; then
    install -m 0755 "${tmp_dir}/${bin}" "${install_dir}/${bin}"
  fi
done

if [[ ! -x "${install_dir}/nsc" || ! -x "${install_dir}/bazel-credential-nsc" ]]; then
  echo "::error ::Failed to install nsc and bazel-credential-nsc from ${asset}" >&2
  exit 1
fi

if [[ -n "${GITHUB_PATH:-}" ]]; then
  echo "${install_dir}" >> "${GITHUB_PATH}"
fi
export PATH="${install_dir}:$PATH"
nsc version || true
