#!/bin/sh
# -*- mode: shell-script; coding: utf-8 -*-
#
# elho-install-sshkey
#
# Script to install SSH authorized keys file granting me access.
#
# Copyright (C) 2010 Elmar Hoffmann
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#

set -e

IDENTITY__FILE_PATH='/usr/share/elho/ssh'
USER_IDENTITY_FILE="${IDENTITY__FILE_PATH}/id_rsa.pub"
ROOT_IDENTITY_FILE="${IDENTITY__FILE_PATH}/id_rsa_root.pub"

AUTORIZED_KEYS_FILE="${HOME}/.ssh/authorized_keys"

ROOT_HOME=$(getent passwd root | cut --delimiter=':' --field=6)

if [ -z "${ROOT_HOME}" ]; then
    echo "Error: Unable to determine home directory of root user!" >&2
    exit 1
fi

install --mode=2700 --directory "${HOME}/.ssh"

if [ "${HOME}" = "${ROOT_HOME}" ]; then
    IDENTITY_FILE="${ROOT_IDENTITY_FILE}"
else
    IDENTITY_FILE="${USER_IDENTITY_FILE}"
fi

echo -e "Do you really want to overwrite '${AUTORIZED_KEYS_FILE}'" \
    " grantings\naccess to that account to the SSH kei with the following" \
    " fingerprint:\n"
ssh-keygen -l -f "${IDENTITY_FILE}"
echo -e -n "\nEnter uppercase yes to grant access: "

read answer
if [ "${answer}" = 'YES' ]; then
    echo 'Installing authorized keys file...'
    cp -i "${IDENTITY_FILE}" "${AUTORIZED_KEYS_FILE}"
else
    echo 'Not installing authorized keys file.'
    exit 0
fi
