#! /bin/bash
# Копирование RSA-ключей на рабочие станции
# Вызов без параметров: используется имя файла /server/ip.txt
# Вызов с параметром: имя файла со списком ip адресов или конкретный ip-адрес
SSHOPT="-o GSSAPIAuthentication=no -o ConnectTimeout=3 -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o LogLevel=ERROR"

if [ ! $1 ]; then
	IPfile=/server/ip.txt
	IPaddr=
elif echo "$1" | egrep -q '^\-?[0-9]'; then 
	IPfile=
	IPaddr=$1
else
	IPfile=$1
	IPaddr=
fi

cp_to_ws() {
	echo $1
	IP=`echo $1 | cut -d":" -f1`
	PORT=`echo $1 | cut -s -d":" -f2`
	if [ -z $PORT ]; then
		PORT=22
	fi
	scp -P $PORT $SSHOPT /home/adisadmin/.ssh/id_rsa.pub adisadmin@$IP:/home/adisadmin
	ret=$?
	if [ $ret = 0 ]; then
		ssh -p $PORT $SSHOPT adisadmin@$IP "mkdir ~/.ssh &> /dev/null; chmod 700 ~/.ssh; cat ~/id_rsa.pub >> ~/.ssh/authorized_keys; sort ~/.ssh/authorized_keys | uniq > ~/aaa; mv -f ~/aaa ~/.ssh/authorized_keys; rm -f ~/id_rsa.pub"
		ret=$?
	fi
	if [ $ret != 0 ]; then
		echo "$1 did not do $0"
		return 1
	fi
	echo "$1 ok"
	return 0
}

if [ $IPfile ]; then
	for ip in `cat $IPfile`; do
		cp_to_ws $ip
	done
else
	cp_to_ws $IPaddr
fi
