#!/bin/bash

# Get the first session as the target for all panes
target_session=$(tmux list-sessions -F '#{session_name}' | head -n 1)
target_window="${target_session}:0" # assuming the first window is index 0
target_pane="${target_window}.0" # assuming the first pane is index 0

# Loop through each session
tmux list-sessions -F '#{session_name}' | while read session; do
    # Skip the target session
    if [[ "$session" == "$target_session" ]]; then
        continue
    fi

    # Loop through each window in the session
    tmux list-windows -t "$session" -F '#{window_index}' | while read window; do
        # Loop through each pane in the window
        tmux list-panes -t "${session}:${window}" -F '#{pane_index}' | while read pane; do
            source="${session}:${window}.${pane}"
            # Check if the source is not the same as the target
            if [[ "$source" != "$target_pane" ]]; then
                # Join the pane to the target pane
                tmux join-pane -s "$source" -t "$target_pane"
            fi
        done
    done

    # After moving all panes from a session, kill the now-empty session
    # Check if the session to be killed is not the target session
    if [[ "$session" != "$target_session" ]]; then
        tmux kill-session -t "$session"
    fi
done

# After moving all panes, you may want to manually adjust the layout.
# For a simple automatic layout adjustment, you can use:
tmux select-layout -t "$target_window" tiled

# Attach to the master session after everything is merged
tmux attach-session -t "$target_session"