#!/bin/sh
#
# 2011 Aurélien Bondis  aurelien.bondis AT gmail DOT com
#
# This file is part of cdist.
#
# cdist is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cdist is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cdist. If not, see <http://www.gnu.org/licenses/>.
#
#
# This type allows to send a public ssh key from a user to the
# authorized_keys of another
#
#require="__package openssh-server --state installed"
# Get option srcuser if defined
if [ -f "$__object/parameter/srcuser" ]; then
   srcuser=`cat "$__object/parameter/srcuser"`
fi
# Get option dstuser if defined
if [ -f "$__object/parameter/dstuser" ]; then
   dstuser=`cat "$__object/parameter/dstuser"`
fi

# if a source user is defined, use it's public key
if [ "$srcuser" ]; then
   srcrsa="/home/${srcuser}/.ssh/id_rsa.pub"
# if no source user is defined we use root's public key
else
   srcrsa="/root/.ssh/id_rsa.pub"
fi
# if a destination user is defined, insert in it's authorized_keys
if [ "$dstuser" ]; then
   sshpath="/home/$dstuser/.ssh"
# if no destination user is defined we use root's home
else
   sshpath="/root/.ssh"
fi
rsa=`cat $srcrsa`
__directory $sshpath
# the file authorized_keys depends on the .ssh folder
require="__directory${sshpath}" __file "$sshpath/authorized_keys" --mode 640
# the line added depends on authorized_keys existence
require="__file${sshpath}/authorized_keys" __addifnosuchline sshkey --file \
 "$sshpath/authorized_keys" --line "$rsa"

