#!/bin/sh

if [ $# != 2 ]; then
    printf "Usage: $0 username group{name|id}\n"
    exit 1
fi
user_name=$1
group=$2

# FIXME: This is CentOS and FreeBSD scripts pasted together.  Consolidate
# the code more when there's time to thoroughly test.

case $(auto-ostype) in
FreeBSD)
    
    mkdir -p -m 0700 /home/$user_name/.ssh
    chown -Rh ${user_name}:$group /home/$user_name/.ssh
    if [ ! -e /home/$user_name/.ssh/id_rsa ] || \
	[ ! -e /home/$user_name/.ssh/id_rsa.pub ]; then
	su $user_name -c "ssh-keygen -f /home/$user_name/.ssh/id_rsa -N ''"
    fi
    file=/home/$user_name/.ssh/authorized_keys
    if [ ! -e $file ]; then
	cp -f /home/$user_name/.ssh/id_rsa.pub $file
	chown ${user_name}:$group $file
    fi
    ;;

RHEL)

    if [ ! -e /home/$user_name/.ssh ]; then
	mkdir -m 0700 /home/$user_name/.ssh
    fi
    
    chown -Rh $user_name /home/$user_name/.ssh
    
    # Generated by cluster-setup
    if [ ! -f /home/$user_name/.ssh/id_rsa ]; then
	su $user_name -c "ssh-keygen -f /home/$user_name/.ssh/id_rsa -N ''"
    fi
    
    if [ ! -f /home/$user_name/.ssh/authorized_keys ]; then
	cat /home/$user_name/.ssh/id_rsa.pub > /home/$user_name/.ssh/authorized_keys
	chmod 600 /home/$user_name/.ssh/authorized_keys
	chmod 600 /home/$user_name/.ssh/id_rsa
	chmod 644 /home/$user_name/.ssh/id_rsa.pub
    fi
    
    chown -Rh ${user_name}:$group /home/$user_name/.ssh
    ;;

*)
    printf "$0: Not supported on $(auto-ostype).\n"
    exit 1
    ;;

esac
