#!/bin/bash

# Check if the required arguments are provided
if [ -z "$1" ] || [ -z "$2" ]; then
	echo "Error: Missing arguments."
	echo "Usage: $0 <ruby_file> <ruby_env_path> [mode]"
	exit 1
fi

RUBY_FILE=$1
RUBY_ENV_PATH=$2
MODE=${3:-production}

# Set environment variables for RVM dynamically based on provided path
export GEM_HOME="$RUBY_ENV_PATH/gems/ruby-3.0.0"
export GEM_PATH="$RUBY_ENV_PATH/gems/ruby-3.0.0:$RUBY_ENV_PATH/gems/ruby-3.0.0@global"
export PATH="$RUBY_ENV_PATH/gems/ruby-3.0.0/bin:$RUBY_ENV_PATH/gems/ruby-3.0.0@global/bin:$RUBY_ENV_PATH/rubies/ruby-3.0.0/bin:$PATH"

# Log file path
logfile='/tmp/ruby_wrapper_log.txt'

# Create log file and write messages only in test mode
if [ "$MODE" = "test" ]; then
	{
		echo "Wrapper script started"
		echo "Mode: $MODE"
		echo "GEM_HOME: $GEM_HOME"
		echo "GEM_PATH: $GEM_PATH"
		echo "PATH: $PATH"
		echo "Executing user: $(whoami)"
		echo "Effective user ID: $(id -u)"
		echo "Effective group ID: $(id -g)"
		echo "Effective user name: $(id -un)"
		echo "Effective group name: $(id -gn)"
		echo "Home directory: $HOME"
	} >>$logfile
fi

# Execute the provided Ruby script based on mode
if [ "$MODE" = "test" ]; then
	echo "Running in test mode" >>$logfile
	"$RUBY_ENV_PATH/rubies/ruby-3.0.0/bin/ruby" "$RUBY_FILE" --test >>$logfile 2>&1
else
	echo "Running in production mode" >>$logfile
	"$RUBY_ENV_PATH/rubies/ruby-3.0.0/bin/ruby" "$RUBY_FILE"
fi

# Log script completion only in test mode
if [ "$MODE" = "test" ]; then
	echo "Wrapper script completed" >>$logfile
fi

# Exit
exit 0
