#!/usr/bin/env sh
set -eu

BASE="${XESA_DOWNLOAD_BASE:-https://xesa.si/download}"
DEST="${XESA_INSTALL_DIR:-$HOME/.local/bin}"

os="$(uname -s | tr '[:upper:]' '[:lower:]')"
arch="$(uname -m)"
case "$arch" in
  x86_64|amd64) arch="amd64" ;;
  aarch64|arm64) arch="arm64" ;;
  *) echo "unsupported architecture: $arch" >&2; exit 1 ;;
esac
case "$os" in
  linux) os="linux" ;;
  darwin) os="darwin" ;;
  *) echo "unsupported OS: $os" >&2; exit 1 ;;
esac

url="$BASE/xesa-$os-$arch.tar"
bin="$DEST/xesa"
mkdir -p "$DEST"

echo "Downloading XESA for $os/$arch..."
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
if command -v curl >/dev/null 2>&1; then
  curl -fsSL "$url" -o "$tmp/xesa.tar"
elif command -v wget >/dev/null 2>&1; then
  wget -qO "$tmp/xesa.tar" "$url"
else
  echo "curl or wget is required" >&2
  exit 1
fi
tar -xf "$tmp/xesa.tar" -C "$tmp"
install -m 755 "$tmp/xesa" "$bin"

if [ "$os" = "linux" ]; then
  apps="$HOME/.local/share/applications"
  mkdir -p "$apps"
  if [ -d "$apps" ]; then
    cat > "$apps/xesa.desktop" <<EOF
[Desktop Entry]
Type=Application
Name=XESA Client
Comment=Local coding agent for XUSS AI
Exec="$bin"
Terminal=false
Icon=utilities-terminal
Categories=Development;
EOF
    chmod 644 "$apps/xesa.desktop"
  fi
fi

echo
echo "Installed: $bin"
echo "Run:       xesa"
if ! echo ":$PATH:" | grep -q ":$DEST:"; then
  echo
  echo "Add this to your shell profile:"
  echo "  export PATH=\"$DEST:\$PATH\""
fi
