#!/bin/bash

# Jose A. Herran <jherran at kedesfase dot com>
# Script to insert Evolution contacts into RC contacts.
#
# RC contact format:
#	Display name	
#	First name	
#	Last name	
#	E-Mail

# Database settings.
db=your_database
us=your_database_user
pw=your_database_password
user_email=dummy@kedesfase.com
# path where list.vcf is
list_path='./'

cat $list_path'list.vcf' | while read line
do
	field=`echo $line | cut -d: -f1`
	content=`echo $line | cut -d: -f2`
	#echo $field
	#echo $content
	#echo $line
	if [[ -n $content && -n $field ]]
	then
		if [ $field == "FN" ]
		then
			echo $content
			display=$content
		fi
		if [[ $field == "X-EVOLUTION-FILE-AS" && $display == "" ]]
		then
			echo $content
			display=$content
		fi
		if [ $field == "N" ]
		then
			last=`echo $content | cut -d';' -f1 -s`
			first=`echo $content | cut -d';' -f2 -s`
			middle=`echo $content | cut -d';' -f3 -s`
			echo $first $middle $last
		fi
		if [[ $field == "EMAIL;TYPE=HOME;X-EVOLUTION-UI-SLOT=1" || $field == "EMAIL;TYPE=HOME;X-EVOLUTION-UI-SLOT=2" || $field == "EMAIL;TYPE=WORK;X-EVOLUTION-UI-SLOT=1" || $field == "EMAIL;TYPE=WORK;X-EVOLUTION-UI-SLOT=2" ]]
		then
			email=`echo $content`
			echo $email
		fi
		if [ $field == "END" ]
		then
			mysql $db -u $us --password=$pw -e "insert into contacts (contact_id, changed, del, name, email, firstname, surname, vcard, user_id) select 0, CURRENT_TIMESTAMP, 0, left('$display', char_length('$display')-1), left('$email', char_length('$email')-1), '$first', '$last', '', min(user_id) from users where username = '$user_email'"
			display=''
			last=''
			first=''
			middle=''
			email=''
		fi
	fi
done


