#!/bin/bash

. ${TOOLKIT}-functions.sh

module="roundcubemail"

repo=`jtconf install.mirror_downloaded`	|| exit_missing_define "install.mirror_downloaded"

release=`jtconf $module.version`	|| exit_missing_define "$module.version"
tarfile=`jtconf $module.tarfile`	|| exit_missing_define "$module.tarfile"
instdir=`jtconf $module.instdir`	|| exit_missing_define "$module.instdir"


releasefile="$instdir/.release"
current_release=
tardir="$module-$release"

user=$(jtconf apache.user)
group=$(jtconf apache.group)
owner="$user:$group"


here=`pwd`


# check the installed version
#
[ -f $releasefile ] && current_release=`cat $releasefile`

cd $RUNDIR

[ "$current_release" != $release ] && {	# not installed or neeed upgrade
	rm -f $tarfile
	wgetfile $repo/$module/$tarfile

	echo -e "  extracting files ..."
	tar xfpz $tarfile

	[ -d $tardir ] || {
		echo "  ERROR: can't find '$tardir' dir in $tarfile"
		exit 1
	}
	[ -d $tardir/vendor ] || {
		echo "  ERROR: can't find '$tardir/vendor' dir in $tarfile"
		exit 1
	}

	if [ "$current_release" != "" ] 
	then
		echo "  upgrading $instdir $current_release -> $release ..."
		cd $tardir
		./bin/installto.sh $instdir
	else
		echo -n "  installing $module $release -> $instdir ... "
		(cd $tardir; find . | cpio -pdum $instdir/)
	fi
}

# save current release
echo "$release" >$releasefile


# cleanup and fix install dir perms (always)
#
rm -rf $instdir/composer* $instdir/installer
chown -R $owner $instdir
find $instdir -type f -exec chmod 440 {} \;
find $instdir -type d -exec chmod 2770 {} \;

# config directories/files are moved to /etc and symlinked here
#
updatelink /etc/$module/config.inc.php $instdir/config/config.inc.php

for plugin in managesieve
do
	updatelink \
		/etc/$module/plugins/$plugin/config.inc.php \
		$instdir/plugins/$plugin/config.inc.php
done



# populate mysql db if needed
#
db_server=`jtconf roundcubemail.db_server`
db_name=`jtconf roundcubemail.db_name`
db_user=`jtconf roundcubemail.db_user`
db_password=`jtconf roundcubemail.db_password`

sqlfile="$instdir/SQL/mysql.initial.sql"

run_sql()
{
	echo "  running: mysql --host $db_server --database $db_name --user $db_user -p*******" "$@" >&2
	mysql --host $db_server --database $db_name --user $db_user -p$db_password "$@"
}

if [ "`which mysql`" != "" ]
then
	echo "select * from users;" | run_sql >/dev/null 2>/dev/null || {
		echo "  setting up database '$db_name' on '$db_server'"
		echo "    (using $sqlfile)"
		run_sql <$sqlfile || {
			echo -e "\n  hint: you must create user and database in advance\n" >&2
			exit 1
		}
	}
else
	putwarning "ROUNDCUBE DB CHECK" \
		"I don't have 'mysql' installed at this stage and can't check/create" \
		"db, install one of 'srv-mysql' or 'cli-mysql' modules and relaunch" \
		"'kusa -f srv-webmail' to finish the installation"
fi

$SOMETHING_CHANGED && {
	restart_service apache2 apache2
}

exit 0
