#!/bin/bash

echo "Start configuration"
cat app/config/parameters.yml |grep database_user| awk -F ":" '{print $2}' >> name.txt
cat app/config/parameters.yml |grep database_password| awk -F ":" '{print $2}' >> database.txt

sed -i 's/     //gI' name.txt
sed -i 's/     //gI' database.txt

PROJECTNAME=`cat name.txt`
DATABASEPASS=`cat database.txt`

echo "Create mysql user"
mysql -u root -e "CREATE USER '$PROJECTNAME'@'%' IDENTIFIED BY '$DATABASEPASS';"
mysql -u root -e "GRANT ALL PRIVILEGES ON *.* TO '$PROJECTNAME'@'%';"
mysql -u root -e "CREATE USER '$PROJECTNAME'@'localhost' IDENTIFIED BY '$DATABASEPASS';"
mysql -u root -e "GRANT ALL PRIVILEGES ON *.* TO '$PROJECTNAME'@'localhost';"
mysql -u root -e "FLUSH PRIVILEGES;"

CREATEDOMAIN="create database "$PROJECTNAME"_domain_1;"
CREATEMAIN="create database "$PROJECTNAME"_main;"

echo "Create databases"
mysql -u $PROJECTNAME -p$DATABASEPASS -e "$CREATEDOMAIN"
mysql -u $PROJECTNAME -p$DATABASEPASS -e "$CREATEMAIN"

DBDOMAIN=""$PROJECTNAME"_domain_1"
DBMAIN=""$PROJECTNAME"_main"
SQLDOMAIN=""$PROJECTNAME"_domain_1.sql"
SQLMAIN=""$PROJECTNAME"_main.sql"

echo "Restore Databases using sql files"
mysql -u $PROJECTNAME -p$DATABASEPASS $DBDOMAIN < databases/$SQLDOMAIN
mysql -u $PROJECTNAME -p$DATABASEPASS $DBMAIN < databases/$SQLMAIN

rm -f name.txt
rm -f database.txt

echo "Databases created"

chmod -R 777 /var/lib/php/session/

echo "Permission for save php session done"

echo "If the elasticsearch are running in localhost is not necessary change the parameters.yml"

read -p "Your elasticsearch is running in localhost? (y/n) " ELASTIC 

if [ "$ELASTIC" = "y" ];
	then
		echo "Installation finished. Have a nice day!!!"
		exit 0
	else
		read -p "Would you like to use elasticsearch in Arca server hosted in DigitalOcean? (y/n) " DO 
		if [ "$DO" = "y" ];
			then
				echo "Update your parameters.yml"
				IP=`/sbin/ifconfig eth1 | grep 'inet end.:' | cut -d: -f2 | awk '{ print $1}'`
				sed -i 's/database_host.*/database_host:     '"$IP"'/gI' app/config/parameters.yml
				sed -i 's/elastic_host.*/elastic_host:     10.132.190.143/gI' app/config/parameters.yml
			else
				echo "For the user ElasticSearch on another server you must configure the parameters.yml file so that the service of elasticsearch can connect to the mysql service and mysql can connect to elasticsearch."
				echo "Installation finished. Have a nice day!!!"
				exit 0
		fi
fi 

echo "Installation finished. Have a nice day!!!"
exit 0



