#! /bin/bash
################################################################################
#
#	fix_permissoes - Rafael Carreiro
#
#       Ajustar permissoes para o projeto.
#
#-------------------------------------------------------------------------------
#
#               Histórico
#
#       v0.1    2016-09-20 - Rafael Carreiro:
#               Ajusta permissoes, apaga cache e recria indice do elastic
#
################################################################################

#Verifica usuario e define variaveis _USER e _DOMAIN
USER=$(whoami)
if [ $USER = "root" ] ;then
	[ "$#" = 0 ] && echo -e "Especifique um usuario." && exit 1
	[ "$1" ] && _USER="$1"
	_DOMAIN="$(grep "main_domain" /var/cpanel/userdata/$_USER/main | awk '{print $2}')"
else
	_USER="$USER"
	_DOMAIN="$(grep "main_domain" /var/cpanel/userdata/$_USER/main | awk '{print $2}')"
fi

[[ $2 == '-y' ]] && opt='y'
[[ $2 == '-n' ]] && opt='n'


# Configura permissoes para o usuario
echo -e "Limpando cache..."
rm -rf /home/$_USER/edirectory/cache
echo -e "\n\nFixando permissoes do usuario $_USER ..."
chown -R $_USER:$_USER /home/$_USER
chown -R $_USER:$_USER /home/$_USER/public_html
find /home/$_USER/edirectory -type d -exec chmod 755 {} \;

if [ -z $opt ]; then
	echo -e "Deseja recriar o indice do elastic? (y/n)"
	read opt
elif [ "$opt" == 'y' ];then
	:
elif [ "$opt" == 'n' ];then
	echo -e "Concluido.\n" && exit 0
fi

if [ "$opt" == "y" ] ; then 
	# Recria o indice
	php /home/$_USER/edirectory/app/console edirectory:sync -r --env=prod --domain=$_DOMAIN
	if [[ "$?" != 0 ]] ; then 
		echo -e "
		***

		Se ainda estiver com problema ou não conseguiu recriar o indice do elastic por timeout
		verifique se está setado como \"localhost\" no campo database_host da tabela Domain do banco 
		"$_USER"_main e nos arquivos edirectory/app/config/parameters.yml e edirectory/web/custom/conf/config.inc.php
		
		***
		"
	fi
fi
unset opt
echo -e "Limpando cache..."
rm -rf /home/$_USER/edirectory/cache
echo -e "Concluido."
