#!/bin/sh
#
# This script should only run on the astium backup server.
# It creates the default config to backup an astium.
# A user is created for each Astium. 
# If a user already exists, the Astium's root user public key
# is allowed access to this users' directories.
#
# This script should be run twice.
#
# Perry 1-8-2007
#
#set -x

print_point()
{
   for (( i=0; i<2; i++ ))
   do
	sleep 1
        echo -en "."
   done
   echo ""
}

add_user()
{
   adduser $SERVERID -s /bin/bash > /dev/null 2>&1
   echo ""

   if [ $? -gt 0 ]
   then
      echo "User probably exists"
      echo -en "Exiting."
      print_point
      exit 1
   fi
}

display_comment()
{
   echo ""
   echo -en "\\033[1;31m" 
   echo "Run on the Astium (backup client)"
   echo -en "\\033[0;39m"
   echo "/usr/local/astium/sbin/astium-backup-activate"
   echo -en "\\033[1;31m" 
   echo "Then on the backup server"
   echo -en "\\033[0;39m"	
   echo "/usr/local/astium/sbin/new-backupastium"
}

end_proces()
{
   # Create .ssh directory if it does not exists yet.
   if [ ! -d /home/$SERVERID/.ssh ]
   then
   	mkdir /home/$SERVERID/.ssh
   fi

   # If the .ssh directory exists, set the correct permissions.
   if [ -d /home/$SERVERID/.ssh ]
   then
   	chown -R $SERVERID:$SERVERID /home/$SERVERID/.ssh
	chmod 700 /home/$SERVERID/.ssh
   fi 	

   #set permissions
   if [ -f /home/$SERVERID/.ssh/authorized_keys ]
   then	
   	chmod 400 /home/$SERVERID/.ssh/authorized_keys    
   fi

   if [ -f /home/$SERVERID/.ssh/authorized_keys2 ]
   then	
   	chmod 400 /home/$SERVERID/.ssh/authorized_keys2    
   fi 

   echo ""
   echo -en "Done exiting."
   print_point
   echo ""
}

echo ""
echo "This scripts creates the backup config for an Astium"
echo ""
echo "Please give the astium id : 10116"
echo -en "Astium Server ID="
read SERVERID

if [ ! -d /home/$SERVERID ]
then
	add_user
fi

if [ -f /home/backup/$SERVERID-authorized_keys2 -a -d /home/$SERVERID ]
then
	AUTHORIZED_KEYS="/home/$SERVERID/.ssh/authorized_keys2"

	if [ -f $AUTHORIZED_KEYS ]	
	then
		cp -f $AUTHORIZED_KEYS $AUTHORIZED_KEYS.new
	else 
		mkdir -p "/home/$SERVERID/.ssh"
	fi

	cat /home/backup/$SERVERID-authorized_keys2 >> $AUTHORIZED_KEYS.new
	cat $AUTHORIZED_KEYS.new|sort|uniq > $AUTHORIZED_KEYS

	if [ -f $AUTHORIZED_KEYS.new ]
	then
		rm -f $AUTHORIZED_KEYS.new
	fi

	if [ -f /home/backup/$SERVERID-authorized_keys2 ]
	then
		rm -f /home/backup/$SERVERID-authorized_keys2
	fi
fi

end_proces

exit 0
