#!/bin/sh
# Copyright (c) 2000-2012 Synology Inc. All rights reserved.

PKG_DIR="Joomla_2.5.6"
SITES_ENABLED_USER_DIR="/usr/syno/etc/sites-enabled-user"
JOOMLA_APACHE_CONF="/var/packages/Joomla/target/$PKG_DIR/etc/SYNO.SDS.Joomla.conf"
ApacheUserScript="/usr/syno/etc/rc.d/S97apache-user.sh"

if [ -d $SITES_ENABLED_USER_DIR ]; then
	cp -f $JOOMLA_APACHE_CONF $SITES_ENABLED_USER_DIR
	$ApacheUserScript restart > /dev/null 2>&1
fi

/bin/rm -rf /var/services/web/joomla
/bin/mv /var/packages/Joomla/target/$PKG_DIR /var/services/web/joomla


[ "$SYNOPKG_PKG_STATUS" = "UPGRADE" ] && exit 0


# Get path of data of previous installation
[ -f "/var/packages/.joomla.conf" ] || exit 0
TEMP_PATH=`grep ^path= /var/packages/.joomla.conf | cut -d'"' -f2`

# Get DB name and password of previous installation
[ -f "$TEMP_PATH/$PKG_DIR/configuration.php" ] || exit 0
DB_NAME=`grep 'public \$db =' $TEMP_PATH/$PKG_DIR/configuration.php | cut -d"'" -f2`
DB_PASSWORD=`grep 'public \$password =' $TEMP_PATH/$PKG_DIR/configuration.php | cut -d"'" -f2`

# Recover data of previous installation and remove installation folder if DB exists and password is valid
/usr/syno/mysql/bin/mysql -u root --password="$DB_PASSWORD" -e "show databases" 2> /dev/null | grep ^$DB_NAME$
if [ $? -eq 0 ]; then
	cp -rf $TEMP_PATH/$PKG_DIR/* /var/services/web/joomla/
	rm -rf /var/services/web/joomla/installation /var/services/web/joomla/joomla.xml
	chown -R nobody:nobody /var/services/web/joomla
	rm -rf $TEMP_PATH/$PKG_DIR /var/packages/.joomla.conf
fi

exit 0
