#!/bin/bash
set -eu

# Set HISTCONTROL to ignorespace
HISTCONTROL="ignorespace"

# Define the session name
SESSION_NAME="{{ session_name }}"
LOG_FILE="{{ log_file }}"
PID_FILE="{{ pid_file }}"

# Array of commands to run in separate windows
COMMANDS=(
	{% for command in commands %}
	"{{ command }}"
	{% endfor %}
)

# Start a new screen session (detached)
screen -dmS $SESSION_NAME

# Initialize the PID list
AFLR_PID_LIST=""

# Function to wait for shell to be ready
wait_for_shell() {
    local window_num=$1
    local max_attempts=10
    local attempt=1
    local marker="AFLR_SHELL_READY_$$"  # Use PID to make marker unique
    
    # Send echo command with our marker
    screen -S $SESSION_NAME -p $window_num -X stuff "echo '$marker'\n"
    
    while [ $attempt -le $max_attempts ]; do
        local temp_capture="/tmp/screen_capture_$$_${window_num}.txt"
        screen -S $SESSION_NAME -p $window_num -X hardcopy $temp_capture
        if [ -f "$temp_capture" ] && grep -q "$marker" "$temp_capture"; then
            rm -f "$temp_capture"
            sleep 0.1  # Small delay to ensure shell is fully ready after marker
            return 0
        fi
        rm -f "$temp_capture"
        sleep 0.1
        attempt=$((attempt + 1))
    done
    return 1
}

# Create and rename a window for each command
for i in "${!COMMANDS[@]}"; do
	WINDOW_NAME="window-$i"
	TEMP_PID_FILE="/tmp/aflr_pid_${i}.txt"
	COMMAND_ESCAPED=$(echo "${COMMANDS[$i]}" | sed 's/"/\\"/g')
	if [ $i -eq 0 ]; then
		# For the first command, send it to the first window and rename it
		screen -S $SESSION_NAME -p 0 -X title $WINDOW_NAME
        wait_for_shell "0"
		screen -S $SESSION_NAME -p 0 -X stuff $' { '"$COMMAND_ESCAPED"' & echo $! > '"$TEMP_PID_FILE"'; clear; fg; }\n'
	else
		# For subsequent commands, create new windows and rename them
		screen -S $SESSION_NAME -X screen -t $WINDOW_NAME
        wait_for_shell "$i"
		screen -S $SESSION_NAME -p $WINDOW_NAME -X stuff $' { '"$COMMAND_ESCAPED"' & echo $! > '"$TEMP_PID_FILE"'; clear; fg; }\n'
	fi

    # Add a small delay between windows
    sleep 0.2
done

# Wait for all commands to start and PIDs to be written
sleep 1

# Capture the PIDs from the temporary files
for i in "${!COMMANDS[@]}"; do
	TEMP_PID_FILE="/tmp/aflr_pid_${i}.txt"
	if [ -f "$TEMP_PID_FILE" ]; then
		PID=$(cat "$TEMP_PID_FILE")
		if [ -n "$PID" ]; then
			if [ -z "$AFLR_PID_LIST" ]; then
				AFLR_PID_LIST="$PID"
			else
				AFLR_PID_LIST="$AFLR_PID_LIST:$PID"
			fi
		fi
		rm "$TEMP_PID_FILE"
	fi
done

# Configure the screen status bar
screen -S $SESSION_NAME -X hardstatus alwayslastline "%{.kW}%-w%{.gK}%n %t%{-}%+w %= %{..B}%H %LD %MM/%d %YY %c"
screen -S $SESSION_NAME -X startup_message off

# Redirect screen session log to a specific file
screen -S $SESSION_NAME -X logfile $LOG_FILE

echo $AFLR_PID_LIST > "$PID_FILE"
