#!/bin/bash

cd entities_logger

# Database settings
MYSQL_HOST="localhost"
MYSQL_PORT=3306
MYSQL_ADMIN="root"

# DB name that will be created for DB user
DB_DATABASE=entities_logger
DB_USERNAME=entities-logger

genpasswd() {
	local l=$1
	[ "$l" == "" ] && l=16
	tr -dc A-Za-z0-9_!:\- < /dev/urandom | head -c ${l} | xargs
}

initMySQL() {
	echo "Going to create MySQL database & user privileges to it .."
	read -p "Please enter password for new user (leave empty to generate): " DB_PASSWORD
	if test -z "$DB_PASSWORD"; then
		DB_PASSWORD=`genpasswd`
		echo "Generated '$DB_PASSWORD'"
	fi
	echo
	echo "Now you will be prompted for '$MYSQL_ADMIN' password into your mysql ..."

	# Create database, user & his privileges that the IS will use to communicate with the DB
	mysql -h "$MYSQL_HOST" -P "$MYSQL_PORT" -u"$MYSQL_ADMIN" -p <<EOF
		DROP DATABASE IF EXISTS \`$DB_DATABASE\`;
		DROP USER IF EXISTS \`$DB_USERNAME\`@'$MYSQL_HOST';

		CREATE SCHEMA IF NOT EXISTS \`$DB_DATABASE\` DEFAULT CHARACTER SET utf8;
		CREATE USER IF NOT EXISTS '$DB_USERNAME'@'$MYSQL_HOST' IDENTIFIED BY '$DB_PASSWORD';
		GRANT ALL PRIVILEGES ON $DB_DATABASE.* TO '$DB_USERNAME'@'$MYSQL_HOST';
		FLUSH PRIVILEGES;
EOF

	if test $? -eq 0; then
		echo "MySQL DB initialization done!"
	else
		echo "MySQL DB initialization failed!" >&2
		echo "Maybe bad password?" >&2
		exit 2
	fi
}

setEnv() {
	KEY="$1"
	VAL="$2"
	echo "Setting $KEY to '$VAL' in .env"
	sed -i "s,\\($KEY=\\).*,\1$VAL,g" ".env"
}

propagateDbSettings() {

	if test ! -f .env; then
		cp .env.example .env
	fi

	setEnv DB_HOST "$MYSQL_HOST"
	setEnv DB_PORT "$MYSQL_PORT"
	setEnv DB_DATABASE "$DB_DATABASE"
	setEnv DB_USERNAME "$DB_USERNAME"
	setEnv DB_PASSWORD "$DB_PASSWORD"

}

checkPhpVersion() {
	php --version | head -n 1 | grep -o "^PHP 7" &>/dev/null

	if test $? -ne 0; then
		echo "PHP must run in version 7 & higher, sorry .." >&2
		exit 3
	fi
}

fillDatabase() {

	php artisan key:generate
	php artisan migrate:refresh
	php artisan db:seed
}

runCmd() {
	echo "Running UNIX command '$CMD' ..."
	RESULT=`eval $CMD`
	if test ! -z "$RESULT"; then
		echo "$RESULT"
	fi
}

addServerOwnership() {
	CMD="sudo chown www-data:$USER storage/ bootstrap/cache -R"
	runCmd

	CMD="sudo chmod g+w storage/ bootstrap/cache -R"
	runCmd
}

run() {
	checkPhpVersion
	initMySQL
	propagateDbSettings
	#addServerOwnership
	fillDatabase
}

run "$@"
exit $?
