#!/bin/bash
#
# @package      hubzero-submit-distributor
# @file         update-known-hosts
# @copyright    Copyright (c) 2004-2020 The Regents of the University of California.
# @license      http://opensource.org/licenses/MIT MIT
#
# Copyright (c) 2004-2020 The Regents of the University of California.
#
# 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 The Regents of the University of California.
#
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})

   if [ $? -eq 0 ] ; then
      addrs=$(host -t A ${host} | grep -v alias | cut -d' ' -f4)
   else
      addrs=$(getent ahostsv4 ${host} | grep STREAM | cut -d' ' -f1 | head -1)
   fi

   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
