#!/bin/sh
set -eu

BINARY="autoshelf"
VERSION="latest"
BASE_URL="https://useautoshelf.com/cli"

UNAME_S="$(uname -s)"
UNAME_M="$(uname -m)"

case "$UNAME_S" in
  Darwin) ;;
  *)
    echo "Unsupported OS: $UNAME_S (macOS only)"
    exit 1
    ;;
esac

case "$UNAME_M" in
  arm64)  ARCH="arm64" ;;
  x86_64) ARCH="amd64" ;;
  *)
    echo "Unsupported architecture: $UNAME_M"
    exit 1
    ;;
esac

TARBALL="$BINARY-darwin-$ARCH.tar.gz"
URL="$BASE_URL/$TARBALL"

echo "Downloading autoshelf ($ARCH)..."

TMPDIR="$(mktemp -d)"
trap "rm -rf \"$TMPDIR\"" EXIT

curl -sfL "$URL" -o "$TMPDIR/$TARBALL"

tar xzf "$TMPDIR/$TARBALL" -C "$TMPDIR"

if [ -w /usr/local/bin ]; then
  install -m 755 "$TMPDIR/$BINARY" /usr/local/bin/$BINARY
else
  echo ""
  echo "  /usr/local/bin is not writable by your user — this is normal on macOS."
  echo "  macOS System Integrity Protection (SIP) restricts write access to"
  echo "  system directories. The script will use sudo to install there."
  echo ""
  sudo install -m 755 "$TMPDIR/$BINARY" /usr/local/bin/$BINARY
fi

echo ""
echo "  autoshelf installed to /usr/local/bin/$BINARY"
echo "  Run 'autoshelf --help' to get started."
