#!/bin/sh

# copies host keys into known hosts files for lessdisks terminals

# copyright 2004 vagrant@freegeek.org, distributed under the terms of the
# GNU General Public License version 2 or any later version.

# Rewrite 2005 Jonas Smedegaard <dr@jones.dk>:
#   * Preserve existing keys
#   * Quote all vars
#   * Set modes on SSH dir only if creating it
#   * Sanity checks on getting keys
#   * Inject only existing keys

# Re-rewrite 2005 Vagrant Cascadian <vagrant@freegeek.org>:
#   * generate proper known_hosts file
#   * use /etc/ssh/ssh_known_hosts instead of /root/.ssh/known_hosts
#   * use $() instead of ``

set -e

if [ -r /etc/lessdisks-install.conf ]; then
  . /etc/lessdisks-install.conf
fi 

if [ -r /etc/lessdisks/server.config ]; then
  . /etc/lessdisks/server.config
fi

if [ -z "$lessdisks_path" ]; then
  echo "lessdisks_path not set, exiting..."
  exit 2
fi

workdir="$lessdisks_path/etc/ssh"
known_hosts="$workdir/ssh_known_hosts"
thishost="$(hostname)"

if [ ! -d "$workdir" ]; then
	mkdir -p "$workdir"
fi

for type in rsa dsa; do

	pubkey="$(cat /etc/ssh/ssh_host_${type}_key.pub | tail -n 1 | awk '{ print $1" "$2}')"
	pubkey_type="$(echo $pubkey | awk '{print $1}')"
	if [ -n "$pubkey" ]; then
		# Make sure there's at least one line for perl to parse
		echo "# dummy line" >> "$known_hosts"

		for name in xapp disk $thishost; do
			perl -ni -e "\$n++; \
				print \"$name $pubkey\n\" if \$n==1; \
				print && next unless /^($name\s$pubkey_type|# dummy line)/i;" "$known_hosts"
		done
	fi
done

exit $?
