#!/bin/sh
# Web Performance Load Engine startup script

# Set the application home directory
APP_HOME=`dirname "$0"`
APP_HOME=`cd "$APP_HOME" && pwd`

# Detect architecture and set appropriate Java options
ARCH=`uname -m`
case $ARCH in
    x86_64|amd64)
        # 64-bit system
        JAVA_OPTS="-XX:DefaultMaxRAMFraction=2 -server -Djava.net.preferIPv4Stack=true"
        LIB_PATH="lib64"
        ;;
    i*86|x86)
        # 32-bit system
        JAVA_OPTS="-Xms200m -Xmx200m -server -Djava.net.preferIPv4Stack=true"
        LIB_PATH="lib32"
        ;;
    *)
        # Default to 64-bit settings
        JAVA_OPTS="-XX:DefaultMaxRAMFraction=2 -server -Djava.net.preferIPv4Stack=true"
        LIB_PATH="lib64"
        ;;
esac

# Set library path for native libraries
if [ -d "$APP_HOME/$LIB_PATH" ]; then
    JAVA_OPTS="$JAVA_OPTS -Djava.library.path=$APP_HOME/$LIB_PATH"
elif [ -d "$APP_HOME/lib" ]; then
    JAVA_OPTS="$JAVA_OPTS -Djava.library.path=$APP_HOME/lib"
fi

# Use bundled JRE if available, otherwise use system Java
if [ -x "$APP_HOME/jre/bin/java" ]; then
    JAVA_CMD="$APP_HOME/jre/bin/java"
else
    JAVA_CMD="java"
fi

# Detect if running on EC2 and set RMI hostname to public IP
# This is critical for Load Tester to connect from outside the VPC
# Amazon Linux 2023 uses IMDSv2 which requires a token
TOKEN=$(curl -s -X PUT -m 2 "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" 2>/dev/null)
if [ -n "$TOKEN" ]; then
    PUBLIC_IP=$(curl -s -m 2 -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/public-ipv4 2>/dev/null)
    if [ -n "$PUBLIC_IP" ] && echo "$PUBLIC_IP" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$'; then
        echo "Detected EC2 environment, setting RMI hostname to public IP: $PUBLIC_IP"
        JAVA_OPTS="$JAVA_OPTS -Djava.rmi.server.hostname=$PUBLIC_IP"
    else
        # Token obtained but no valid public IP (might be private instance)
        HOSTNAME=$(hostname -f 2>/dev/null || hostname)
        echo "EC2 instance without public IP, setting RMI hostname to: $HOSTNAME"
        JAVA_OPTS="$JAVA_OPTS -Djava.rmi.server.hostname=$HOSTNAME"
    fi
else
    # Not on EC2, use system hostname
    HOSTNAME=$(hostname -f 2>/dev/null || hostname)
    echo "Setting RMI hostname to: $HOSTNAME"
    JAVA_OPTS="$JAVA_OPTS -Djava.rmi.server.hostname=$HOSTNAME"
fi

# Start the Load Engine with full classpath for thin JAR
cd "$APP_HOME"
exec "$JAVA_CMD" $JAVA_OPTS -cp "LoadEngine.jar:com.webperformanceinc.util/com.webperformanceinc.util.jar:lib/*:lib/selenium/*" com.webperfcenter.trainer.server.RemotePlaybackEngine "$@"