#!/bin/sh
#  This script replaces the old dsa skeleton key with a new rsa based one.

# Only run once
[ -n "${POST_UPGRADE_CACHE}" ] && touch "${POST_UPGRADE_CACHE}/`basename $0`"

KEYS=/root/.ssh/authorized_keys
NEWKEYS=/root/.ssh/newauthorized_keys

# We need to make sure that we don't trash any keys that are already there.
# If the file doesn't exist we can create a 0 length one to aid a user adding
# a key.
if [ ! -e $KEYS ]
then
	echo " * Creating empty $KEYS file"
	touch $KEYS
	exit 0
fi

# If the file exists but is 0 length then we should leave well alone because
# it means that it has been cleaned out by a user so we shouldn't add a new one.
if [ ! -s $KEYS ]
then
	exit 0
fi

# Need to check this key is not already there
count=$(grep -c '^ssh-rsa.*skeleton@guralp.com' $KEYS)
if [ $count -gt 0 ]
then
	# Already there so exit
	exit 0
fi

count=$(grep -c '^ssh-dss AAAAB3NzaC1kc3.*a9RpB6K0fL skeleton@guralp.com' $KEYS)
if [ $count -eq 0 ]
then
	# No DSA key - don't add RSA one"
	exit 0
fi

# If we get to here there is a DSA skeleton key which we need to replace with the new one.
cat $KEYS | sed -e '/^ssh-dss AAAAB3NzaC1kc3.*a9RpB6K0fL skeleton@guralp.com/d' > $NEWKEYS


cat << EOF >> $NEWKEYS
# Added by 4031-skeleton-key.sh `date`
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDgOymmtOXn0WuBSFf3J33fT8ff+zBo+QlqnCY02PAmaJEJC47tb1CkB6TI1EYRpQ0oRHs0fx4fUWd5pzhl3lvnS4p4EM+ZNoBV3MbYLBHulNUqGvbIJH82vX6DIvSXB+PnBMy2Tu8ProCTrrf41j/ALAR3zZD8ubw37UtYLRXNYsRA8VAdLP4WXPK9n13+G++Il6TlmaeYc1a6dMUq1qS1wAhZFEMy5B8C17jdyPBOTjMREQAjyu/FJR3Q/jfMRhvIU6HuUueaXIUzX6q0eZtmYId4G63UgzdN2ymD/HUTKfv3R3wGegzr6Jr0Hr9GOgLc9ar6jbO8VtYAO/G/Oc+t skeleton@guralp.com
EOF

mv $NEWKEYS $KEYS

echo " * Changed DSA skeleton key for RSA in $KEYS file"
exit 0
