#!/bin/sh

set -eu


export FZF_DEFAULT_OPTS="\
${FZF_DEFAULT_OPTS}
--print-query
--border-label=' Start SSH session '
--preview-window=hidden
--preview=''
"

ssh_hosts="$(grep 'Host ' "${HOME}/.ssh/config" | sed 's/^Host //')"
etc_hosts="$(grep -v '^#' /etc/hosts)"
history_hosts="$(grep ssh "${HOME}/.zsh_history" | grep -o -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')"
all_hosts="$(echo "${ssh_hosts}" "${etc_hosts}" "${history_hosts}" | grep -v '\*'| sed 's/ /\n/g ; /^$/d' | sort | uniq | tac)"


choosed_ssh_server="$(echo "${all_hosts}" | fzf | tail -n 1)"


if [ -z "${choosed_ssh_server}" ]; then
    exit 0
fi

SESSION="ssh_$(echo "${choosed_ssh_server%% *}" | sed 's/\./\-/g ; s/\:/\-/g')"


if ! tmux has-session -t="${SESSION}" 2>/dev/null; then
    tmux new-session -s "${SESSION}" -c "${HOME}" -d -n "1" "TERM=xterm-256color ssh ${choosed_ssh_server} || read"
fi

tmux switch-client -t "${SESSION}"
