#!/usr/bin/env zsh

local session_name
local start_command

function errcho {
  echo "$@" 1>&2
}

while [[ $# -gt 0 ]]; do
  case $1 in
    -n|--name)
      session_name="$2"
      shift;;
    -s|--start)
      start_command="$2"
      shift;;
    *)
      errcho "[ERR] Invalid option received '$1'"
      exit 1
  esac
  shift
done

if [[ -z "$session_name" ]]; then
  session_name="$(basename `pwd`)"
fi

session_name=$(echo "$session_name"    \
                | tr '. \n' '-'        \
                | sed 's/^\(-\|_\)\+//'\
                | sed 's/\(-\|_\)\+$//')

function session_exists {
  if [[ $(tmux ls -F '#S' 2>/dev/null \
          | grep -E "^$1\$"           \
          | wc -l) -eq 1 ]]; then
    return 0
  fi

  return 1
}

if session_exists $session_name; then
  exec tmux attach-session -t "$session_name"
else
  exec tmux new-session -s "$session_name" -c "$PWD" -n "shell" $start_command
fi
