#!/usr/bin/env bash

# Exit on error, treat unset variables as errors, and propagate pipeline failures
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"
WORKSPACE_FOLDER="${SCRIPT_DIR}"

# Get the relative path from the project root to the current directory
RELATIVE_PATH="$(realpath --relative-to="${SCRIPT_DIR}" "$(pwd)")"

# Check if the 'devcontainer-info' command is available in the PATH.
# This command is typically injected into the dev container environment.
if command -v devcontainer-info >/dev/null 2>&1; then
    echo "[Inside Container] 'devcontainer-info' command found. Executing command directly: $@"
    exec "$@"
elif command -v devcontainer >/dev/null 2>&1; then
    echo "[Outside Container] Ensuring devcontainer for '${WORKSPACE_FOLDER}' is running..."

    # Ensure the container is up and running (idempotent)
    if ! ( devcontainer up --workspace-folder "${WORKSPACE_FOLDER}" && devcontainer exec --workspace-folder "${WORKSPACE_FOLDER}" -- true >/dev/null 2>&1 ); then
        echo "[Outside Container] Container test failed. Rebuilding container with --remove-existing-container..."
        devcontainer up --workspace-folder "${WORKSPACE_FOLDER}" --remove-existing-container
    fi

    echo "[Outside Container] Executing command via 'devcontainer exec': $@"
    echo "[Outside Container] Working directory: ${RELATIVE_PATH}"

    QUOTED_COMMAND=$(printf '%q ' "$@")
    devcontainer exec --workspace-folder "${WORKSPACE_FOLDER}" -- bash -c "cd \"${RELATIVE_PATH}\" && ${QUOTED_COMMAND}"
else
    echo "[Warning] DevContainer CLI not found. Running command directly in current environment."
    exec "$@"
fi

exit 0
