#!/bin/bash
# build the hosts configuration directory with the actual IP addresses
#
# Copyright (C) 2004  Eric Marchionni, Patrik Rayo
# Zuercher Hochschule Winterthur
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.  See <http://www.fsf.org/copyleft/gpl.txt>.
#
# This program 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 General Public License
# for more details.
#
# RCSID $Id: build-sshkeys,v 1.2 2005/02/15 14:12:16 as Exp $

DIR=`dirname $0`

source $DIR/function.sh

[ -f $DIR/../testing.conf ] || die "!! Configuration file 'testing.conf' not found"
[ -d $DIR/../hosts ]        || die "!! Directory 'hosts' not found"

source $DIR/../testing.conf

if [ ! -d $BUILDDIR ]
then
    cecho " * Creating directory '$BUILDDIR'"
    mkdir $BUILDDIR
fi

LOGFILE=${BUILDDIR}/testing.log

if [ ! -f $LOGFILE ]
then
    cecho-n " * Logfile '$LOGFILE' does not exist..creating.."
    touch $LOGFILE
    cecho "done"
fi

if [ ! -d ~/.ssh ]
then
    cecho-n " * Creating directory '~/.ssh'.."
    mkdir ~/.ssh
    cecho "done"
fi

if [ -f ~/.ssh/known_hosts ]
then
    cecho-n " * Backing up ~/.ssh/known_hosts to '~/.ssh/known_hosts.before_uml'.."
    cp -fp ~/.ssh/known_hosts ~/.ssh/known_hosts.before_uml
    cecho "done"
else
    cecho-n " * Creating '~/.ssh/known_hosts'"
    touch ~/.ssh/known_hosts
    cecho "done"
fi

for host in $HOSTNAMEIPV4
do
    HOSTNAME=`echo $host | awk -F, '{ print $1 }'`
    IP=`echo $host | awk -F, '{ print $2 }'`
    if [ `grep "$IP " ~/.ssh/known_hosts | wc -l` != "0" ]
    then
        cecho "!! Warning: An entry exists for the following IP address: $IP"
    else
	cecho-n " * Adding uml host $HOSTNAME ($IP) to '~/.ssh/known_hosts'.."
	echo "$HOSTNAME,$IP `cat $DIR/../hosts/ssh_host_rsa_key.pub`" >> ~/.ssh/known_hosts
	cecho "done"
    fi
done

#####################################
# preparing ssh for PK authentication
#

cecho-n " * Checking for ssh rsa key '~/.ssh/id_rsa.pub'.."
if [ -f ~/.ssh/id_rsa.pub ]
then
    cecho "already exists"
else
    cecho "not found"
    cecho-n " * Generating ssh rsa key pair.."
    echo "" | ssh-keygen -N "" -t rsa -f ~/.ssh/id_rsa >> $LOGFILE 2>&1
    cecho "done"
fi
