#!/usr/bin/env bash
#
# shellcheck shell=bash disable=SC2207
# idea: https://cedaei.com/posts/ideas-from-my-dev-setup-always-tmux
# https://lobste.rs/s/n5blid/ideas_from_my_development_setup_always

# doesn't let you press ctrl-c
ctrl_c() {
  printf "%s\n" "enter nil to drop to normal prompt"
}
trap ctrl_c INT

no_of_terminals="$(tmux list-sessions | wc -l)"
IFS=$(printf ' \n\t')
output="${output}$(tmux list-sessions)"
output_names="${output_names}$(tmux list-sessions -F\#S)"
k=1
echo "choose the terminal to attach: "

for i in ${output}; do
  echo "${k} - ${i}"
  ((k++))
done
echo
echo "create a new session by entering a name for it"
read -r input

if [[ ${input} == "" ]]; then
  tmux new-session
elif [[ ${input} == "nil" ]]; then
  exit 1
elif [[ ${input} =~ ^[0-9]+$ ]] && [[ ${input} -le ${no_of_terminals} ]]; then
  terminal_name="${output_names[input - 1]}"
  tmux attach -t "${terminal_name}"
else
  tmux new-session -s "${input}"
fi
exit 0
