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

. "$(dirname $0)"/common

DB_HOST="$DOCKER_HOST"
DB_USER="$PKG_SHORT"
API=/usr/syno/bin/synowebapi
SIZE=245

if [ "$SYNOPKG_PKG_STATUS" != UPGRADE ]; then
	DB_NAME="$pkgwizard_db_name"
	DB_PASS="$(openssl rand -base64 48 | sed 's,/,_,g')"
	MARIADB_PASS="${pkgwizard_mysql_password:+-p$pkgwizard_mysql_password}"
	HTTP_PORT=$pkgwizard_http_port
	SHARE="$pkgwizard_dataroot"
	SQL="CREATE USER '$DB_USER'@'%' IDENTIFIED BY '$DB_PASS'; CREATE DATABASE IF NOT EXISTS \`$(echo "$DB_NAME" | quote_sql)\` DEFAULT CHARACTER SET \`utf8\` COLLATE \`utf8_unicode_ci\`; GRANT ALL PRIVILEGES ON \`$(echo "$DB_NAME" | quote_sql)\`.* TO '$DB_USER'@'%';"

	echo "$SQL" | mysql -uroot "$MARIADB_PASS"

	(
		echo HTTP_PORT="\"$(echo "$HTTP_PORT" | quote_sh)\""
		echo DB_NAME="\"$(echo "$DB_NAME" | quote_sh)\""
		echo DB_PASS="\"$(echo "$DB_PASS" | quote_sh)\""
		echo SHARE="\"$(echo "$SHARE" | quote_sh)\""
	) > "$ETC_PATH"/config
else
	. "$ETC_PATH"/config
fi

sed -i \
	-e "s/__HTTP_PORT__/$(echo "$HTTP_PORT" | quote_json | quote_sed)/g" \
	"$TARGET_PATH"/ui/config \
	"$PROFILE"
sed -i \
	-e "s/__SHARE__/$(echo "$SHARE" | quote_json | quote_sed)/g" \
	-e "s/__DB_HOST__/$(echo "$DB_HOST" | quote_sed | quote_json | quote_sed)/g" \
	-e "s/__DB_NAME__/$(echo "$DB_NAME" | quote_sed | quote_json | quote_sed)/g" \
	-e "s/__DB_USER__/$(echo "$DB_USER" | quote_sed | quote_json | quote_sed)/g" \
	-e "s/__DB_PASS__/$(echo "$DB_PASS" | quote_sed | quote_json | quote_sed)/g" \
	"$PROFILE"

/var/packages/Docker/target/tool/helper \
	sameersbn/redmine 3.3.1 "$TARGET_PATH"/docker/redmine-3.3.1.tar.xz $SIZE \
	|| exit 1

$API --exec api=SYNO.Docker.Container version=1 method=create is_run_instantly=false \
	profile="$(cat "$PROFILE")"

exit 0
