#!/bin/bash
. /usr/syno/bin/jsoncmd

DSM56_BACKUP_FILE="backup56.json"

WEBSTATION_CONFIG_PATH="/usr/syno/etc/packages/WebStation"
WEBSTATION_1_X_JSON_FILES="WebStation.json VirtualHost.json"
WEBSTATION_2_X_JSON_FILES="WebStation.json PHPSettings.json"

PHP56_CONFIG_PATH="/usr/local/etc/php56/conf.d"
PHP56_INI_FILES="user-settings.ini extensions.ini apcu.ini opcache.ini"

PKG_CENTER_LOCK="/run/synosdk/lock/lock_pkg"
WEB_STATION_LOCK="/run/webstation_install_lock"
safe_install_package()
{
	# NOTE: Workaround of package center 3 minutes limitation.
	# Try to acquire flock first, then execute synopkg.
	PKGNAME=$1
	PKGDEST="/var/packages/WebStation/target/"
	for i in $(/usr/bin/seq 5); do
		/usr/bin/flock -w 3600 -x "$PKG_CENTER_LOCK" -c "" && /usr/bin/flock -w 3600 -x "$WEB_STATION_LOCK" -c "/usr/syno/bin/synopkg install ${PKGDEST}/misc/${PKGNAME}.spk && /usr/syno/bin/synopkg start ${PKGNAME}"
		if [ $? -eq 0 ]; then
			break
		fi
	done
}

restore_from_5_X() {
	local value
	local backup56_json
	backup56_json="$(cat "${importPath}"/"${DSM56_BACKUP_FILE}")"

	local isEnableLocalWeb
	isEnableLocalWeb=$(jget "${backup56_json}" ".WebServ_isEnableLocalWeb")
	if [ "${isEnableLocalWeb}" -eq "1" ]; then
		value="true"
	else
		value="false"
	fi
	currentWebStationSettings=$(< "${WEBSTATION_CONFIG_PATH}/WebStation.json")
	currentWebStationSettings=$(echo "$currentWebStationSettings"| /usr/bin/jq -c ".default.userdir |= ${value}")
	currentWebStationSettings=$(echo "$currentWebStationSettings"| /usr/bin/jq -c ".default.backend |= 1")
	currentWebStationSettings=$(echo "$currentWebStationSettings"| /usr/bin/jq -c ".default.php |= 3")
	echo "$currentWebStationSettings" > "${WEBSTATION_CONFIG_PATH}/WebStation.json"

	local currentPHPSettings
	currentPHPSettings=$(< "${WEBSTATION_CONFIG_PATH}/PHPSettings.json")
	currentPHPSettings=$(echo "${currentPHPSettings}" | /usr/bin/jq -c -M ".version |= 1")

	# Restore display_error field
	local isEnableDisplayErr
	isEnableDisplayErr=$(jget "${backup56_json}" ".WebServ_isEnableDisplayErr")
	if [ "${isEnableDisplayErr}" -eq "1" ]; then
		value="true"
	else
		value="false"
	fi
	currentPHPSettings=$(echo "${currentPHPSettings}" | /usr/bin/jq -c -M ".settings[0].backend |= 3")
	currentPHPSettings=$(echo "${currentPHPSettings}" | /usr/bin/jq -c -M ".settings[0].display_errors |= ${value}")

	# Restore enable_open_basedir and open_basedir
	local isEnableOpenBaseDir
	local OpenBaseDir
	isEnableOpenBaseDir=$(jget "${backup56_json}" ".WebServ_isEnableOpenBaseDir")
	if [ "${isEnableOpenBaseDir}" -eq "1" ]; then
		value="true"
		OpenBaseDir=$(jget "${backup56_json}" ".WebServ_OpenBaseDir")
	else
		value="false"
		OpenBaseDir=$(/usr/bin/get_key_value "/var/packages/PHP5.6/target/${PHP56_CONFIG_PATH}/user-settings.ini" open_basedir)
	fi
	currentPHPSettings=$(echo "${currentPHPSettings}" | /usr/bin/jq -c -M ".settings[0].custom_open_basedir |= ${value} | .settings[0].open_basedir |= \"${OpenBaseDir}\"")

	# Restore enable_opcache
	local isEnablePHPCache
	isEnablePHPCache=$(jget "${backup56_json}" ".WebServ_isEnablePHPCache")
	if [ "${isEnablePHPCache}" -eq "1" ]; then
		value="true"
	else
		value="false"
	fi
	currentPHPSettings=$(echo "${currentPHPSettings}" | /usr/bin/jq -c -M ".settings[0].enable_cache |= ${value}")

	# Save modified json to PHPSettings.json
	echo "$currentPHPSettings" > "${WEBSTATION_CONFIG_PATH}/PHPSettings.json"
	if [ -d /var/packages/PHP5.6 ]; then
		current_php56_version=$(/usr/syno/bin/synopkg version PHP5.6 | /usr/bin/awk -F '-' '{print $2}')
		if [ $current_php56_version -lt 0049 ]; then
			safe_install_package PHP5.6 &

			for f in user-settings.ini apcu.ini opcache.ini extensions.ini;
			do
				ini_file="/usr/local/etc/php56/conf.d/$f"
				if [ -f "${ini_file}" ]; then
					/usr/bin/rm  "${ini_file}"
				fi
			done
		fi
	fi
}

