#!/bin/sh
#
# This script should only run on the neonova backup server.
# It creates the default config to backup an neonova.
# A user is created for each Neonova. 
# If a user already exists, the Neonova'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
   #cp -f /etc/skel/.bash_profile_exit /home/$SERVERID/.bash_profile
   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 backup client"
   echo -en "\\033[0;39m"
   echo "/usr/local/neonova/sbin/neonova-backup-activate"
   echo -en "\\033[1;31m" 
   echo "Then on the backup server"
   echo -en "\\033[0;39m"	
   echo "/usr/local/neonova/sbin/new-backupclient"
}

end_proces()
{
   if [ ! -d /home/$SERVERID/.ssh ]
   then
   	mkdir /home/$SERVERID/.ssh
   	chown $SERVERID:$SERVERID /home/$SERVERID/.ssh
   fi

   mkdir -p /home/$SERVERID/upload/databases
   mkdir -p /home/$SERVERID/upload/data

   #set permissions
   chmod 700 -R /home/$SERVERID                      
   #chmod 700 /home/$SERVERID/.bash*                 
   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 
	
   chown -R $SERVERID:$SERVERID /home/$SERVERID 

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

echo ""
echo "This scripts creates the backup config for an Neonova"
echo ""
echo "Please give the neonova id : 10116"
echo -en "Neonova 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
