#!/usr/bin/env bash
# smolvm - OCI-native microVM runtime
# This wrapper sets up the library path and runs the smolvm binary.

set -e

# Resolve symlinks to get the actual script location. Every `$(...)` forks a
# subshell, and this runs before every smolvm command, so the result goes in
# RESOLVED rather than through command substitution, and directories are taken
# with parameter expansion: only `readlink` runs, once per symlink hop.
resolve_symlink() {
    local target="$1"
    # If target is a relative path or bare command from PATH, resolve it to an absolute path first
    if [[ "$target" != /* ]]; then
        if [[ "$target" == */* ]]; then
            target="$PWD/$target"
        else
            local found
            found="$(command -v "$target" 2>/dev/null || type -P "$target" 2>/dev/null || true)"
            if [[ -n "$found" && -e "$found" ]]; then
                target="$found"
            else
                target="$PWD/$target"
            fi
        fi
    fi

    while [[ -L "$target" ]]; do
        local link_dir="${target%/*}"
        target="$(readlink "$target")"
        # Handle relative symlinks
        if [[ "$target" != /* ]]; then
            target="$link_dir/$target"
        fi
    done
    RESOLVED="$target"
}

# Get the directory where the actual script lives (resolving symlinks)
resolve_symlink "${BASH_SOURCE[0]}"
SCRIPT_PATH="$RESOLVED"
SCRIPT_DIR="${SCRIPT_PATH%/*}"

# The actual binary and libraries are in the same directory
SMOLVM_BIN=/usr/lib/smolvm/smolvm-bin
SMOLVM_LIB=/usr/lib/smolvm/lib
SMOLVM_BUNDLED_ROOTFS=/usr/lib/smolvm/agent-rootfs

if [[ -d "$SMOLVM_BUNDLED_ROOTFS" ]]; then
    export SMOLVM_AGENT_ROOTFS="${SMOLVM_AGENT_ROOTFS:-$SMOLVM_BUNDLED_ROOTFS}"
fi

# Check if binary exists
if [[ ! -x "$SMOLVM_BIN" ]]; then
    echo "Error: smolvm binary not found at $SMOLVM_BIN" >&2
    echo "Make sure you extracted the full distribution." >&2
    exit 1
fi

# Check if libraries exist
if [[ ! -d "$SMOLVM_LIB" ]]; then
    echo "Error: library directory not found at $SMOLVM_LIB" >&2
    echo "Make sure you extracted the full distribution." >&2
    exit 1
fi

# Set library path based on OS and run
if [[ "$OSTYPE" == darwin* ]]; then
    export DYLD_LIBRARY_PATH="$SMOLVM_LIB${DYLD_LIBRARY_PATH:+:$DYLD_LIBRARY_PATH}"
else
    export LD_LIBRARY_PATH="$SMOLVM_LIB${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
fi
exec "$SMOLVM_BIN" "$@"
