#!/usr/bin/env bash
# Downloads and installs a specific abbaye version.
# Compatible with both asdf (positional args) and mise (env vars).
set -euo pipefail

VERSION="${ASDF_INSTALL_VERSION:-${2:-}}"
INSTALL_DIR="${ASDF_INSTALL_PATH:-${3:-}}"

if [ -z "$VERSION" ] || [ -z "$INSTALL_DIR" ]; then
  echo "Usage: install <tool> <version> <install_dir>"
  echo "Or set ASDF_INSTALL_VERSION and ASDF_INSTALL_PATH env vars."
  exit 1
fi

# Map current platform to the target-triple naming used in releases.
ARCH=$(uname -m)
OS=$(uname -s)

case "$ARCH:$OS" in
  x86_64:Linux)  TARGET="x86_64-unknown-linux-musl" ;;
  aarch64:Linux) TARGET="aarch64-unknown-linux-musl" ;;
  x86_64:Darwin) TARGET="x86_64-apple-darwin"  ;;
  *)
    echo "Unsupported platform: $ARCH $OS"
    echo "Open an issue at https://todo.sr.ht/~ololduck/abbaye to request a build for your platform."
    exit 1
    ;;
esac

URL="https://vit.am/~ololduck/abbaye/$VERSION/dist/abbaye-$VERSION-$TARGET"

echo "Downloading abbaye v$VERSION for $TARGET..."
curl -sSfL "$URL" -o "$INSTALL_DIR/abbaye"
chmod +x "$INSTALL_DIR/abbaye"
echo "Installed abbaye v$VERSION to $INSTALL_DIR/abbaye"
