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

WPDIR="/var/packages/WordPress/target/src"
WPWEBDIR="/var/services/web/wordpress"

tmp_path=/$(readlink /var/packages/WordPress/target|cut -d/ -f 2)/@tmp

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

if [ $DSM_VERSION -le 4 ]; then
	MYSQL="/usr/syno/mysql/bin/mysql"
else
	MYSQL="/usr/bin/mysql"
fi

# Official upgrade procedure of WordPress
# Please refer to
# https://codex.wordpress.org/Updating_WordPress

# Clean old source code
/bin/mv  ${WPWEBDIR}/index.php /tmp/wp_temp
/bin/rm -rf ${WPWEBDIR}/wp-includes/
/bin/rm -rf ${WPWEBDIR}/wp-admin/
/bin/mv -f ${WPDIR}/* ${WPWEBDIR}
/bin/mv /tmp/wp_temp ${WPWEBDIR}/index.php

# Restore user data
/bin/cp -a ${tmp_path}/wordpress/wp-content/* ${WPWEBDIR}/wp-content/.
/bin/cp -a ${tmp_path}/wordpress/wp-config.php ${WPWEBDIR}/.
/bin/rm -rf ${tmp_path}/wordpress

# Remove html files which cause DOM XSS if existed
/bin/rm -f ${WPWEBDIR}/wp-content/themes/twentythirteen/genericons/example.html
/bin/rm -f ${WPWEBDIR}/wp-content/themes/twentyfourteen/genericons/example.html
/bin/rm -f ${WPWEBDIR}/wp-content/themes/twentyfifteen/genericons/example.html

echo $pkgwizard_mysql_password > $$
pkgwizard_mysql_password=`sed 's/"/\\"/gp' $$`
/bin/rm -f $$
$MYSQL -u root --password="${pkgwizard_mysql_password}" -e "create database if not exists wordpressblog"; 

rm -f /tmp/WordPress.upgrade
exit 0
