#!/usr/bin/env bash

#----------------------------------------
# PyGhidra launch
#----------------------------------------

# Optionally override the default Java heap memory, which is typically 1/4 of system RAM.
# Supported values are of the regular expression form "\d+[gGmMkK]", allowing the value to be
# specified in gigabytes, megabytes, or kilobytes (for example: 8G, 4096m, etc).
MAXMEM_DEFAULT=

# Allow the above MAXMEM_DEFAULT to be overridden by externally set environment variables
# - GHIDRA_MAXMEM: Desired maximum heap memory for all Ghidra instances
# - GHIDRA_GUI_MAXMEM: Desired maximum heap memory only for Ghidra GUI instances
# - GHIDRA_HEADLESS_MAXMEM: Desired maximum heap memory only for headless Ghidra instances
GHIDRA_MAXMEM=${GHIDRA_MAXMEM:=${MAXMEM_DEFAULT}}
GHIDRA_GUI_MAXMEM=${GHIDRA_GUI_MAXMEM:=${GHIDRA_MAXMEM}}
GHIDRA_HEADLESS_MAXMEM=${GHIDRA_HEADLESS_MAXMEM:=${GHIDRA_MAXMEM}}

# Use the headless maximum heap memory if launching in headless mode
MAXMEM="${GHIDRA_GUI_MAXMEM}"
for ARG in "$@"; do
	if [ "${ARG}" = "-H" ] || [ "${ARG}" = "--headless" ]; then
		MAXMEM="${GHIDRA_HEADLESS_MAXMEM}"
		break
	fi
done

# Resolve symbolic link if present and get the directory this script lives in.
# NOTE: "readlink -f" is best but works on Linux only, "readlink" will only work if your PWD
# contains the link you are calling (which is the best we can do on macOS), and the "echo" is the 
# fallback, which doesn't attempt to do anything with links.
SCRIPT_FILE="$(readlink -f "$0" 2>/dev/null || readlink "$0" 2>/dev/null || echo "$0")"
SCRIPT_DIR="$(dirname -- "$SCRIPT_FILE")"
# Since JPype doesn't seem to pick up JDK_JAVA_OPTIONS automatically, include it ourselves
VMARG_LIST="${JDK_JAVA_OPTIONS}"

# Apply the maximum heap memory, if specified
if [ -n "${MAXMEM}" ]; then
	VMARG_LIST="${VMARG_LIST} -Xmx${MAXMEM}"
fi

# Apply Java options from externally set environment variables
VMARG_LIST="${VMARG_LIST} ${GHIDRA_JAVA_OPTIONS} ${PYGHIDRA_JAVA_OPTIONS}"

# Make sure Python3 is installed
if ! [ -x "$(command -v python3)" ] ; then
	echo "Python 3 is not installed."
	exit 1
fi

# Dev mode or production mode?
DEV_ARG=
INSTALL_DIR="${SCRIPT_DIR}/.."
if [ ! -d "${INSTALL_DIR}/Ghidra" ]; then
	DEV_ARG="--dev"
	INSTALL_DIR="${SCRIPT_DIR}/../../.."
fi

PYGHIDRA_LAUNCHER="${INSTALL_DIR}/Ghidra/Features/PyGhidra/support/pyghidra_launcher.py"

python3 "${PYGHIDRA_LAUNCHER}" "${INSTALL_DIR}" ${DEV_ARG} ${VMARG_LIST} "$@"
