#!/bin/bash
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e

error_exit()
{
    echo "There was an error running python"
    exit 1
}

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# MY_DIR="$(realpath -s "$SCRIPT_DIR")"

# Setup python env from generated file (generated by tools/repoman/build.py)
export CARB_APP_PATH=$SCRIPT_DIR/kit
export ISAAC_PATH=$SCRIPT_DIR
export EXP_PATH=$SCRIPT_DIR/apps
source ${SCRIPT_DIR}/setup_python_env.sh

# By default use our python, but allow overriding it by checking if PYTHONEXE env var is defined:
python_exe=${PYTHONEXE:-"${SCRIPT_DIR}/kit/python/bin/python3"}

# Parse command line arguments to check for --lldb-debug flag
use_lldb=false
filtered_args=()

for arg in "$@"; do
    if [[ "$arg" == "--lldb-debug" ]]; then
        use_lldb=true
    else
        filtered_args+=("$arg")
    fi
done


if ! [[ -z "${CONDA_PREFIX}" ]]; then
  echo "Warning: running in conda env, please deactivate before executing this script"
  echo "If conda is desired please source setup_conda_env.sh in your python 3.11 conda env and run python normally"
fi

# Check if we are running in a docker container
if [ -f /.dockerenv ]; then
  # Check for vulkan in docker container
  if [[ -f "${SCRIPT_DIR}/vulkan_check.sh" ]]; then
    ${SCRIPT_DIR}/vulkan_check.sh
  fi
fi

# Show icon if not running headless
export RESOURCE_NAME="IsaacSim"
# WAR for missing libcarb.so
export LD_PRELOAD=$SCRIPT_DIR/kit/libcarb.so

# Run with lldb if --lldb-debug flag was specified, otherwise run normally
if [[ "$use_lldb" == true ]]; then
    lldb -o run $python_exe -- "${filtered_args[@]}" $args || error_exit
else
    $python_exe "${filtered_args[@]}" $args || error_exit
fi