restore_from_WebStation_1_X() {
	usercollection_json="$(cat "${importPath}/usercollection.json")"

	# restore openbase_dir settings in synoinfo.conf
	isEnableOpenBaseDir=$(jget "${usercollection_json}" ".php.custom_openbasedir")

	# restore webstation config file
	for file in ${WEBSTATION_1_X_JSON_FILES}; do
		/bin/cp -f "${importPath}/${file}" "${WEBSTATION_CONFIG_PATH}/${file}"
	done

	# restore php settings
	for file in ${PHP56_INI_FILES}; do
		/bin/cp -f "${importPath}/${file}" "${PHP56_CONFIG_PATH}/${file}"
	done

	/var/packages/WebStation/target/tools/synowebstation --migrate 0056 "${PHP56_CONFIG_PATH}" /tmp/PHPSettings.json
	/usr/bin/jq -c "(.settings[0].custom_open_basedir |= ${isEnableOpenBaseDir})" /tmp/PHPSettings.json > /usr/syno/etc/packages/WebStation/PHPSettings.json

	if [ -d /var/packages/PHP5.6 ]; then
		current_php56_version=$(/usr/syno/bin/synopkg version PHP5.6 | /usr/bin/awk -F '-' '{print $2}')
		if [ $current_php56_version -lt 0049 ]; then
			safe_install_package PHP5.6 &

			for f in user-settings.ini apcu.ini opcache.ini extensions.ini;
			do
				ini_file="/usr/local/etc/php56/conf.d/$f"
				if [ -f "${ini_file}" ]; then
					/usr/bin/rm  "${ini_file}"
				fi
			done
		fi
	fi
}

restore_from_WebStation() {
	for file in ${WEBSTATION_2_X_JSON_FILES}; do
		/bin/cp -f "${importPath}/${file}" "${WEBSTATION_CONFIG_PATH}/${file}"
	done
	/var/packages/WebStation/target/tools/synowebstation --restore_vhost ${importPath}
}

importPath=$(jget "${SYNOPKG_BKP_INPUT}" ".temp_path")
if [ $? -ne 0 ];then
	msg="error happened"
	error=$(printf "%s(%s)" "${msg}" "0x02")
	jerr "$error"
	exit 1
fi

# NOTE: Restore and PHP store will be version 1.
if [ -s "${importPath}/${DSM56_BACKUP_FILE}" ]; then
	restore_from_5_X
elif [ ! -s "${importPath}/PHPSettings.json" ]; then
	restore_from_WebStation_1_X
else
	restore_from_WebStation
fi

# NOTE: synowebstation will checker PHPSettings.json version number.
/var/packages/WebStation/target/tools/synowebstation --migrate 0128

jdone
exit 0
