#!/bin/bash

# blob:summary=Run one SSH or NetBird SSH session in the current terminal, offering to trust an unknown host key
# blob:args=<ssh|netbird> <[user@]host>
# blob:hidden=true

mode="${1-}"
target="${2-}"
host="${target##*@}"
known_hosts="$HOME/.ssh/known_hosts"

pause_before_closing() {
  echo
  read -rp "Connection ended ($1). Press Enter to close"
}

host_is_known() {
  ssh-keygen -F "$host" -f "$known_hosts" >/dev/null 2>&1
}

offer_to_trust_host() {
  local scanned
  scanned=$(ssh-keyscan -T 5 "$host" 2>/dev/null)
  if [[ -z $scanned ]]; then
    echo
    echo "Could not read a host key from $host:22. Check that the SSH server is enabled on the peer."
    return 1
  fi
  echo
  echo "The host key for $host is not in $known_hosts."
  echo "Fingerprints it offers:"
  ssh-keygen -lf - <<<"$scanned" | sed 's/^/  /'
  echo
  read -rp "Trust this host and connect again? [y/N] " answer
  [[ $answer =~ ^[Yy]$ ]] || return 1
  mkdir -p "$(dirname "$known_hosts")"
  printf '%s\n' "$scanned" >>"$known_hosts"
  echo "Saved to $known_hosts"
  echo
}

case "$mode" in
  ssh)
    ssh "$target"
    status=$?
    ;;
  netbird)
    netbird ssh "$target"
    status=$?
    if (( status != 0 )) && ! host_is_known && offer_to_trust_host; then
      netbird ssh "$target"
      status=$?
    fi
    ;;
  *)
    echo "Usage: blob-ssh-session <ssh|netbird> <[user@]host>" >&2
    status=2
    ;;
esac

(( status == 0 )) || pause_before_closing "$status"
exit "$status"
