#!/bin/bash
#
# @package      hubzero-submit-distributor
# @file         update-known-hosts
# @author       Steven Clark <clarks@purdue.edu>
# @copyright    Copyright (c) 2004-2013 HUBzero Foundation, LLC.
# @license      http://www.gnu.org/licenses/lgpl-3.0.html LGPLv3
#
# Copyright (c) 2004-2013 HUBzero Foundation, LLC.
#
# This file is part of: The HUBzero(R) Platform for Scientific Collaboration
#
# The HUBzero(R) Platform for Scientific Collaboration (HUBzero) is free
# software: you can redistribute it and/or modify it under the terms of
# the GNU Lesser General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# HUBzero is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# HUBzero is a registered trademark of HUBzero Foundation, LLC.
#
PATH=/usr/bin:/bin
export PATH

function valid_ip()
{
   local ip=$1
   local stat=1

   if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
      OIFS=$IFS
      IFS='.'
      ip=($ip)
      IFS=$OIFS
      [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
          && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
      stat=$?
   fi
   return $stat
}

host=$1

#
# Look for the host first.  If it exists, exit.
#
grep -q "^${host}[ ,]" /etc/ssh/ssh_known_hosts 2>/dev/null && exit 0

#
# Become root if not already.
#
if [[ $(id -u) != 0 ]] ; then
   sudo $0 $*
   exit $?
fi

if valid_ip ${host} ; then
   if [ ${host:0:4} = '127.' ] ; then
      t=${host%.*}
      o=${t##*.}
      let port=2000+${o}

      ksargs[0]="-p"
      ksargs[1]=${port}
      ksargs[2]="${host},${host}"
   else
      ksargs[0]="${host},${host}"
   fi
else
   addrs=$(host -t A ${host} | while read _ _ _ addr; do echo -n ,$addr; done)
   ksargs[0]="${host}${addrs}"
fi
#
# Create the file if it doesn't exist.
#
if [ ! -f /etc/ssh/ssh_known_hosts ] ; then
   touch /etc/ssh/ssh_known_hosts
   chmod 644 /etc/ssh/ssh_known_hosts
fi

#echo "Can't find key for ${host}.  Adding it to the ssh_known_hosts file." 1>&2

#
# Construct a new entry.
#
ssh-keyscan -t rsa ${ksargs[@]} >> /etc/ssh/ssh_known_hosts 2>&1 || {
  echo "Unable to add ${host}${addrs} to ssh_known_hosts" 1>&2
  exit 1
}

exit 0
