#!/bin/bash

# DQV/KTAC Agent Startup Script for Linux/MacOS
# This script checks for Java availability and starts the DQV/KTAC agent in background

# Function to log messages with timestamp
log_message() {
    local message="$1"
    local level="${2:-INFO}"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    echo "[$timestamp] [$level] $message" | tee -a logs/agent/bootstrap-cli.log
}

# Function to show error message and wait for user input
show_error_message() {
    local message="$1"
    
    log_message "ERROR: $message" "ERROR"
    echo "ERROR: $message"
    echo "Press Enter to continue..."
    read -r
    return 1
}

# Function to check Java version
check_java_version() {
    local java_version_output
    local java_version
    local major_version
    local minor_version
    
    # Get Java version
    java_version_output=$("$JAVA_CMD" -version 2>&1)
    java_version=$(echo "$java_version_output" | grep -i version | head -1 | sed 's/.*version "\([^"]*\)".*/\1/')
    
    if [ -z "$java_version" ]; then
        log_message "ERROR: Could not determine Java version" "ERROR"
        return 1
    fi
    
    log_message "Detected Java version: $java_version" "INFO"
    
    # Extract major and minor version numbers
    if [[ "$java_version" =~ ^1\.([0-9]+)\. ]]; then
        # Java 1.x format (1.8, 1.9, etc.)
        major_version=1
        minor_version="${BASH_REMATCH[1]}"
    elif [[ "$java_version" =~ ^([0-9]+)\. ]]; then
        # Java 9+ format (9, 10, 11, etc.)
        major_version="${BASH_REMATCH[1]}"
        minor_version=0
    else
        log_message "ERROR: Could not parse Java version: $java_version" "ERROR"
        return 1
    fi
    
    # Check if version is 1.8 or higher
    if [ "$major_version" -eq 1 ]; then
        if [ "$minor_version" -lt 8 ]; then
            log_message "ERROR: Java version $java_version is not supported. Please install Java 1.8 or higher." "ERROR"
            log_message "Current version $java_version is below the minimum required version 1.8" "ERROR"
            return 1
        fi
    elif [ "$major_version" -lt 9 ]; then
        log_message "ERROR: Java version $java_version is not supported. Please install Java 1.8 or higher." "ERROR"
        return 1
    fi
    
    log_message "Java version $java_version is supported - proceeding with agent startup" "INFO"
    return 0
}

# Main script execution
main() {
    # Get script directory
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    cd "$SCRIPT_DIR"
    
    # Create logs directory
    mkdir -p logs/agent
    
    log_message "Starting DQV/KTAC Agent startup process" "INFO"
    log_message "Agent directory: $SCRIPT_DIR" "INFO"
    
    # Check for local Java installation first
    JAVA_CMD=""
    if [ -x "./java/bin/java" ]; then
        JAVA_CMD="./java/bin/java"
        log_message "Found local Java installation: $JAVA_CMD" "INFO"
    else
        # Fall back to system PATH
        if command -v java >/dev/null 2>&1; then
            JAVA_CMD="java"
            log_message "Using system Java from PATH" "INFO"
        fi
    fi
    
    # Check if Java exists (either local or system)
    if [ -z "$JAVA_CMD" ]; then
        log_message "ERROR: Java is not installed or not found in PATH" "ERROR"
        log_message "Please install Java 1.8 or higher and ensure it is in your system PATH" "ERROR"
        log_message "Alternatively, place a Java installation in the 'java' folder" "ERROR"
        show_error_message "Java is not installed or not found in PATH. Please install Java 1.8 or higher."
        exit 1
    fi
    
    # Check Java version
    if ! check_java_version; then
        show_error_message "Java version check failed. Please install Java 1.8 or higher."
        exit 2
    fi
    
    # Check if bootstrap-agent.jar exists
    if [ ! -f "bootstrap-agent.jar" ]; then
        log_message "ERROR: bootstrap-agent.jar not found in current directory" "ERROR"
        show_error_message "bootstrap-agent.jar not found in current directory."
        exit 3
    fi
    
    # Kill existing agent process if running
    if [ -f "agent.pid" ]; then
        local pid=$(cat agent.pid 2>/dev/null)
        if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
            log_message "Stopping existing agent process (PID: $pid)" "INFO"
            kill -15 "$pid" 2>/dev/null
            sleep 2
            if kill -0 "$pid" 2>/dev/null; then
                log_message "Force killing agent process (PID: $pid)" "WARN"
                kill -9 "$pid" 2>/dev/null
            fi
        fi
        rm -f agent.pid
    fi
    
    # Start the agent in background
    log_message "Starting DQV/KTAC Agent with nohup" "INFO"
    log_message "Log file: logs/agent/bootstrap-cli.log" "INFO"
    log_message "Using Java: $JAVA_CMD" "INFO"
    
    # Clear Java options
    unset JAVA_TOOL_OPTIONS
    unset IBM_JAVA_OPTIONS
    unset _JAVA_OPTIONS
    unset JAVA_OPTIONS
    
    # Start agent with nohup
    nohup "$JAVA_CMD" -XX:+UseG1GC -XX:+HeapDumpOnOutOfMemoryError -jar bootstrap-agent.jar >> logs/agent/bootstrap-cli.log 2>&1 &
    local agent_pid=$!
    
    # Save PID to file
    echo "$agent_pid" > agent.pid
    
    log_message "DQV/KTAC Agent started successfully with PID: $agent_pid" "INFO"
    log_message "Agent is running in background. Check logs/agent/bootstrap-cli.log for details." "INFO"
    
    # Wait a moment and check if process is still running
    sleep 2
    if kill -0 "$agent_pid" 2>/dev/null; then
        log_message "Agent process is running successfully" "INFO"
        echo "DQV/KTAC Agent is now running with PID: $agent_pid"
        echo "Log file: logs/agent/bootstrap-cli.log"
        echo "To stop the agent, run: ./stop-agent.sh or kill $agent_pid"
        exit 0
    else
        log_message "ERROR: Agent process failed to start or crashed immediately" "ERROR"
        rm -f agent.pid
        show_error_message "Agent process failed to start. Check logs/agent/bootstrap-cli.log for details."
        exit 4
    fi
}

# Execute main function
main "$@"
