#!/bin/bash

# Simple tool that can be run to create a tmux session or
# connect to an existing one.

if [[ $# -eq 1 ]]; then
    echo $1
    selected=$1
else
    selected=$(find ~/repos/github.com/*/ ~/repos/gitlab.inkletblot.com/inkletblot ~/.config ~/ ~/nextcloud ~/nextcloud/*/ -mindepth 1 -maxdepth 1 -type d | fzf)
fi

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

selected_name=$(basename "$selected" | tr ":,. " _)

switch_to() {
    if [[ -z $TMUX ]]; then
        tmux attach-session -t "$selected_name"
    else
        tmux switch-client -t "$selected_name"
    fi
}

if tmux has-session -t="$selected_name" 2>/dev/null; then
    switch_to
    exit 0
fi

tmux new-session -ds "$selected_name" -c "$selected"
switch_to

tmux send-keys -t "$selected_name" "ready-tmux" 
