#!/bin/sh
##
## Copyright (c) 2001-2003 Gregory M. Kurtzer
##
## Copyright (c) 2003-2012, The Regents of the University of California,
## through Lawrence Berkeley National Laboratory (subject to receipt of any
## required approvals from the U.S. Dept. of Energy).  All rights reserved.
##

_UID=`id -u`

_UID_MIN=`grep '^UID_MIN' /etc/login.defs 2>/dev/null | tail -n 1 | awk '{print $2;}'`
if [ -z "$_UID_MIN" ]; then
    _UID_MIN=500
fi

if [ $_UID -lt "$_UID_MIN" -a $_UID -ne 0 ]; then
    exit
fi


if [ ! -f "$HOME/.ssh/config" ] && [ ! -f "$HOME/.ssh/cluster" ]; then
    echo "Configuring SSH for cluster access"
    install -d -m 700 $HOME/.ssh
    ssh-keygen -t rsa -f $HOME/.ssh/cluster -N '' -C "Warewulf Cluster key" > /dev/null 2>&1
    if [ -f $HOME/.ssh/authorized_keys ] && [ ! -w $HOME/.ssh/authorized_keys ]; then
      echo "[INFO] Making $HOME/.ssh/authorized_keys writable by user"
      touch $HOME/.ssh/authorized_keys
      chmod 0600 $HOME/.ssh/authorized_keys
    fi
    cat $HOME/.ssh/cluster.pub >> $HOME/.ssh/authorized_keys
    # If authorized_keys didn't exist, we just created it... and the permissions could be off
    chmod 0600 $HOME/.ssh/authorized_keys

    echo "# Added by Warewulf  `date +%Y-%m-%d 2>/dev/null`" >> $HOME/.ssh/config
    echo "Host *" >> $HOME/.ssh/config
    echo "   IdentityFile ~/.ssh/cluster" >> $HOME/.ssh/config
    echo "   StrictHostKeyChecking=no" >> $HOME/.ssh/config
    chmod 0600 $HOME/.ssh/config
fi

