#!/bin/sh
# ssh-hostkey v1.0.2  (c) 10.10.2018 by Andreas Ley  (u) 10.12.2019
# Add hostkeys to /etc/ssh/ssh_known_hosts

PATH=/usr/bin:/bin
export PATH

domain=$(/bin/hostname --domain)

usage()
{
	echo "Usage: `basename $0` [-s] [-f ssh_known_hosts] FQDN [...]" >&2
	echo "-f  Specify ssh_known_hosts file location (defaults to /etc/ssh/ssh_known_hosts)" >&2
	echo "-s  also add short (domainless) host names for FQDNs ending in ${domain}" >&2
	exit 1
}

set -- `getopt hxvf:s $*` || usage

trace=false
verbose=false
ssh_known_hosts='/etc/ssh/ssh_known_hosts'
short=false
while :; do
	case $1 in
		-h)	sed '1d;s/^# *//;/^$/q' $0; usage;;
		-x)	set -x; trace=true; shift;;
		-v)	verbose=true; shift;;
		-f)	ssh_known_hosts="$2"; shift 2;;
		-s)	short=true; shift;;
		--)	shift; break;;
	esac
done

test $# -eq 0 && usage

for host in $@; do
	ip="${ip} `host "${host}" 2>/dev/null | sed -n 's/.* has address //p;s/.* has IPv6 address //p'`"
	if ${short} && test $(echo "${host}" | cut -d. -f2-) = "${domain}"; then
		ip="${ip} $(echo "${host}" | cut -d. -f1)"
	fi
done

ssh-keyscan $@ ${ip} 2>/dev/null | while read line; do
	fgrep -q -x "${line}" "${ssh_known_hosts}" || \
		echo "${line}" >>"${ssh_known_hosts}"
done
chmod 644 "${ssh_known_hosts}"

exit 0
