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

. `dirname $0`/common

SetMySQLPort()
{
	port="$1"
cat << EOF > "$MY_PORT_CNF_FILE"
# DO NOT EDIT THIS FILE !!!
# You can change the port on user interface of MariaDB.
# Please add other custom configuration to /var/packages/MariaDB/etc/my.cnf
[mysqld]
port=$port
[client]
port=$port
EOF
	"$BIN_SET_MYSQL_PORT" "$port"

	# workaround: avoid update port config worker fail
	[ ! -f "/usr/local/etc/services.d/MariaDB.sc" ] && /bin/cp "$PORT_CONFIG_FILE" "/usr/local/etc/services.d/MariaDB.sc"

	/usr/syno/sbin/synopkghelper update "$PACKAGE_NAME" port-config
}

DO_LINK
/bin/mkdir -p /usr/local/libexec/mariadb_chpw

# Check if /var/services/mysql exist (compatible with packages version before DSM5.2)
if [ -L /var/services/mysql ]; then
	mysqlPath=`readlink /var/services/mysql`
	/bin/rm -rf /var/services/mysql
fi

[ -n "${mysqlPath}" ] && /bin/ln -fs "${mysqlPath}" "${DATADIR}"

if [ "$pkgwizard_create" = true ]; then 
	ChkExecEnv
	mysqlPath=$(readlink "${DATADIR}")
	rm -rf "${mysqlPath}"
fi

if [ ! -z "$pkgwizard_port" ]; then 
#all new install
	port="$pkgwizard_port"
elif [ -f "$MY_PORT_CNF_FILE" ]; then
# upgrade, restore from old version > 1001, > 52
	port=$(/usr/syno/bin/get_section_key_value "$MY_PORT_CNF_FILE" mysqld port)
else
# upgrade, restore from old version <= 1001, <= 52
	port=3306
fi

SetMySQLPort "$port"

# Modify logrotate setting to correct log file
sed -i "s/mysqld.log/$(hostname).err/g" "${SYNOPKG_PKGDEST}/etc/logrotate.d/mysql"

RebuildDatabase

exit 0
