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

PKG_DIR="Joomla"
JOOMLA_UPDATE_DIR="/var/services/web/joomla/update_source/"

# Get DSM Version
[ -f "/etc.defaults/VERSION" ] || exit 1
DSM_VERSION=`grep ^majorversion= /etc.defaults/VERSION | cut -d'"' -f2`
[ -z "$DSM_VERSION" ] && exit 1

# Create conf folder and write conf/PKG_DEPS for MariaDB
mkdir -p /var/packages/Joomla/conf
cat > /var/packages/Joomla/conf/PKG_DEPS << EOF
[MariaDB]
dsm_min_ver=5.0-4300
EOF

# Link mariadb hook
mkdir -p /usr/local/libexec/mariadb_chpw
ln -sf /var/packages/Joomla/scripts/hooks/mariadb_chpw /usr/local/libexec/mariadb_chpw/Joomla


/bin/rm -rf /var/services/web/joomla
/bin/mv /var/packages/Joomla/target/$PKG_DIR /var/services/web/joomla
chown -R 1023:1023 /var/services/web/joomla

# 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
HAS_ONE=""
# Joomla 2.5.4 and 2.5.6 may have separate directory, we only need to get one to upgrade.
for i in $TEMP_PATH/*/configuration.php;
do
	DB_NAME=`grep 'public \$db =' $i | cut -d"'" -f2`
	DB_PASSWORD=`grep 'public \$password =' $i | cut -d"'" -f2`
	HAS_ONE="true"
	BACKUP_DIR=`dirname $i`
done
[ "$HAS_ONE" ] || exit 0

# Recover data of previous installation and remove installation folder if DB exists and password is valid
if [ "$DSM_VERSION" -eq "4" ]; then
	MYSQL="/usr/syno/mysql/bin/mysql"
else
	MYSQL="/usr/bin/mysql"
fi
$MYSQL -u root --password="$DB_PASSWORD" -e "show databases" 2> /dev/null | grep ^$DB_NAME$

if [ $? -eq 0 ] || [ "$SYNOPKG_PKG_STATUS" = "UPGRADE" ]; then
	# Possible directory name are Joomla_2.5.6(0010) and Joomla(0011)
	cp -rf $BACKUP_DIR/* /var/services/web/joomla/
	rm -rf /var/services/web/joomla/installation /var/services/web/joomla/joomla.xml
	chown -R 1023:1023 /var/services/web/joomla
	rm -rf $BACKUP_DIR /var/packages/.joomla.conf
fi

#Joomla 3.0 need to install Update package to compatible previous version
/usr/bin/php -e /var/services/web/joomla/Update.php $JOOMLA_UPDATE_DIR
rm -rf $JOOMLA_UPDATE_DIR
rm /var/services/web/joomla/Update.php

exit 0
