#!/bin/bash

if [ $(id -u) -ne 0 ]; then
    echo "Script must be started as root!"
    exit 1
fi

users=$(getent group sudo | awk -F: '{print $4}' | sed "s/,/ /g")

TMP_FILE="root-keys.tmp"
ROOT_KEY_FILE="$(getent passwd root | awk -F: '{print $6}')/.ssh/authorized_keys"

# Ensure temporary file is empty and only writable by root
echo "" > $TMP_FILE
chown root:root $TMP_FILE

echo -ne "# File created at $(date) by root-keysync on $(hostname)!\n# Do NOT edit this file. To add keys for root only, add them to ${ROOT_KEY_FILE}_override!\n" >> $TMP_FILE

touch "${ROOT_KEY_FILE}_override"
echo -ne "\n\n#################################\n# Keys of root  (imported from ${ROOT_KEY_FILE}_override)\n#################################\n" >> $TMP_FILE
cat "${ROOT_KEY_FILE}_override" >> $TMP_FILE
echo "Added override-keys for root only"

# iterate over all users in the sudo-group
# add all their authorized_keys to root
for u in $users; do
    homedir=$(getent passwd $u | awk -F: '{print $6}')
    keyfile="$homedir/.ssh/authorized_keys"
    echo -ne "\n\n#################################\n# Keys of $u  (imported from $keyfile)\n#################################\n" >> $TMP_FILE
    cat $keyfile >> $TMP_FILE
    echo "Added user $u"

    # make sure the user can actually use the keyfile
    chown "$u" $keyfile
    chmod g-wx,o-wx,g+r,o+r $keyfile
done

# Copy new keyfile to roots location
mv $TMP_FILE $ROOT_KEY_FILE
chmod 444 $ROOT_KEY_FILE
echo "Replaced old key file!"

