#!/bin/sh
#
# Copyright (c) 2004-2010 Purdue University All rights reserved.
# 
# Developed by: HUBzero Technology Group, Purdue University
#               http://hubzero.org
# 
# 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 HUBzero.
# If not, see <http://www.gnu.org/licenses/>.
# 
# GNU LESSER GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
# Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
#
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.
#
[[ -f /etc/ssh/ssh_known_hosts ]] || touch /etc/ssh/ssh_known_hosts

#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
