#!/bin/sh
# Ample CLI installer
# Usage: curl -fsSL https://get.ample.computer/install.sh | sh
set -e

BASE_URL="${AMPLE_DOWNLOAD_URL:-https://get.ample.computer/latest}"

# Detect OS
case "$(uname -s)" in
    Darwin) os="darwin" ;;
    Linux)  os="linux" ;;
    *)
        echo "Error: Unsupported operating system: $(uname -s)" >&2
        echo "Ample supports macOS and Linux. Windows users: download ample-windows-amd64.exe manually." >&2
        exit 1
        ;;
esac

# Detect architecture
case "$(uname -m)" in
    x86_64|amd64)   arch="amd64" ;;
    arm64|aarch64)   arch="arm64" ;;
    *)
        echo "Error: Unsupported architecture: $(uname -m)" >&2
        exit 1
        ;;
esac

binary="ample-${os}-${arch}"
url="${BASE_URL}/${binary}"

echo "Downloading ample for ${os}/${arch}..."

# Download
tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT

if command -v curl >/dev/null 2>&1; then
    curl -fsSL -o "$tmpdir/ample" "$url"
elif command -v wget >/dev/null 2>&1; then
    wget -qO "$tmpdir/ample" "$url"
else
    echo "Error: curl or wget required" >&2
    exit 1
fi

chmod +x "$tmpdir/ample"

# Install
if [ "$(id -u)" = "0" ]; then
    install_dir="/usr/local/bin"
else
    install_dir="$HOME/.local/bin"
    mkdir -p "$install_dir"
fi

mv "$tmpdir/ample" "$install_dir/ample"

echo ""
echo "Installed ample to $install_dir/ample"

# Check PATH
case ":$PATH:" in
    *":$install_dir:"*) ;;
    *)
        echo ""
        echo "Add to your PATH:"
        echo "  export PATH=\"$install_dir:\$PATH\""
        echo ""
        echo "Or add that line to your ~/.bashrc or ~/.zshrc"
        ;;
esac

echo ""
echo "Ample is ready. To update later, run: ample update"
