#!/usr/bin/env bash
# tw: create a sibling git worktree and enter its canonical tmux session.

set -euo pipefail

usage() {
  echo "Usage: tw <name>" >&2
}

if [[ ${1:-} == "-h" || ${1:-} == "--help" ]]; then
  usage
  exit 0
fi

if [[ $# -ne 1 ]]; then
  usage
  exit 1
fi

script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
lib_path="$script_dir/tmux-lib.sh"
root_helper="${TMUX_PROJECT_ROOT_BIN:-$script_dir/tmux-project-root}"
tmproj_bin="${TMPROJ_BIN:-$script_dir/tmproj}"

# shellcheck source=bin/tmux-lib.sh
source "$lib_path"

checkout_root=$($root_helper .)
worktree_path=$(create_sibling_worktree "$checkout_root" "$1")

exec "$tmproj_bin" "$worktree_path"
