#!/usr/bin/env bash
set -e

OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)

case "$OS" in
  darwin) OS=macos ;;
  linux) OS=linux ;;
  *) echo "🐾 Unsupported OS: $OS" >&2; exit 1 ;;
esac

case "$ARCH" in
  x86_64) ARCH=x64 ;;
  arm64|aarch64) ARCH=arm64 ;;
  *) echo "🐾 Unsupported arch: $ARCH" >&2; exit 1 ;;
esac

BINARY="toes-${OS}-${ARCH}"
URL="__TOES_URL__/dist/${BINARY}"

if [ -n "$TOES_INSTALL_DIR" ]; then
  INSTALL_DIR="$TOES_INSTALL_DIR"
elif [ -d /usr/local/bin ] && [ -w /usr/local/bin ]; then
  INSTALL_DIR=/usr/local/bin
else
  INSTALL_DIR="$HOME/.local/bin"
fi
mkdir -p "$INSTALL_DIR"

echo "🐾 Downloading toes CLI (${OS}/${ARCH})..."
curl -fsSL "$URL" -o "$INSTALL_DIR/toes"
chmod +x "$INSTALL_DIR/toes"
echo "🐾 Installed toes to $INSTALL_DIR/toes"

if ! echo "$PATH" | tr ':' '\n' | grep -qx "$INSTALL_DIR"; then
  echo "🐾 Add $INSTALL_DIR to your PATH to use toes globally"
fi
