#!/bin/sh
# axon installer for macOS and Linux.
#
#   curl -fsSL https://guerchele.github.io/axon-releases/install.sh | sh
#
# Options (environment variables):
#   AXON_VERSION      version to install, e.g. 1.4.0 or v1.4.0   (default: latest)
#   AXON_INSTALL_DIR  where to put the binary                     (default: ~/.local/bin, or /usr/local/bin as root)
#   AXON_BASE_URL     download mirror; must serve <tag>/<asset> and latest/<asset>
#                     (default: GitHub releases of AXON_REPO)
#   AXON_REPO         public GitHub repo that hosts releases      (default: guerchele/axon-releases)
#
# The whole script is wrapped in main() so a truncated download never runs half a script.

set -eu

REPO="${AXON_REPO:-guercheLE/axon-releases}"
BIN="axon"

say()  { printf '%s\n' "axon-install: $*" >&2; }
err()  { say "error: $*"; exit 1; }
has()  { command -v "$1" >/dev/null 2>&1; }
need() { has "$1" || err "'$1' is required but was not found"; }

download() { # <url> <dest>
  if has curl; then
    curl --proto-redir '=https' -fsSL --retry 3 --connect-timeout 20 -o "$2" "$1"
  elif has wget; then
    wget -q -O "$2" "$1"
  else
    err "curl or wget is required"
  fi
}

sha256_of() {
  if has sha256sum; then sha256sum "$1" | awk '{print $1}'
  elif has shasum; then shasum -a 256 "$1" | awk '{print $1}'
  elif has openssl; then openssl dgst -sha256 -r "$1" | awk '{print $1}'
  else echo ""; fi
}

detect_target() {
  os=$(uname -s)
  arch=$(uname -m)
  case "$os" in
    Linux)
      if (ldd --version 2>&1 || true) | grep -qi musl; then
        err "musl-based Linux (e.g. Alpine) is not supported; axon needs glibc 2.38 or newer"
      fi
      glibc=$( (getconf GNU_LIBC_VERSION 2>/dev/null || true) | awk '{print $2}')
      if [ -n "$glibc" ]; then
        major=${glibc%%.*}; minor=${glibc#*.}; minor=${minor%%.*}
        if [ "$major" -lt 2 ] || { [ "$major" -eq 2 ] && [ "$minor" -lt 38 ]; }; then
          err "axon needs glibc 2.38 or newer (found $glibc): Ubuntu 24.04+, Debian 13+, Fedora 39+, RHEL 10+"
        fi
      fi
      os_part="unknown-linux-gnu" ;;
    Darwin)
      os_part="apple-darwin"
      # A Rosetta (x86_64) shell on Apple Silicon should still get the native arm64 build.
      if [ "$arch" = "x86_64" ] && [ "$(sysctl -n hw.optional.arm64 2>/dev/null || echo 0)" = "1" ]; then
        arch="arm64"
      fi ;;
    MINGW*|MSYS*|CYGWIN*)
      err "on Windows use PowerShell:  irm https://guerchele.github.io/axon-releases/install.ps1 | iex" ;;
    *) err "unsupported OS: $os" ;;
  esac
  case "$arch" in
    x86_64|amd64)  arch_part="x86_64" ;;
    arm64|aarch64) arch_part="aarch64" ;;
    *) err "unsupported CPU architecture: $arch" ;;
  esac
  echo "${arch_part}-${os_part}"
}

main() {
  need uname; need tar; need mktemp; need awk

  target=$(detect_target)
  version="${AXON_VERSION:-latest}"
  if [ "$version" != "latest" ]; then
    case "$version" in v*) ;; *) version="v$version" ;; esac
  fi

  if [ -n "${AXON_BASE_URL:-}" ]; then
    base="${AXON_BASE_URL%/}/$version"
  elif [ "$version" = "latest" ]; then
    base="https://github.com/$REPO/releases/latest/download"
  else
    base="https://github.com/$REPO/releases/download/$version"
  fi

  asset="$BIN-$target.tar.gz"
  tmp=$(mktemp -d 2>/dev/null || mktemp -d -t axon)
  trap 'rm -rf "$tmp"' EXIT INT TERM

  say "downloading $asset ($version)"
  download "$base/$asset" "$tmp/$asset" || err "download failed: $base/$asset"

  if download "$base/SHA256SUMS" "$tmp/SHA256SUMS" 2>/dev/null; then
    expected=$(awk -v f="$asset" '$2 == f || $2 == "*" f { print $1 }' "$tmp/SHA256SUMS")
    actual=$(sha256_of "$tmp/$asset")
    [ -n "$expected" ] || err "$asset is not listed in SHA256SUMS"
    if [ -n "$actual" ]; then
      [ "$expected" = "$actual" ] || err "checksum mismatch for $asset (expected $expected, got $actual)"
      say "checksum verified"
    else
      say "warning: no sha256 tool found; skipping checksum verification"
    fi
  else
    err "could not download SHA256SUMS from $base"
  fi

  tar -xzf "$tmp/$asset" -C "$tmp"
  src="$tmp/$BIN-$target/$BIN"
  [ -f "$src" ] || err "archive did not contain $BIN-$target/$BIN"

  if [ -n "${AXON_INSTALL_DIR:-}" ]; then
    dir="$AXON_INSTALL_DIR"
  elif [ "$(id -u)" = "0" ]; then
    dir="/usr/local/bin"
  else
    dir="$HOME/.local/bin"
  fi

  sudo_cmd=""
  if ! mkdir -p "$dir" 2>/dev/null || [ ! -w "$dir" ]; then
    need sudo
    sudo_cmd="sudo"
    say "$dir is not writable; using sudo"
    $sudo_cmd mkdir -p "$dir"
  fi

  # Copy then rename, so a running axon is never left half-written.
  $sudo_cmd cp "$src" "$dir/.$BIN.new"
  $sudo_cmd chmod 755 "$dir/.$BIN.new"
  $sudo_cmd mv -f "$dir/.$BIN.new" "$dir/$BIN"
  if [ "$(uname -s)" = "Darwin" ] && has xattr; then
    $sudo_cmd xattr -d com.apple.quarantine "$dir/$BIN" 2>/dev/null || true
  fi

  installed=$("$dir/$BIN" --version 2>/dev/null || echo "$BIN $version")
  say "installed $installed -> $dir/$BIN"

  case ":$PATH:" in
    *":$dir:"*) ;;
    *)
      say "$dir is not on your PATH. Add this to your shell profile:"
      say "  export PATH=\"$dir:\$PATH\"" ;;
  esac
}

main "$@"
