#!/bin/bash

##########################################################################
# SecPanel.dist - Key-Distribution
# Shellscript for distributing public keys to remote hosts
#
# Version SecPanel 0.6.0
# Author: Steffen Leich-Nienhaus <steffen.leich _at_ gmail.com>
##########################################################################


if [ -z $4 ]
then
cat <<EOF

	SecPanel 0.6.0 - key distribution
	Shellscript for distributing public keys to remote hosts
	Usage: spdistkey.sh <host> <port> <user> <keyfile> <sshbin>

EOF
    exit 2
fi

HOST=$1
PORT=$2
USER=$3
IDENTITY=$4
SSHBIN=$5

if [ ! -s $IDENTITY ]
then
    echo "Keyfile $IDENTITY does not exist or has size zero"
    do_exit
fi


cat <<EOF

    SecPanel - Distribution of public keys to remote hosts
    ------------------------------------------------------

    Connecting to $HOST:$PORT as $USER
    with key $IDENTITY

    First we try to check if the key is already on the target host.

EOF

$SSHBIN -l $USER -p $PORT $HOST "mkdir \$HOME/.ssh 2>/dev/null; grep '$(cat $IDENTITY)' \$HOME/.ssh/authorized_keys > /dev/null 2>&1"

DISTRET=$?

if [ $DISTRET = 0 ]
then
    echo
    echo "    Your public key is already on the remote host"
    echo
elif [ $DISTRET = 255 ]
then
    echo
    echo "There was an error connecting to the remote site"
    echo -e "Parameters:\n\tHost:\t$HOST\n\tUser:\t$USER"
    echo
    echo "Canceling the key-transfer"
    do_exit
else
    echo
    echo "    The key could not be found on this host"
    echo "    -> Transfering your public key to remote host"
    echo
    $SSHBIN -l $USER $HOST "cat >> \$HOME/.ssh/authorized_keys; chmod 600 \$HOME/.ssh/authorized_keys; chmod 700 \$HOME/.ssh" < $IDENTITY
fi

