#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Load shared runtime selector
source "$ROOT_DIR/select-runtime.env"

# Determine tool name
INVOKED_AS="$(basename "$0")"

if [[ "$INVOKED_AS" == "appimage-tool" ]]; then
    if [[ $# -lt 1 ]]; then
        echo "Usage:"
        echo "  appimage-tool <tool-name> [args...]"
        exit 1
    fi
    TOOL_NAME="$1"
    shift
else
    TOOL_NAME="$INVOKED_AS"
fi

BIN="$APPIMAGE_TOOLS_DIR/$TOOL_NAME"

if [[ ! -x "$BIN" ]]; then
    echo "Tool not found or not executable:"
    echo "   $BIN"
    echo
    echo "Available tools:"
    ls -1 "$APPIMAGE_TOOLS_DIR" 2>/dev/null || true
    exit 1
fi

# Debug mode
if [[ "${1:-}" == "--debug" || "${1:-}" == "-d" ]]; then
    echo "=== AppImage Tool Debug Info ==="
    echo "Tool name:        $TOOL_NAME"
    echo "Binary path:      $BIN"
    echo "Platform:         $APPIMAGE_TOOLS_PLATFORM"
    echo "Architecture:     $APPIMAGE_TOOLS_ARCH"
    echo "Runtime dir:      $APPIMAGE_TOOLS_DIR"
    echo "Library dir:      $APPIMAGE_TOOLS_LIBDIR"
    if [[ "$APPIMAGE_TOOLS_PLATFORM" == "darwin" ]]; then
        echo "DYLD_LIBRARY_PATH: $DYLD_LIBRARY_PATH"
    else
        echo "LD_LIBRARY_PATH:   $LD_LIBRARY_PATH"
    fi
    echo "Executable file info:"
    file "$BIN"
    echo "Dynamic libs:"
    if [[ "$APPIMAGE_TOOLS_PLATFORM" == "darwin" ]]; then
        otool -L "$BIN" || true
    else
        ldd "$BIN" || true
    fi
    exit 0
fi

# macOS: remove quarantine attribute if present
if [[ "$APPIMAGE_TOOLS_PLATFORM" == "darwin" ]]; then
    if command -v xattr >/dev/null 2>&1; then
        xattr -dr com.apple.quarantine "$APPIMAGE_TOOLS_DIR" 2>/dev/null || true
    fi
fi

# Execute normally
exec "$BIN" "$@"
