#!/bin/bash

db_host=`jtconf roundcubemail.db_server`	|| exit $?
db_name=`jtconf roundcubemail.db_name`		|| exit $?
db_user=`jtconf roundcubemail.db_user`		|| exit $?
db_pass=`jtconf roundcubemail.db_password`	|| exit $?

min_uid=`jtconf ldap.starting_uid`		|| exit $?

customer=`jtconf customer.name`			|| exit $?

tmpsql=/tmp/sql.tmp

SQL()
{
	echo "$@" | mysql -N --batch --host $db_host --database=$db_name --user=$db_user --password=$db_pass | \
		sed -e 's/|/ESCPIPE/g' -e 's/	/|/g'
}


getent passwd | while read pass
do
	user=`	echo "$pass" | cut -d':' -f1`
	uid=`	echo "$pass" | cut -d':' -f3`
	name=`	echo "$pass" | cut -d':' -f5`
	home=`	echo "$pass" | cut -d':' -f6`

	[ $uid -lt $min_uid ] && continue

	echo "  checking user: $user"

	r_userid=`SQL "select user_id from users where username ='$user';"`

	[ "$r_userid" ] || continue

	fullname=`echo $name | tr A-Z a-z | tr ' ' '.'`

	for row in `SQL "select identity_id,name,email,signature from identities
				where user_id =$r_userid;"`
	do
		r_id=`echo "$row" | cut -d'|' -f1`
		r_name=`echo "$row" | cut -d'|' -f2`
		r_email=`echo "$row" | cut -d'|' -f3`
		r_sig=`echo "$row" | cut -d'|' -f4`

		r_email_user=`echo $r_email | sed -e 's/@.*//'`
		r_email_domain=`echo $r_email | sed -e 's/.*@//'`


		echo "id=$r_id name=$r_name email=$r_email sig=$r_sig"

		[ "$r_name" = "$user" ] 	&& r_name="$name"
		[ "$r_email_user" = "$user" ]	&& r_email="$fullname@$r_email_domain"
		[ "$r_sig" = "" ] 		&& r_sig="$customer - $name"

		echo "id=$r_id name=$r_name email=$r_email sig=$r_sig"

		continue

		SQL "udpate identities
			set name='$r_name',
			set email='$r_email',
			set signature='$r_sig'
			where identity_id = $r_id
			limit 1;
		"
	done
done
