#! /bin/ksh

#
# Name        : ${HOME}/bin/CheckAccount.ksh
#
# Version     : 1.1
#
# Author      : Gerard van Wageningen
#
# Description : Use ssh with no passphrase to check account for expiring 
#
# 1.0   First Version
# 1.1	Use 1 ssh command to add public keys
#

\whence set_debug 1>/dev/null 2>&1 && eval $( set_debug ${0##*/} )

typeset OUTPUT=''
typeset HOST=''
typeset identity_check_pub=''
typeset id_rsa_check_pub=''
typeset id_dsa_check_pub=''

# crontab -e:
# 30 06 * * * ${HOME}/bin/CheckAccount.ksh

if (( $# == 1 ))
then
  print "$1" >> "${HOME}/.CheckAccountrc"
  sort -u "${HOME}/.CheckAccountrc" > "${HOME}/.CheckAccountrc.$$"
  mv "${HOME}/.CheckAccountrc.$$" "${HOME}/.CheckAccountrc"
  HOST="$1"
else
  # Create the host file if not present
  if [[ ! -r "${HOME}/.CheckAccountrc" ]]
  then
    print "${HOSTNAME:-$( hostname )}" > "${HOME}/.CheckAccountrc"
    HOST="${HOSTNAME:-$( hostname )}"
  fi
fi


# Generate the public and private keys
if [[ ! -r "${HOME}/.ssh/identity.check" ]]
then
  ssh-keygen -N '' -t rsa1 -C ${LOGNAME:-${USER}}.${HOSTNAME:-$( hostname )}.check -f ${HOME}/.ssh/identity.check
fi
if [[ ! -r "${HOME}/.ssh/id_rsa.check" ]]
then
  ssh-keygen -N '' -t rsa  -C ${LOGNAME:-${USER}}.${HOSTNAME:-$( hostname )}.check -f ${HOME}/.ssh/id_rsa.check
fi
if [[ ! -r "${HOME}/.ssh/id_dsa.check" ]]
then
  ssh-keygen -N '' -t dsa  -C ${LOGNAME:-${USER}}.${HOSTNAME:-$( hostname )}.check -f ${HOME}/.ssh/id_dsa.check
fi

# Distribute the public keys
if [[ -n "${HOST}" ]]
then
  identity_check_pub="$( < ${HOME}/.ssh/identity.check.pub )"
  id_rsa_check_pub="$(   < ${HOME}/.ssh/id_rsa.check.pub )"
  id_dsa_check_pub="$(   < ${HOME}/.ssh/id_dsa.check.pub )"

  \ssh "${HOST}" "\
    mkdir .ssh 2>/dev/null
    chmod 700 .ssh
    grep -v ${LOGNAME:-${USER}}.${HOSTNAME:-$( hostname )}.check .ssh/authorized_keys  > .ssh/authorized_keys.$$
    mv .ssh/authorized_keys.$$ .ssh/authorized_keys
    grep -v ${LOGNAME:-${USER}}.${HOSTNAME:-$( hostname )}.check .ssh/authorized_keys2 > .ssh/authorized_keys2.$$
    mv .ssh/authorized_keys2.$$ .ssh/authorized_keys2
    echo '${identity_check_pub}' >> .ssh/authorized_keys
    echo '${id_rsa_check_pub}'   >> .ssh/authorized_keys2
    echo '${id_dsa_check_pub}'   >> .ssh/authorized_keys2"
fi

for HOST in $( < "${HOME}/.CheckAccountrc" )
do

  OUTPUT=$( \ssh -i ${HOME}/.ssh/id_dsa.check -i ${HOME}/.ssh/id_rsa.check -i ${HOME}/.ssh/identity.check ${HOST} /bin/echo "\\\c" 2>&1 )
  if (( $? != 0 ))
  then
    print "::::::::::::::::::::\n${HOST}\n::::::::::::::::::::"
    print "${OUTPUT}"
  fi

done

exit 0 

################# EOF #################
