#!/bin/bash
# ============================================================================
# MaxUserBenchmarkTest - Linux/Mac Launcher
# ============================================================================
# This script sets up the environment and launches the database benchmark test
# using the bundled Java runtime and JMeter installation.
#
# Configuration is read from config/appsettings.json
#
# Usage:
#   ./run.sh [config_name] [config_file]
#
# Parameters:
#   config_name    Name of the database configuration from the JSON file (e.g., "oracle", "postgres", "oracle-qa")
#                  If not provided and only one config exists, uses that automatically.
#                  If multiple configs exist, prompts user to select.
#   config_file    Optional path to custom config file (defaults to config/appsettings.json)
#
# Examples:
#   ./run.sh                                    # Auto-select if only one config, or prompt if multiple
#   ./run.sh oracle                             # Use specific config
#   ./run.sh postgres-dev
#   ./run.sh oracle-qa config/my-custom-config.json
# ============================================================================

# Parse arguments
CONFIG_NAME="$1"
CONFIG_FILE="${2:-config/appsettings.json}"

echo ""
echo "============================================================================"
echo "MaxUserBenchmarkTest - Database Benchmark Tool"
echo "============================================================================"
echo ""

# Get the directory where this script is located
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# Resolve config file path
if [[ "$CONFIG_FILE" = /* ]]; then
    CONFIG_PATH="$CONFIG_FILE"
else
    CONFIG_PATH="$SCRIPT_DIR/$CONFIG_FILE"
fi

# Check if config file exists
if [ ! -f "$CONFIG_PATH" ]; then
    echo "ERROR: Configuration file not found at $CONFIG_PATH"
    echo "Please create a config file or use the sample: config/appsettings.json"
    echo ""
    exit 1
fi

echo "Loading configuration from: $CONFIG_PATH"

# Check if jq is available for JSON parsing
if ! command -v jq &> /dev/null; then
    echo "ERROR: jq is not installed. jq is required for parsing JSON configuration."
    echo "Please install jq:"
    echo "  - macOS: brew install jq"
    echo "  - Ubuntu/Debian: sudo apt-get install jq"
    echo "  - CentOS/RHEL: sudo yum install jq"
    echo ""
    exit 1
fi

# Get available configurations
AVAILABLE_CONFIGS=($(jq -r '.databases | keys[]' "$CONFIG_PATH"))

# Check if any configurations exist
if [ ${#AVAILABLE_CONFIGS[@]} -eq 0 ]; then
    echo "ERROR: No database configurations found in $CONFIG_PATH"
    echo "Please add at least one database configuration to the 'databases' section."
    echo ""
    exit 1
fi

# Determine which config to use
if [ -z "$CONFIG_NAME" ]; then
    if [ ${#AVAILABLE_CONFIGS[@]} -eq 1 ]; then
        # Auto-select the only available config
        CONFIG_NAME="${AVAILABLE_CONFIGS[0]}"
        echo "Auto-selected configuration: $CONFIG_NAME (only one available)"
        echo ""
    else
        # Multiple configs available - prompt user
        echo "Multiple database configurations available:"
        for i in "${!AVAILABLE_CONFIGS[@]}"; do
            echo "  [$((i + 1))] ${AVAILABLE_CONFIGS[$i]}"
        done
        echo ""
        
        while true; do
            read -p "Select a configuration (1-${#AVAILABLE_CONFIGS[@]}) or press Ctrl+C to cancel: " selection
            
            if [[ "$selection" =~ ^[0-9]+$ ]] && [ "$selection" -ge 1 ] && [ "$selection" -le ${#AVAILABLE_CONFIGS[@]} ]; then
                CONFIG_NAME="${AVAILABLE_CONFIGS[$((selection - 1))]}"
                break
            else
                echo "Invalid selection. Please enter a number between 1 and ${#AVAILABLE_CONFIGS[@]}."
            fi
        done
        echo ""
    fi
fi

# Parse configuration
DB_TYPE=$(jq -r ".databases.\"$CONFIG_NAME\".type // empty" "$CONFIG_PATH")
DB_URL=$(jq -r ".databases.\"$CONFIG_NAME\".url // empty" "$CONFIG_PATH")
DB_USER=$(jq -r ".databases.\"$CONFIG_NAME\".username // empty" "$CONFIG_PATH")
DB_PASS=$(jq -r ".databases.\"$CONFIG_NAME\".password // empty" "$CONFIG_PATH")

# Check if configuration exists
if [ -z "$DB_TYPE" ]; then
    echo "ERROR: Configuration '$CONFIG_NAME' not found in $CONFIG_PATH"
    echo "Available configurations:"
    printf '%s\n' "${AVAILABLE_CONFIGS[@]}" | sed 's/^/  - /'
    echo ""
    exit 1
fi

echo "Using database configuration: $CONFIG_NAME"
echo "  Type: $DB_TYPE"
echo "  URL: $DB_URL"
echo "  User: $DB_USER"
echo ""

# Set JAVA_HOME to the bundled JRE
export JAVA_HOME="$SCRIPT_DIR/jre"
export PATH="$JAVA_HOME/bin:$PATH"

# Verify Java is available
if [ ! -f "$JAVA_HOME/bin/java" ]; then
    echo "ERROR: Java runtime not found at $JAVA_HOME"
    echo "Please ensure the jre folder exists in the installation directory."
    echo ""
    exit 1
fi

# Display Java version
echo "Using bundled Java:"
"$JAVA_HOME/bin/java" -version 2>&1 | grep "version"
echo ""

# Verify JMeter exists
if [ ! -f "$SCRIPT_DIR/jmeter/bin/jmeter" ]; then
    echo "ERROR: JMeter not found at $SCRIPT_DIR/jmeter"
    echo "Please ensure the jmeter folder exists in the installation directory."
    echo ""
    exit 1
fi

# Verify test scripts exist
if [ ! -f "$SCRIPT_DIR/test/benchmark_test.ps1" ]; then
    echo "ERROR: Test scripts not found at $SCRIPT_DIR/test"
    echo "Please ensure the test folder exists in the installation directory."
    echo ""
    exit 1
fi

# Check if PowerShell is available
if ! command -v pwsh &> /dev/null; then
    echo "ERROR: PowerShell (pwsh) is not installed."
    echo "Please install PowerShell Core from: https://github.com/PowerShell/PowerShell"
    echo ""
    exit 1
fi

# Change to test directory
cd "$SCRIPT_DIR/test"

# Run the PowerShell benchmark script with configuration parameters
echo "Starting benchmark test..."
echo ""
pwsh -File "benchmark_test.ps1" -Database "$DB_TYPE" -DbUser "$DB_USER" -DbPass "$DB_PASS" -DbUrl "$DB_URL"

# Capture exit code
EXIT_CODE=$?

echo ""
echo "============================================================================"
echo "Test completed with exit code: $EXIT_CODE"
echo "============================================================================"
echo ""
exit $EXIT_CODE