#!/bin/sh
# -*- mode: shell-script; coding: utf-8 -*-
#
# elho-install-sshkey
#
# Script to install SSH authorized keys file granting me access.
#
# Copyright (C) 2010,2011 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

. /lib/elho/shell-tools

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"

USERID=$(id --user)
REAL_HOME=$(getent passwd "${USERID}" | cut --delimiter=':' --field=6)

if [ -z "${REAL_HOME}" ]; then
    error "Unable to determine your real home directory!"
    exit 1
fi

if [ ! -d "${REAL_HOME}" ]; then
    error "Your real home directory '${REAL_HOME}' does not exist!"
    exit 1
fi

if [ "${HOME}" != "${REAL_HOME}" ]; then
    warn "Current value of \$HOME does not match your real home directory!"
fi

SSH_DOTDIR="${REAL_HOME}/.ssh"
AUTORIZED_KEYS_FILE="${SSH_DOTDIR}/authorized_keys"

install --mode=2700 --directory "${SSH_DOTDIR}"

if [ "${USERID}" -eq 0 ]; then
    IDENTITY_FILE="${ROOT_IDENTITY_FILE}"
else
    IDENTITY_FILE="${USER_IDENTITY_FILE}"
fi

if [ ! -r "${IDENTITY_FILE}" ]; then
    error "Unable to read source identity file '${IDENTITY_FILE}'!"
    exit 1
fi

echo "Do you really want to install '${AUTORIZED_KEYS_FILE}', granting"
echo "access to your account to the SSH key with the following fingerprint:"
echo
ssh-keygen -l -f "${IDENTITY_FILE}"
printf "\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
