#!/bin/sh
#
# Copy 1 address book (master) to 1 or more client (one way copy)
#	Guillaume DURR
#	g.durr.removethis@free.fr
#
#		30 dec 04			0.1 			first release
#
#
###############################		Configure		###################################
# ftp server must be "on" on each client
#on client 1
user1=user_short_name
pasword1=something
ip1=192.168.1.100
name1="John"
lastname1="Doe"

#on other client, if they
user2=
pasword2=
ip2=
name2=
lastename2=
# ...
##########

#On the server, the call will be
#		save_address_book.sh master

#on the client(s)
#		save_address_book.sh slave

#You can user a crontab to launch each script, with first the master script, and a few seconds after the slave script
#Don not forget to chmod x this script on the client

# ... or a one command : 
#save_address_book.sh master;ssh $user1@$ip1 "chmod a+x <path_to>/save.address_book.sh && <path_to>/save.address_book.sh slave"

################################################################################


if [ -z $1 ]; then
	echo "Usage is : `basename $0` master | slave"
	exit
fi

if [ $1 == "master" ]; then
	cd $HOME/Library/Application\ Support/AddressBook/
	tar -cvf /tmp/ab.tar ./*
	curl -T /tmp/ab.tar "ftp://$user1:$pasword1@$ip1/Library/TEMP_AB/"
	rm /tmp/ab.tar
	
	
	curl -T "$0" "ftp://$user1:$pasword1@$ip1/Library/`basename $0`"

fi


if [ $1 == "slave" ]; then
	#check if the temp folder exists on client
	if [ ! -d ~/Library/TEMP_AB/ ]; then
		mkdir ~/Library/TEMP_AB/
	fi
	
	cd $HOME/Library/TEMP_AB
	
	if [ ! -f ab.tar ]; then 
		exit
	fi
	
	tar -xf ab.tar 
	rm ab.tar
	ab=`ps -acx | grep "Address Book"`

	if [ -n "$ab" ]; then
		kill -3 `echo $ab | awk '{print $1}'`
		was_opened=true
	fi
	cp * $HOME/Library/Application\ Support/AddressBook/
	rm -R ./*
	osascript -e "tell application \"Address Book\" to set my card to people whose first name is \"$name1\" and last name is \"$lastname1\"" 
	
	if [ $was_opened ]; then
		open -a /Applications/Address\ Book.app/
	else
		osascript -e 'tell application "Address Book" to quit'
	fi
fi
