#!/usr/bin/env bash
# Ensure a tmux session exists with the given name (or in a session group
# with that name). Creates it (detached) if missing; ensures named windows exist.
#
# IMPORTANT: tmux "session groups" (created via `tmux new-session -t <name>`)
# produce numbered sessions like "develop-0", "develop-24", etc. that share
# windows. If you are attached to a grouped session, there may be no session
# with the exact base name. This script checks both exact name matches and
# session groups to avoid creating a duplicate session.
#
# Usage: ensure-session.sh <session-name> <repo-root>

set -euo pipefail

SESSION="${1:?session name required}"
REPO_ROOT="${2:?repo root required}"

# Resolve the actual session name to target.
# 1. Check for an exact name match.
# 2. Check for any session in a group with this name.
resolve_session() {
  if tmux has-session -t "=${SESSION}" 2>/dev/null; then
    echo "${SESSION}"
    return
  fi

  local grouped
  grouped=$(tmux list-sessions -F '#{session_name} #{session_group}' 2>/dev/null \
    | awk -v g="${SESSION}" '$2 == g { print $1; exit }')
  if [[ -n "${grouped}" ]]; then
    echo "${grouped}"
    return
  fi

  return 1
}

TARGET=$(resolve_session) && {
  echo "Session '${SESSION}' already exists (via '${TARGET}')"
} || {
  tmux new-session -d -s "${SESSION}" -n server -c "${REPO_ROOT}"
  TARGET="${SESSION}"
  echo "Created session '${SESSION}'"
}

# Ensure 'server' window
if ! tmux list-windows -t "=${TARGET}" -F '#{window_name}' | grep -q '^server$'; then
  tmux new-window -t "=${TARGET}" -n server -c "${REPO_ROOT}"
  echo "Created window 'server'"
fi

# Ensure 'test-ship' window
if ! tmux list-windows -t "=${TARGET}" -F '#{window_name}' | grep -q '^test-ship$'; then
  tmux new-window -t "=${TARGET}" -n test-ship -c "${REPO_ROOT}"
  echo "Created window 'test-ship'"
fi
