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

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

case "$os" in
  darwin|linux) ;;
  *) echo "Unsupported OS: $os" >&2; exit 1 ;;
esac

version="${X4RGE_CLI_VERSION:-latest}"
base="https://4rged.ai/downloads/cli"
artifact="4rged-${version}-${os}-${arch}.tar.gz"
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT

curl -fLsS "$base/$artifact" -o "$tmp/$artifact"
curl -fLsS "$base/$artifact.sha256" -o "$tmp/$artifact.sha256"
(cd "$tmp" && shasum -a 256 -c "$artifact.sha256")
tar -xzf "$tmp/$artifact" -C "$tmp"

install_dir="${X4RGE_CLI_INSTALL_DIR:-$HOME/.local/bin}"
mkdir -p "$install_dir"
install "$tmp/4rged" "$install_dir/4rged"

echo "4RGED installed at $install_dir/4rged"
echo "Run: 4rged login"
echo "Then: 4rged"
