#!/usr/bin/bash
#
# $Id
#
# CG 12.02.09

SSH='/usr/bin/ssh'

if [ $# -lt 1 -o "$1" = "-h" ];  then
  echo "Usage: elt-ssh_set.sh <host> # or"
  echo "Usage: elt-ssh_set.sh <host1> <host2> ... # or"
  echo "Usage: elt-ssh_set.sh <hoslist-filename>"
  exit 1
fi

# Generate the public key if it does not exist
if [ ! -f ~/.ssh/id_rsa ]; then
  ssh-keygen -t rsa -N "" -f ~/.ssh/id_rsa >/dev/null 2>&1
fi

# If $1 is a file use it as the list of hosts
if [ -f "$1" ]; then
  LIST=`cat $1`
else
  LIST="$*"
fi

#echo  LIST OF HOSTS=$LIST
#exit 0

bon="[1m"
boff="[0m"
noglob=1

for machine in ${LIST}
do
  # Discard comments
  echo $machine | egrep -q '^#'
  if [ $? -eq 0 ]
  then
    continue
  fi
  host $machine > /dev/null 2>&1
  if [ $? -ne 0 ]
  then
    echo "$bon$machine: UNKNOWN HOST$boff"
    continue
  fi
  ping -c 1 -W 1 $machine > /dev/null 2>&1
  if [ $? -eq 0 ]
  then
    # Check first if there is permission to ssh
    $SSH -o PasswordAuthentication=no $machine hostname >/dev/null 2>&1
    if [ $? -ne 0 ]; then # Supply public_key by providing first password
      cat ~/.ssh/id_rsa.pub | $SSH $machine "if [ ! -d .ssh ]; then mkdir .ssh; fi ; cat >> .ssh/authorized_keys"
    fi
    echo "$bon$machine: OK $boff"
#    $SSH $machine -n hostname
  else
    echo "$bon$machine: HOST IS DOWN$boff"
  fi
done
