#!/bin/bash

# Download ripgrep for ARM64 Linux (works on Termux)
# This script downloads and extracts the ripgrep binary

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
BINARIES_DIR="$PROJECT_DIR/src/binaries"

# Ripgrep version and URL
RG_VERSION="14.1.1"
RG_URL="https://github.com/BurntSushi/ripgrep/releases/download/${RG_VERSION}/ripgrep-${RG_VERSION}-aarch64-unknown-linux-gnu.tar.gz"

echo "Downloading ripgrep v${RG_VERSION} for ARM64..."

# Create binaries directory
mkdir -p "$BINARIES_DIR"

# Create temp directory
TMP_DIR=$(mktemp -d)
trap "rm -rf $TMP_DIR" EXIT

# Download
curl -sL "$RG_URL" -o "$TMP_DIR/ripgrep.tar.gz"

# Extract
tar -xzf "$TMP_DIR/ripgrep.tar.gz" -C "$TMP_DIR"

# Find and copy the binary
RG_BINARY=$(find "$TMP_DIR" -name "rg" -type f | head -1)

if [[ -z "$RG_BINARY" ]]; then
    echo "Error: ripgrep binary not found in archive"
    exit 1
fi

cp "$RG_BINARY" "$BINARIES_DIR/rg"
chmod +x "$BINARIES_DIR/rg"

echo "Ripgrep binary saved to: $BINARIES_DIR/rg"
echo ""

# Verify
if [[ -x "$BINARIES_DIR/rg" ]]; then
    echo "Verification:"
    file "$BINARIES_DIR/rg"
    ls -la "$BINARIES_DIR/rg"
    echo ""
    echo "Success! Ripgrep binary is ready."
else
    echo "Error: Binary verification failed"
    exit 1
fi
