#!/usr/bin/env bash

# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

# Get path of the myst-gdb script
# See https://mywiki.wooledge.org/BashFAQ/028 for complexities involved
# in determining location of a bash script. ${BASH_SOURCE}, though not perfect,
# is an acceptable solution for myst-gdb.
# readlink provides additional benefit in getting the absolute path
# to the script directory for systems where BASH_SOURCE is only relative.
MYST_GDB_DIR=$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")

# Get the path to the dependent debugger libraries from OpenEnclave relative to
# the myst-gdb path. Normalize the path by cd-ing and doing a pwd -P.
OE_GDB_LIB_DIR=$(cd "$MYST_GDB_DIR/../lib/openenclave/debugger" || exit; pwd -P)

# Also get the path to the debugger libraries relative to the myst-gdb path.
MYST_GDB_LIB_DIR=$(cd "$MYST_GDB_DIR/../lib/debugger" || exit; pwd -P)

OE_GDB_PLUGIN_DIR=$OE_GDB_LIB_DIR/gdb-sgx-plugin
OE_GDB_PTRACE_PATH=$OE_GDB_LIB_DIR/liboe_ptrace.so

MYST_GDB_PLUGIN_DIR=${MYST_GDB_LIB_DIR}/gdb-sgx-plugin

export PYTHONPATH=$OE_GDB_PLUGIN_DIR:$MYST_GDB_PLUGIN_DIR
LD_PRELOAD=$OE_GDB_PTRACE_PATH gdb \
	  -iex "directory $OE_GDB_PLUGIN_DIR" \
	  -iex "directory $MYST_GDB_PLUGIN_DIR" \
	  -iex "source $OE_GDB_PLUGIN_DIR/gdb_sgx_plugin.py" \
	  -iex "source $MYST_GDB_PLUGIN_DIR/print.py" \
	  -iex "source $MYST_GDB_PLUGIN_DIR/mprotect.py" \
	  -iex "source $MYST_GDB_PLUGIN_DIR/symbol_analyzer.py" \
	  -iex "set environment LD_PRELOAD" \
	  -iex "add-auto-load-safe-path /usr/lib" \
	  "$@"
