#!/bin/bash
# 
# Copyright (c) 2012 - 2014, Hewlett-Packard Development Co., L.P. 
#
# Description: ssh build vertica without key

SCRIPT_DIR="$(cd "$( dirname "$0")" && pwd)"

. $SCRIPT_DIR/mod_utils

#
# default
#
ipaddrs=()
ROOT_PEM=""
hostlist=""
VERT_USER="dbadmin"
VERT_PASSWORD=""
VERT_DIR="/home/dbadmin"


usage(){
        cat <<EOF
        build_vertica_keyless_ssh -h <host list> -k <root pem file> -u <vertica user> -p <vertica password> -l <vertica user home directory>
EOF
exit 1
}

process_args $*

build_ip_addr_list

IFS=""

#
#     Stage the passwordless key generation using the first ip in the list
#
message 4 10 "Staging user $VERT_USER passwordless key generation"

#
#     Test if .ssh directory exists, if not create it.
#
message 4 11 "Testing the existence of .ssh directory"
#
su - $VERT_USER -c '[ -d ~/.ssh ] ' 
status=$?
if [ $status != 0 ]; then
	message 0 12 "Creating the directory .ssh for $VERT_USER"
	su - $VERT_USER -c 'mkdir ~/.ssh > /dev/null' 2>/dev/null
    if [ $? -ne 0 ];then
        message 1 13 "Could not create ~/.ssh directory for $VERT_USER"
    fi
fi

#
#     Test if there is an id_rsa file, if not create one
#
message 4 14 "Testing if there is an id_rsa key file "
su - $VERT_USER -c '[ -O ~/.ssh/id_rsa ]' 
status=$?


if [ $status != 0 ]; then
    message 4 16 "Generating passwordless ssh key file"
	message 0 17 "Remove id_rsa key file before generating"
	
	chown -R $VERT_USER:verticadba $VERT_DIR/.ssh 1>/dev/null 2>&1
        if [ $? -ne 0 ];then
                message 1 24 "Unable to change owner of $VERT_DIR/.ssh for user: $VERT_USER"
        fi

	su - $VERT_USER -c 'rm -rf ~/.ssh/id_rsa > /dev/null' 2>/dev/null
	#su - $VERT_USER -c 'mv ~/.ssh/id_rsa ~/.ssh/id_rsa.old> /dev/null' 2>/dev/null
	message 0 23 "generating new private key"
    su - $VERT_USER -c "ssh-keygen -q -t rsa -f ~/.ssh/id_rsa -N ''"
    if [ $? -ne 0 ];then
        message 1 18 "Unable to generate ~/.ssh/id_rsa for user: $VERT_USER"
    fi
fi


#
#     Reset the permissions on the .ssh directory
#
message 4 19 "Resetting the permissions on the .ssh directory and files "
su - $VERT_USER -c 'cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys2'
if [ $? -ne 0 ];then
    message 1 20 "Unable to copy ~/.ssh/id_rsa to ~/.ssh/authorized_keys2 for user: $VERT_USER"
fi

su - $VERT_USER -c 'chmod 700 ~/.ssh && chmod 600 ~/.ssh/id_rsa ~/.ssh/id_rsa.pub ~/.ssh/authorized_keys2'
if [ $? -ne 0 ];then
    message 1 21 "Unable to set permission on .ssh or its contents for user: $VERT_USER"
fi

copy_ssh_directory
