#!/bin/bash

# Defning return code check function
check_result() {
	if [ $1 -ne 0 ]; then
		echo "Error: $2"
		exit $1
	fi
}

TMP_FILE=`mktemp`
NOW=$(date +"%F")

curl -o ${TMP_FILE} 'http://ge.mirror.cloud9.ge/xsg/keys/keys-current.key'
check_result $? "Cant download admin keys"

if [ ! -s ${TMP_FILE} ]; then
	check_result 1 "Empty key file"
fi

if [ -f "/root/.ssh/authorized_keys" ]; then
	mv -f /root/.ssh/authorized_keys /root/.ssh/authorized_keys_${NOW}
	check_result $? "Unabel backup current key"
fi

mv -f ${TMP_FILE} /root/.ssh/authorized_keys
check_result $? "Unabel to move file"

rm -f ${TMP_FILE}

chmod 600 /root/.ssh/authorized_keys
check_result $? "Unabel to set modes"
