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

. `dirname $0`/string_loader
. `dirname $0`/common

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

CheckBeforeInstall() {
	#check moodle's link not exist
	if [ -e /var/services/web/moodle ]; then
		echo $err_path_exist >> $SYNOPKG_TEMP_LOGFILE
		exit 1
	fi

	if [ -z "$pkgwizard_db_name" ]; then
		echo $wizard_db_name_error > $SYNOPKG_TEMP_LOGFILE
		exit 1
	fi

	#check moodle's dataroot
	RESERVED_SHARE_NAMES="homes web video music audio photo netbackup surveillance"
	for name in $RESERVED_SHARE_NAMES
	do
		if [ `echo ${pkgwizard_dataroot} | awk '{ print toupper($0) }'` = `echo ${name} | awk '{ print toupper($0) }'` ]; then
			echo $share_name_is_reserved > $SYNOPKG_TEMP_LOGFILE
			exit 1
		fi
	done

	if [ -z "$pkgwizard_dataroot" ]; then
		echo $share_name_is_empty > $SYNOPKG_TEMP_LOGFILE
		exit 1
	fi
}

CreateSharedFolder() {
	/usr/syno/sbin/synoshare --get "$pkgwizard_dataroot"
	if [ $? -ne 0 ]; then
		VOLPATH=`servicetool --get-first-alive-volume`
		/usr/syno/sbin/synoshare --add "$pkgwizard_dataroot" "" "$VOLPATH/$pkgwizard_dataroot" "" "" "" 0 0

		if [ $SYNOPKG_DSM_VERSION_MAJOR -eq 5 ]; then
			/usr/syno/bin/synoacltool -add "$VOLPATH/$pkgwizard_dataroot"  user:http:allow:rwxpdDaARWc:fd
		fi
		echo "x_dataroot_x=$VOLPATH/$pkgwizard_dataroot" > /tmp/.MD_Install.tmp
	else
		# if get share correct, check if reserved conf in existed in this share
		MDDATA_PATH=`synoshare --get $pkgwizard_dataroot |grep Path|cut -d'[' -f2|cut -d']' -f1`
		# if share exist and Synology_Moodle.conf not exist in this share, that is mean this share is not Moodle share but share exist.
		# exit error and tell user share exist
		MD_BACKUP_CONFIG=$(FindMoodleBackupConf $MDDATA_PATH)
		if [ -n "$MD_BACKUP_CONFIG" ]; then
			MD_DATAROOT_BAK=`/bin/get_key_value $MD_BACKUP_CONFIG x_dataroot_x`
			if [ "$MD_DATAROOT_BAK" != "$MDDATA_PATH" ]; then
				echo $md_dataroot_exist > $SYNOPKG_TEMP_LOGFILE
				exit 1
			fi
			echo "x_dataroot_x=$MDDATA_PATH" > /tmp/.MD_Install.tmp
		else
			echo $md_dataroot_exist > $SYNOPKG_TEMP_LOGFILE
			exit 1
		fi
	fi
}

CreateDatabase() {
	pkgwizard_mysql_password=$(ParsePassword $pkgwizard_mysql_password)
	$MYSQL -u root --password="$pkgwizard_mysql_password" -e "CREATE DATABASE if not exists $pkgwizard_db_name DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci"
	if [ $? -eq "1" ]; then
		echo $md_mysql_password_error > $SYNOPKG_TEMP_LOGFILE
		exit 1;
	fi
}

CheckBeforeInstall
CreateDatabase
CreateSharedFolder

exit 0
