#!/usr/bin/env bash
# Universal installation script for rust-cache
# This script can be downloaded and run directly:
#   curl -fsSL https://raw.githubusercontent.com/SiamInnovator/rust-cache/main/install-universal.sh | bash
#   OR
#   wget -qO- https://raw.githubusercontent.com/SiamInnovator/rust-cache/main/install-universal.sh | bash

set -euo pipefail

REPO_URL="${RUST_CACHE_REPO:-https://github.com/SiamInnovator/rust-cache}"
VERSION="${RUST_CACHE_VERSION:-latest}"
INSTALL_DIR="${RUST_CACHE_INSTALL_DIR:-$HOME/.local/bin}"

echo "Installing rust-cache..."

# Detect OS and architecture
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH="$(uname -m)"

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

# Check if Rust is installed
if ! command -v cargo &> /dev/null; then
    echo "Rust is not installed. Installing Rust..."
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
    source "$HOME/.cargo/env"
fi

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

cd "$TMP_DIR"

# Clone or download
if [ "$VERSION" = "latest" ]; then
    echo "Cloning repository..."
    git clone --depth 1 "$REPO_URL" rust-cache || {
        echo "Error: Could not clone repository. Make sure git is installed."
        exit 1
    }
    cd rust-cache
else
    echo "Downloading version $VERSION..."
    git clone --depth 1 --branch "$VERSION" "$REPO_URL" rust-cache || {
        echo "Error: Could not clone repository. Make sure git is installed."
        exit 1
    }
    cd rust-cache
fi

# Build
echo "Building rust-cache..."
cargo build --release

# Install
mkdir -p "$INSTALL_DIR"
cp target/release/rust-cache "$INSTALL_DIR/"
cp target/release/rust-cache-cli "$INSTALL_DIR/"
chmod +x "$INSTALL_DIR/rust-cache" "$INSTALL_DIR/rust-cache-cli"

# Install config and service (if sudo available)
if sudo -n true 2>/dev/null || [ -w /etc ]; then
    echo "Installing system config..."
    sudo mkdir -p /etc/rust-cache
    sudo cp rust-cache.toml /etc/rust-cache/rust-cache.conf 2>/dev/null || true
    
    echo "Installing systemd service..."
    sudo cp rust-cache.service.example /etc/systemd/system/rust-cache.service 2>/dev/null || true
    sudo systemctl daemon-reload 2>/dev/null || true
fi

echo ""
echo "✓ rust-cache installed successfully!"
echo ""
echo "Binaries installed to: $INSTALL_DIR"
echo ""
if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then
    echo "Add to PATH:"
    echo "  export PATH=\"$INSTALL_DIR:\$PATH\""
    echo "  # Add to ~/.bashrc or ~/.zshrc for persistence"
    echo ""
fi
echo "Usage:"
echo "  rust-cache          # Start server"
echo "  rust-cache-cli      # Start CLI client"
echo ""
echo "To enable as systemd service:"
echo "  sudo systemctl enable rust-cache"
echo "  sudo systemctl start rust-cache"

