#!/bin/sh
# @package      hubzero-mw2-exec-virtualssh
# @file         ensure-known-host
# @author       Pascal Meunier <pmeunier@purdue.edu>
# @copyright    Copyright (c) 2016-2017 HUBzero Foundation, LLC.
# @license      http://opensource.org/licenses/MIT MIT
#
# Based on prior work by Richard L. Kennell
#
# Copyright (c) 2016-2017 HUBzero Foundation, LLC.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# HUBzero is a registered trademark of HUBzero Foundation, LLC.
#

# add an SSH key to /etc/ssh/ssh_known_hosts
# root privilege required for ssh-keyscan

PATH=/usr/bin:/bin:/usr/sbin:/sbin

if [ $# -lt 1 ] || [ $# -gt 2 ]
then
  echo "Improper arguments for $0: $*" >&2
  exit 1
fi

hostname="$1"
portnum=22
[ $# = 2 ] && portnum="$2"

[ -f /etc/ssh/ssh_known_hosts ] || {
  touch /etc/ssh/ssh_known_hosts
}

egrep -q "^${hostname} " /etc/ssh/ssh_known_hosts || {
  ssh-keyscan -t rsa -p ${portnum} ${hostname} 2>/dev/null >> /etc/ssh/ssh_known_hosts
}

# make sure this file is always readable by all to avoid dialogs like
# "The authenticity of host 'localhost (127.0.0.1)' can't be established."
chmod 644 /etc/ssh/ssh_known_hosts

