#!/bin/bash
# RyuSim installer
# Usage: curl -fsSL https://ryusim.seiraiyu.com/install.sh | bash
set -euo pipefail

VERSION="${RYUSIM_VERSION:-latest}"
ARCH="$(uname -m)"
BASE_URL="${RYUSIM_DOWNLOAD_URL:-https://ryusim.seiraiyu.com/releases}"

# Detect system glibc version
SYSTEM_GLIBC="$(ldd --version 2>&1 | head -1 | grep -oP '\d+\.\d+$' || true)"
if [ -z "$SYSTEM_GLIBC" ]; then
    echo "ERROR: Could not detect glibc version"
    exit 1
fi

# Determine install prefix
if [ "$(id -u)" -eq 0 ]; then
    PREFIX="/opt/ryusim"
else
    PREFIX="${HOME}/.local"
    echo "Installing to ${PREFIX} (run with sudo for /opt/ryusim)"
fi

echo "=== RyuSim Installer ==="
echo "Version:  ${VERSION}"
echo "Arch:     ${ARCH}"
echo "Glibc:    ${SYSTEM_GLIBC}"
echo "Prefix:   ${PREFIX}"
echo ""

# Fetch directory listing and find compatible tarballs
echo "Checking available builds..."
LISTING="$(curl -fsSL "${BASE_URL}/" 2>/dev/null || true)"
if [ -z "$LISTING" ]; then
    echo "ERROR: Could not fetch release listing from ${BASE_URL}/"
    exit 1
fi

# Extract tarball filenames matching version and arch
# Pattern: ryusim-{VERSION}-linux-{ARCH}-glibc{X.Y}.tar.gz
if [ "$VERSION" = "latest" ]; then
    VERSION_PATTERN="[0-9]+\.[0-9]+\.[0-9]+"
else
    # Escape dots for regex
    VERSION_PATTERN="$(echo "$VERSION" | sed 's/\./\\./g')"
fi

CANDIDATES=$(echo "$LISTING" | grep -oP "ryusim-${VERSION_PATTERN}-linux-${ARCH}-glibc\d+\.\d+\.tar\.gz" | sort -u || true)

if [ -z "$CANDIDATES" ]; then
    echo "ERROR: No builds found for linux-${ARCH} (version: ${VERSION})"
    echo ""
    echo "Available files at ${BASE_URL}/:"
    echo "$LISTING" | grep -oP 'ryusim-[^"<]+\.tar\.gz' | sort -u | sed 's/^/  /' || echo "  (none)"
    exit 1
fi

# Find the highest glibc build that is <= our system glibc
# Compare as integers: 2.35 -> 2035, 2.38 -> 2038
sys_major="${SYSTEM_GLIBC%%.*}"
sys_minor="${SYSTEM_GLIBC#*.}"
sys_int=$(( sys_major * 1000 + sys_minor ))

BEST_TARBALL=""
BEST_GLIBC=""
BEST_INT=0

for tarball in $CANDIDATES; do
    glibc="$(echo "$tarball" | grep -oP 'glibc\K\d+\.\d+')"
    g_major="${glibc%%.*}"
    g_minor="${glibc#*.}"
    g_int=$(( g_major * 1000 + g_minor ))

    if [ "$g_int" -le "$sys_int" ] && [ "$g_int" -gt "$BEST_INT" ]; then
        BEST_TARBALL="$tarball"
        BEST_GLIBC="$glibc"
        BEST_INT="$g_int"
    fi
done

if [ -z "$BEST_TARBALL" ]; then
    # Show what's available and what they require
    echo "ERROR: No compatible build for glibc ${SYSTEM_GLIBC}"
    echo ""
    echo "Available builds require:"
    for tarball in $CANDIDATES; do
        glibc="$(echo "$tarball" | grep -oP 'glibc\K\d+\.\d+')"
        echo "  ${tarball}  (requires glibc >= ${glibc})"
    done
    echo ""
    echo "Your system has glibc ${SYSTEM_GLIBC}. You need a newer OS or a build targeting an older glibc."
    exit 1
fi

echo "Selected: ${BEST_TARBALL} (requires glibc >= ${BEST_GLIBC})"
echo ""

DOWNLOAD_URL="${BASE_URL}/${BEST_TARBALL}"

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

echo "Downloading ${DOWNLOAD_URL}..."
if command -v curl &>/dev/null; then
    curl -fsSL -o "${TMPDIR}/${BEST_TARBALL}" "${DOWNLOAD_URL}"
elif command -v wget &>/dev/null; then
    wget -q -O "${TMPDIR}/${BEST_TARBALL}" "${DOWNLOAD_URL}"
else
    echo "ERROR: curl or wget required"
    exit 1
fi

# Extract
echo "Extracting..."
tar -xzf "${TMPDIR}/${BEST_TARBALL}" -C "${TMPDIR}"

# Install
EXTRACTED_DIR=$(find "${TMPDIR}" -maxdepth 1 -type d -name "ryusim-*" | head -1)
mkdir -p "${PREFIX}/bin" "${PREFIX}/lib/ryusim"

# Put the real binary in lib, not bin
cp "${EXTRACTED_DIR}/bin/ryusim" "${PREFIX}/lib/ryusim/ryusim-bin"
cp "${EXTRACTED_DIR}/lib/"* "${PREFIX}/lib/ryusim/" 2>/dev/null || true

# Create "ryusim" wrapper that sets library path and execs the real binary
cat > "${PREFIX}/bin/ryusim" << WRAPPER
#!/bin/bash
export LD_LIBRARY_PATH="${PREFIX}/lib/ryusim\${LD_LIBRARY_PATH:+:\$LD_LIBRARY_PATH}"
exec "${PREFIX}/lib/ryusim/ryusim-bin" "\$@"
WRAPPER
chmod +x "${PREFIX}/bin/ryusim"

# Verify the binary can actually run on this system
echo ""
if "${PREFIX}/bin/ryusim" --version >/dev/null 2>&1; then
    echo "=== RyuSim installed ==="
    echo "Binary: ${PREFIX}/bin/ryusim"

    # Check PATH
    if ! echo "$PATH" | tr ':' '\n' | grep -q "^${PREFIX}/bin$"; then
        echo ""
        echo "Add to your PATH:"
        echo "  export PATH=\"${PREFIX}/bin:\$PATH\""
    fi

    echo ""
    echo "Verify: ryusim --version"
else
    echo "=== RyuSim installed but CANNOT RUN on this system ==="
    echo ""
    "${PREFIX}/bin/ryusim" --version 2>&1 || true
    echo ""
    echo "The binary was installed but failed to execute. This may indicate"
    echo "missing system libraries beyond glibc."
    exit 1
fi
