#!/usr/bin/env bash
#
# Open a new tmux session named after the current directory with a basic
# development/editing environment.
#
# The session will be named after the current directory unless the desired name
# is passed as the only argument.
set -e

if [ -z "$1" ]; then
  cwd=$(pwd)
  sessionname=$(basename "$cwd" | tr .: _)
else
  sessionname="$1"
fi

tmux_new_result=$(tmux new -d -s "$sessionname" 2>&1) || true
exitcode=$?

if echo "$tmux_new_result" | grep -q "duplicate session"; then
  echo "Session $sessionname already exists. Attaching..."
  tmux new -d -A -s "$sessionname"
  exit 0
fi

if [ $exitcode -ne 0 ]; then
  echo "$tmux_new_result"
  exit $exitcode
fi

tmux rename-window -t "$sessionname:1" cli
tmux new-window -t "$sessionname" -n vim zsh -ic nvim
tmux select-window -t "$sessionname:1"
# https://github.com/tmux/tmux/issues/2064
sleep 0.5
tmux attach -t "$sessionname"