#!/usr/bin/env bash

if ! test -x "$(command -v gum)"; then
    echo "Missing dependency: gum"
    echo "See github.com/charmbracelet/gum"
    exit 1
fi

if ! test -x "$(command -v autossh)"; then
    echo "Missing dependency: autossh"
    exit 1
fi

SSH_CONFIG="${HOME}/.ssh/config"
hostn_array=()

# Read HostNames from ssh config and store them in hostn_array.
while IFS= read -r line; do
    if [[ "$line" == *"Host "* ]]; then
        hostn=$(echo "$line" | awk '{ print $2 }')
        hostn_array+=("$hostn")
    fi
done < "${SSH_CONFIG}"

# Print each member of logins array on a new line and pipe to gum choose.
# Store selection.
selection=$(printf "%s\n" "${hostn_array[@]}" | gum choose --header="SSH Host" --limit=1)

# If $selection is not aborted by user, pass it to the `autossh -M 0` command.
if [ "${selection}" != "user aborted" ]; then
    autossh -M 0 "${selection}"
fi