#!/usr/bin/env bash

# Credit to ThePrimeagen.

set -o nounset
set -o pipefail

if [[ $# -eq 1 ]]; then
  selected=$1
else
  # Get the session name from fuzzy-finding list of directories and generating a
  # tmux-safe version.

  # Find all project directories within ~/Code, ignoring ~/Code/tmp as those
  # are only at a single level and I don't want sub-directories within those
  # directories to be shown.
  items+=$(find "${HOME}/Code" \
    -maxdepth 3 \
    -mindepth 3 \
    -type d \
    ! -name "*-old" \
    ! -name "*.old" \
    ! -path "${HOME}/Code/tmp/*"
  )

  # Add the top-level directories within ~/Code/tmp.
  items+=" "
  items+=$(find "${HOME}/Code/tmp" \
    -maxdepth 1  \
    -mindepth 1 \
    -type d \
    ! -name "*-old" \
    ! -name "*.old"
  )

  selected=$(echo "${items}" | tr ' ' "\n" | sort | fzf --reverse)
fi

if [[ -z "${selected}" ]]; then
  exit 0
fi

session_name=$(basename "${selected}" | sed 's/\./-/g')
session_path="${selected}"

# Git worktrees.
if [[ -e "${selected}/main" ]]; then
  session_path="${selected}/main"
fi

if tmux has-session -t "${session_name}" 2> /dev/null; then
  tmux attach -t "${session_name}"
fi

# If a .tmux file exists, run it with the generated session name and path.
if [[ -e "${session_path}/.tmuxinator.yaml" ]]; then
  cd "${session_path}" && tmuxinator start
  exit
elif [[ -e "${session_path}/.ignored/.tmuxinator.yaml" ]]; then
  cd "${session_path}" && tmuxinator start --project-config "${session_path}/.ignored/.tmuxinator.yaml"
  exit
elif [[ -e "${session_path}/.tmux" ]]; then
  "${session_path}/.tmux" "${session_name}" "${session_path}"
  exit
elif [[ -e "${session_path}/.ignored/.tmux" ]]; then
  "${session_path}/.ignored/.tmux" "${session_name}" "${session_path}"
  exit
fi

tmux new-session -d -s "${session_name}" -c "${session_path}"

tmux switch-client -t "${session_name}" || tmux attach -t "${session_name}"