#!/bin/zsh

tmux_switch_to() {
    [[ -z $TMUX ]] && tmux attach-session -t $1 || tmux switch-client -t $1
}

tmux_hydrate() {
    local tmux_hydrate_path="$XDG_CONFIG_HOME/tmux/.tmux-session-hydrate-default"
    [[ -f $2/.tmux-session-hydrate ]] && tmux_hydrate_path="$2/.tmux-session-hydrate"
    [[ -f $tmux_hydrate_path ]] && tmux send-keys -t $1 "source $tmux_hydrate_path" c-M
}

tmux_existing_sessions=$(tmux list-sessions 2> /dev/null || echo '')
tmux_search_dirs=(
    $DIR_HOME_BOX
    $DIR_DEV
    $DIR_GIT_PROJECTS/*
)
tmux_target_name=''
tmux_target_path=''

[[ $# -eq 1 ]] && tmux_target_path=$1 ||
    tmux_target_path=$(find $tmux_search_dirs -mindepth 1 -maxdepth 1 -type d | fzf)

if [[ $tmux_target_path = "." ]]; then tmux_target_name=$(basename $(pwd)) && tmux_target_path=$(pwd);
elif [[ $tmux_target_path = "hub" ]]; then tmux_target_name="hub" && tmux_target_path="$HOME";
elif [[ -n $tmux_target_path ]]; then tmux_target_name=$(basename "$tmux_target_path" | tr . _);
fi

[[ -z $tmux_target_name ]] && exit 0

! (echo $tmux_existing_sessions | grep -q "$tmux_target_name") &&
    tmux new-session -d -s $tmux_target_name -c $tmux_target_path &&
    tmux_hydrate $tmux_target_name $tmux_target_path
tmux_switch_to $tmux_target_name
