#!/usr/bin/env sh
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#

case "$1" in
	--inspect*) INSPECT="$1"; shift;;
esac

ROOT="$(dirname "$(dirname "$(readlink -f "$0")")")"

# Set rpath before changing the interpreter path
# Refs https://github.com/NixOS/patchelf/issues/524
if [ -n "$VSCODE_SERVER_CUSTOM_GLIBC_LINKER" ] && [ -n "$VSCODE_SERVER_CUSTOM_GLIBC_PATH" ] && [ -n "$VSCODE_SERVER_PATCHELF_PATH" ]; then
	echo "Patching glibc from $VSCODE_SERVER_CUSTOM_GLIBC_PATH with $VSCODE_SERVER_PATCHELF_PATH..."
	"$VSCODE_SERVER_PATCHELF_PATH" --set-rpath "$VSCODE_SERVER_CUSTOM_GLIBC_PATH" "$ROOT/node"
	echo "Patching linker from $VSCODE_SERVER_CUSTOM_GLIBC_LINKER with $VSCODE_SERVER_PATCHELF_PATH..."
	"$VSCODE_SERVER_PATCHELF_PATH" --set-interpreter "$VSCODE_SERVER_CUSTOM_GLIBC_LINKER" "$ROOT/node"
	echo "Patching complete."

	# Also patch native Node modules (.node files) that require newer GLIBC
	# Native modules are shared libraries, so we only set rpath (not interpreter)
	echo "Patching native modules..."
	if [ -d "$ROOT/node_modules" ]; then
		native_module_count=0
		find "$ROOT/node_modules" -name "*.node" -type f 2>/dev/null | while read -r native_module; do
			# Check if the module links against GLIBC before patching
			if ldd "$native_module" 2>/dev/null | grep -q "libc.so"; then
				# First, try to patch the rpath
				if "$VSCODE_SERVER_PATCHELF_PATH" --set-rpath "$VSCODE_SERVER_CUSTOM_GLIBC_PATH" "$native_module" 2>/dev/null; then
					echo "  Patched rpath: $native_module"
					native_module_count=$((native_module_count + 1))
				else
					echo "  Warning: Failed to patch $native_module"
				fi
			fi
		done
		if [ "$native_module_count" -gt 0 ]; then
			echo "Patched $native_module_count native modules."
		else
			echo "No native modules found to patch."
		fi
	fi
fi

"$ROOT/node" ${INSPECT:-} "$ROOT/out/server-main.js" "$@"
