#!/bin/bash

usage()
{
	echo "Usage: $0 [-p <port>] <hostname> [<args>...]" >&2
	exit 2
}

update_known_hosts()
{
	local port= server=

	if [ "$1" = "-p" ]; then
		port="$2"
		server="$3"
	else
		server="$1"
	fi

	local hostname="`echo "$server" | cut -d@ -f2`"
	local server_addr="$hostname${port:+:$port}"

	KNOWN_HOSTS="`readlink -m ~/.ssh/git_known_hosts${port:+_with_port_$port}`"

	if [ -f "$KNOWN_HOSTS" ] && [ -n "`ssh-keygen -F "$hostname" -f "$KNOWN_HOSTS"`" ]; then
		echo "Public key for the server at '$server_addr' is already known in '$KNOWN_HOSTS'." >&2
		return 0
	fi

	echo "Server at '$server_addr' is seen for the first time." >&2
	echo "Adding its public key to the list of known hosts in '$KNOWN_HOSTS'." >&2

	local key="`ssh-keyscan ${port:+-p $port} -H "$hostname"`"
	[ -n "$key" ] || {
		echo "Failed to gather public SSH host key for the '$server_addr'." >&2
		return 1
	}

	mkdir -p -m0700 "`dirname "$KNOWN_HOSTS"`"
	echo "$key" >> "$KNOWN_HOSTS" || {
		echo "Failed to add public SSH host key for the '$server_addr' into '$KNOWN_HOSTS'." >&2
		return 1
	}

	return 0
}


[ $# -ge 1 ] || usage

KNOWN_HOSTS=
update_known_hosts "$@"

[ -f "$KNOWN_HOSTS" ] || {
	echo "Known hosts file '$KNOWN_HOSTS' doesn't exist" >&2
	exit 1
}
ssh -o UserKnownHostsFile="$KNOWN_HOSTS" -o StrictHostKeyChecking=yes -o HashKnownHosts=yes -o BatchMode=yes "$@"
