#!/bin/sh
# aish universal installer — detects OS/arch and installs the right binary.
#
#   curl -fsSL https://www.ai-sh.net/install.sh | sh
#
# Environment:
#   AISH_INSTALL_DIR   directory to install to (default: /usr/local/bin)
#   AISH_SERVER        download server base URL (default: https://www.ai-sh.net)

set -e

: "${AISH_SERVER:=https://www.ai-sh.net}"
: "${AISH_INSTALL_DIR:=/usr/local/bin}"

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) ext="" ;;
  mingw*|msys*|cygwin*|windows*) os=windows; ext=".exe" ;;
  *) echo "unsupported os: $os" >&2; exit 1 ;;
esac

binary="aish-${os}-${arch}${ext}"
url="${AISH_SERVER}/dl/${binary}"

echo "downloading ${binary} from ${url}"
tmp=$(mktemp)
if ! curl -fsSL "$url" -o "$tmp"; then
  echo "download failed: $url" >&2
  rm -f "$tmp"
  exit 1
fi
chmod +x "$tmp"

target="${AISH_INSTALL_DIR}/aish${ext}"
if [ -w "$AISH_INSTALL_DIR" ]; then
  mv "$tmp" "$target"
else
  echo "elevated privileges needed to install to $AISH_INSTALL_DIR"
  sudo mv "$tmp" "$target"
fi

echo "installed to $target"
echo
echo "next step: create ${AISH_INSTALL_DIR}/aish.json next to the binary (see https://www.ai-sh.net)"
