#!/usr/local/bin/bash
#/ Usage: ghe-ssh-host-key-reset <host>
#/
#/ Removes all keys belonging to the specified host (with optional port number) from known_hosts file.
set -e

# Bring in the backup configuration
# shellcheck source=share/github-backup-utils/ghe-backup-config
. "$( dirname "${BASH_SOURCE[0]}" )/ghe-backup-config"

host="$1"

# Show usage with no host
[ -z "$host" ] && grep '^#/' < "$0" | cut -c 4- && exit 2

ghe_host=$(ssh_host_part "$host")
ghe_port=$(ssh_port_part "$host")

# ssh-keygen -R expects "hostname" or "[hostname]:port"
# we include the port if it differs from the SSH client's default for this host
default_port=$(ssh -G $ghe_host | grep 'port ' | cut -d' ' -f2)
known_host="$ghe_host"
if [[ "$ghe_port" != "$default_port" ]]; then
  known_host="[$ghe_host]:$ghe_port"
fi

# If the host doesn't exist in known hosts, nothing to do.
ssh-keygen -F "$known_host" || exit 0

# Remove host key from known_hosts
ssh-keygen -R "$known_host"

# We expect the host key may have changed so we add it to the known hosts file in advance
ghe-ssh -o StrictHostKeyChecking=accept-new "$host" /bin/true
