#!<%= ENV["SHELL"] || "/bin/bash" %>

# Clear rbenv variables before starting tmux
unset RBENV_VERSION
unset RBENV_DIR

<%= tmux %> start-server;

cd <%= root || "." %>

# Run on_project_start command.
<%= hook_on_project_start %>

<%- if !tmux_has_session? name -%>

  # Run pre command.
  <%= pre %>
  
  # Run on_project_first_start command.
  <%= hook_on_project_first_start %>

  # Create the session and the first window. Manually switch to root
  # directory if required to support tmux < 1.9
  TMUX= <%= tmux_new_session_command %>
  <% if windows.first.root? %>
  <%= windows.first.tmux_window_command_prefix %> <%= "cd #{windows.first.root}".shellescape %> C-m
  <% end %>

  <% if Tmuxinator::Config.version < 1.7 %>
  # Set the default path for versions prior to 1.7
    <% if root? %>
  <%= tmux %> set-option -t <%= name %> <%= Tmuxinator::Config.default_path_option %> <%= root -%> 1>/dev/null
    <% end %>
  <% end %>

  # Create other windows.
  <% windows.drop(1).each do |window| %>
  <%= window.tmux_new_window_command %>
  <% end %>

  <% windows.each do |window| %>

  # Window "<%= window.name %>"
    <% if window.synchronize_before? %>
  <%= window.tmux_synchronize_panes %>
    <% end %>
    <% unless window.panes? %>
      <% if window.project.pre_window %>
  <%= window.tmux_pre_window_command %>
      <% end %>
      <% window.commands.each do |command| %>
  <%= command %>
      <% end %>
    <% else %>
      <% window.panes.each do |pane| %>
        <% if pane.project.pre_window %>
  <%= pane.tmux_pre_window_command %>
        <% end %>
        <% if pane.tab.pre %>
  <%= pane.tmux_pre_command %>
        <% end %>
        <% pane.commands.each do |command| %>
  <%= pane.tmux_main_command(command) %>
        <% end %>

        <% unless pane.last? %>
  <%= pane.tmux_split_command %>
        <% end %>
  <%= window.tmux_tiled_layout_command %>
      <% end %>

  <%= window.tmux_layout_command %>
  <%= window.tmux_select_first_pane %>
    <% end %>

    <% if window.synchronize_after? %>
  <%= window.tmux_synchronize_panes %>
    <% end %>
  <% end %>

  <%= tmux %> select-window -t <%= startup_window %>
  <%= tmux %> select-pane -t <%= startup_pane %>
<%- else -%>
  # Run on_project_restart command.
  <%= hook_on_project_restart %>
<%- end -%>

<%- if attach? -%>
  if [ -z "$TMUX" ]; then
    <%= tmux %> -u attach-session -t <%= name %>
  else
    <%= tmux %> -u switch-client -t <%= name %>
  fi
<%- end -%>

<%= post %>
    
# Run on_project_exit command.
<%= hook_on_project_exit %>
