#!/bin/sh

# SPDX-License-Identifier: Apache-2.0
# Copyright (C) 2019-2021 Xilinx, Inc. All rights reserved.
#

# Working Variables 
XRT_EXEC=""
XRT_LOADER_ARGS=""

# -- Examine the options 
while [ $# -gt 0 ]; do
  case "$1" in
    # Get the executable program name
    -exec|--exec)
      shift
      XRT_EXEC="$1"
      shift
      ;;
    # Collect remaining arguments
    *)
      XRT_LOADER_ARGS="$XRT_LOADER_ARGS \"$1\""
      shift
      ;;
  esac
done

# -- Check to see if the given executable exists
if [ -z "${XRT_EXEC}" ]; then
  echo "ERROR: The -exec option wasn't specified."
  exit 1
fi

XRT_PROG_UNWRAPPED="`dirname \"$0\"`/${XRT_EXEC}"
if [ ! -f "${XRT_PROG_UNWRAPPED}" ]; then
  echo "ERROR: Could not find -exec program: ${XRT_EXEC}"
  echo "ERROR: ${XRT_PROG_UNWRAPPED} does not exist"
  exit 1
fi

# -- Find the setup script and configure environment
XRT_SETUP_SCRIPT="`dirname \"$0\"`/../../setup.sh"

if [ ! -f "$XRT_SETUP_SCRIPT" ]; then
  echo "ERROR: Could not find XRT setup script."
  echo "ERROR: ${XRT_SETUP_SCRIPT} does not exist"
  exit 1
fi

. "${XRT_SETUP_SCRIPT}" >/dev/null

case "$XILINX_XRT" in
  */bin/unwrapped)
    XILINX_XRT=$(dirname "$(dirname "$XILINX_XRT")")
    export XILINX_XRT
    ;;
esac

# Reset LD_LIBRARY_PATH to avoid Vitis/Vivado libs
LD_LIBRARY_PATH=$XILINX_XRT/lib:$(echo $LD_LIBRARY_PATH | tr ':' '\n' | grep -E -v "/(Vitis|Vivado).*/(lnx|lin)" | tr '\n' ':')

# -- Execute the wrapped program
# Use "eval" since we collected args as a string
eval "\"$XRT_PROG_UNWRAPPED\" $XRT_LOADER_ARGS"
