#!/bin/bash

if [ ! -d "/data/ymc-cluster-ymc-config-server/auth" ]; then
  echo "WARNING: Directory '/data/ymc-cluster-ymc-config-server/auth' not present..."
  exit 0
fi

remote_host=$1
known_installed_hosts_file="/data/ymc-cluster-ymc-config-server/auth/ssh_known_hosts"

if [ "$remote_host" == '' ]; then
  echo "ERROR: Please specify an hostname as the only option!" 1>&2
  exit 1
fi

remote_ip=$(fliwi-get-ip-for-hostname $remote_host)
if [ $? -ne 0 ] || [ "$remote_ip" == '' ]; then
  echo "ERROR: Could not get an IP for $remote_host" 1>&2
  exit 1
fi

echo "INFO: Removing the remote host-key from the know-hosts-db..."
ssh-keygen -R $remote_host -f $known_installed_hosts_file && ssh-keygen -R $(fliwi-get-ip-for-hostname $remote_host) -f $known_installed_hosts_file
if [ $? -ne 0 ]; then
  echo "ERROR: Failed to remove remote host-key of $remote_host from the know-hosts-db" 1>&2
  exit 1
else
  rm -f $known_installed_hosts_file".old"
fi

remote_ssh_rsa_pubkey=$(ssh-keyscan -t rsa -T 5 $remote_host | cut -d ' ' -f 3)
if [ $? -eq 0 ] && \
   [ "$remote_ssh_rsa_pubkey" != "" ]; then
  echo "INFO: Adding the remote host-key to the know-hosts-db..."
  echo "$remote_host,$remote_ip ssh-rsa $remote_ssh_rsa_pubkey" >> $known_installed_hosts_file
  if [ $? -ne 0 ]; then
    echo "ERROR: Failed to add remote host-key to know-hosts-db" 1>&2
    exit 1
  fi
else
  echo "WARNING: Not adding the remote '$remote_host' to the know-hosts-db, as no public key can be retrieved..."
fi

