#!/usr/bin/env bash

function _ssh_menu_preview {
    file=$1; shift
    host=$1; shift

    # show host block from ssh config
    awk -v h="$host" '
        $0 == "Host " h { found=1 }
        found && /^[^ \t]/ && $0 != "Host " h { exit }
        found
    ' "$file"

    echo ""

    # resolve hostname for reachability check
    hostname=$(awk -v h="$host" '
        $0 == "Host " h { found=1; next }
        found && /^[^ \t]/ { exit }
        found && /HostName/ { print $2 }
    ' "$file")

    if command -v host &>/dev/null; then
        host "${hostname:-$host}"
        echo ""
    fi

    ping -c 1 -W 1 "${hostname:-$host}" &>/dev/null \
        && echo "reachable" \
        || echo "not reachable"
}

export -f _ssh_menu_preview

function _ssh_menu_select {
    rg -N --no-heading '^Host .*' ~/.ssh \
        | sed 's/Host \(.*\)/\1/' | sort \
        | SHELL=$(which bash) fzf \
            --delimiter ':' \
            --with-nth 2 \
            --preview "_ssh_menu_preview {1} {2}" \
            --preview-label "ssh config info" \
            --border-label "ssh-menu" \
        | cut -d ":" -f2
}

case "${1:-}" in
    -s) _ssh_menu_select ;;
    *)
        selected="$(_ssh_menu_select)"
        [[ -n $selected ]] && ssh "$selected"
        ;;
esac
