#!/usr/bin/env bash

if [[ $# -eq 1 ]]; then
    selected=$1
else
    selected=$(ggman exec pwd 2>&1 >/dev/null \
        | fzf --cycle \
        --bind 'tab:toggle-up,btab:toggle-down' \
        --header "Navigate with ARROW KEYS or TAB/S-TAB. Select with ENTER." \
        --border "double" \
        --border-label "tmux-sessionizer" \
        --ansi \
        --highlight-line \
    )
fi

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

path=$selected
while [[ "$path" != "" && ! -e "$path/.sessionizer" ]]; do
    path=${path%/*}
done

selected_name="$(cat $path/.sessionizer)_$(basename $selected | tr . _ | head -c 10)_$(echo $selected | shasum -a 256 | head -c 4)"
tmux_running=$(pgrep tmux)

if [[ -z $TMUX ]] && [[ -z $tmux_running ]]; then
    tmux new-session -s $selected_name -c $selected
    exit 0
fi

if ! tmux has-session -t=$selected_name 2> /dev/null; then
    tmux new-session -ds $selected_name -c $selected
fi

tmux switch-client -t $selected_name