load_project(){

	USER=$(whoami)
	if [ $USER = "root" ] ;then
		[ "$#" = 0 ] && echo -e "Especifique um usuario." && return 1
		[ "$1" ] && _USER="$1"
	else
		_USER="$USER"
	fi

	EDIR11_ROOT="/home/${_USER}/edirectory"
	[ ! -d "${EDIR11_ROOT}" ] && read -p "Informe o caminho do edirectory: " EDIR11_ROOT
	_HOME="${EDIR11_ROOT%/edirectory}"
	export EDIR11_ROOT="${EDIR11_ROOT}"
	export CONFIG_INC="${EDIR11_ROOT}/web/conf/config.inc.php"
	export DOMAIN_INC="${EDIR11_ROOT}/web/custom/domain/domain.inc.php"
	export DOMAIN_YML="${EDIR11_ROOT}/app/config/domain.yml"
	export DIR_DOMAINS="${EDIR11_ROOT}/app/config/domains"
	export PARAMETERS_YML="${EDIR11_ROOT}/app/config/parameters.yml"
	export CONSTANTS_INC="${EDIR11_ROOT}/web/conf/constants.inc.php"
	export KERNEL_V="${EDIR11_ROOT}/src/ArcaSolutions/CoreBundle/Kernel/Kernel.php"
	export EDIR_VERSION="$(grep "const VERSION = " ${KERNEL_V} | awk -F\' '{print $2}')"
	export TMP_DIR="${_HOME}/tmp_upgrade"
	export LOG="${TMP_DIR}/fix_sitemgr.log"
	export DB_USER=$(grep -E "define\(\"_DIRECTORYDB_USER\"\," ${CONFIG_INC} | cut -f4 -d '"')
	export DB_PASS=$(grep -E "define\(\"_DIRECTORYDB_PASS\"\," ${CONFIG_INC} | cut -f4 -d '"')
	export DB_HOST=$(grep -E "define\(\"_DIRECTORYDB_HOST\"\," ${CONFIG_INC} | cut -f4 -d '"')
	export DB_MAIN=$(grep -E "define\(\"_DIRECTORYDB_NAME\"\," ${CONFIG_INC} | cut -f4 -d '"')
	export BD_TXT="${TMP_DIR}/bd.txt"
	export DOMAIN_1=$(cat $DOMAIN_INC | grep "= 1" | sed "s/\'/\"/g" | awk -F'"' '{print $2}')
	flag_load_project=1
	}

show_info(){
	[ "flag_load_project" != 1 ] && load_project

	echo -e "
	EDIR11_ROOT\t= ${EDIR11_ROOT}
	CONFIG_INC\t= ${CONFIG_INC}
	DOMAIN_INC\t= ${DOMAIN_INC}
	DOMAIN_YML\t= ${DOMAIN_YML}
	PARAMETERS_YML\t= ${PARAMETERS_YML}
	DIR_DOMAINS\t= ${DIR_DOMAINS}
	CONSTANTS_INC\t= ${CONSTANTS_INC}
	EDIR_VERSION\t= ${EDIR_VERSION}
	DB_USER\t\t= ${DB_USER}
	DB_PASS\t\t= ${DB_PASS}
	DB_HOST\t\t= ${DB_HOST}
	DB_MAIN\t\t= ${DB_MAIN}
	DOMAIN_1\t= ${DOMAIN_1}
	"
}

limpar_variaveis(){
  unset novo_id novo_dominio DB_DOMAINX
  unset PROJDOMAIN1 _USER PROJNAME EDIR11_ROOT
  unset DB_USER DB_PASS DB_NAME DB_NAME_PREFIX DB_MAIN DB_DOMAINS DB_DOMAIN1
  }

criar_bd(){
    [ -z "${TMP_DIR}" ] 	&& read -p "Variável TMP_DIR não definida."
    [ -z "${DOMAIN_INC}" ]	&& read -p "Variável DOMAIN_INC não definida."
    [ -z "${DB_USER}" ]		&& read -p "Variável DB_USER não definida."
    [ -z "${DB_HOST}" ]		&& read -p "Variável DB_HOST não definida."
    [ -z "${DB_PASS}" ]		&& read -p "Variável DB_PASS não definida."
    [ -z "${DB_MAIN}" ]		&& read -p "Variável DB_MAIN não definida."

    # Remove pasta temporária, caso exista e cria novamente
	    [ -n "${TMP_DIR}" ] && rm -rf $TMP_DIR
		[ "$?" != 0 ] && echo "Problema ao deletar diretório ${TMP_DIR}." && return 1
		[ ! -d "$TMP_DIR" ] && mkdir $TMP_DIR

    # Cria arquivo domains.txt limpo
        DOMAINS="$TMP_DIR/domains.txt"
        [[ ! -f $DOMAINS ]] && touch $DOMAINS

    # Cria arquivo db_domains.txt limpo
        DB_DOMAINS="$TMP_DIR/db_domains.txt"
        [[ ! -f $DB_DOMAINS ]] && touch $DB_DOMAINS

    # Alimenta arquivo domains.txt
        echo -e "Verificando dominios..."
        sed -i s/\'/\"/g $DOMAIN_INC
        grep -E "domainInfo\[" $DOMAIN_INC | cut -f2 -d '"' > $DOMAINS
        echo -e "Dominios encontrados:\n"
        cat -n $DOMAINS

    # Alimenta arquivo db_domains.txt
        echo -e "\nVerificando databases dos dominios..."
        mysql -h"$DB_HOST" -u"$DB_USER" -p"$DB_PASS" -e "use $DB_MAIN ; \
        select database_name from Domain;" | grep "domain" > $DB_DOMAINS
        echo -e "Databases encontradas:\n"
        cat -n $DB_DOMAINS
        echo ""

    # Alimenta o arquivo domains_staging.txt
        DOMAIN1=$(head -1 $DOMAINS)
        DB_DOMAIN1=$(head -1 $DB_DOMAINS)

        DOMAINS_STAGING="$TMP_DIR/domains_staging.txt"

        cp -f $DOMAINS $DOMAINS_STAGING
        for i in $(cat $DOMAINS)
           do
           sed -i "s/$i/$i-v11.arcastaging.com/g" $DOMAINS_STAGING
        done

        [[ ! -f $DOMAINS_STAGING ]] && echo -e "Problema, arquivo $DOMAINS_STAGING nao encontrado."

    # Cria o arquivo bd.txt vazio
        BD_TXT="$TMP_DIR/bd.txt"
        [[ -f $BD_TXT ]] && cat /dev/null > $BD_TXT
        [[ ! -f $BD_TXT ]] && touch $BD_TXT

    # Alimenta o arquivo bd.txt
        num_domain=$(cat $DOMAINS | wc -l)
        c=0

        for i in $(seq 1 $num_domain);
        do
            c=$((c+1))
        echo -e "$c:$(cat -n $DOMAINS | sed 's/[\ ]//g' | grep "^$i" | awk '{print $2}'):\
    $(cat -n $DOMAINS_STAGING | sed 's/[\ ]//g' | grep "^$i" | awk '{print $2}'):\
    $(cat -n $DB_DOMAINS | sed "s/^\ .* $i/$i/g" | grep "^$i" | awk '{print $2}')" >> $BD_TXT
        done
    	echo -e "Base de dados criada com sucesso."
    	cat $BD_TXT
    }

dump_databases(){
	#Dependencias:
	#-criar_bd

  [ -z "$_USER"     ]	&& read -p "Informe o usuario: " _USER && load_project "${_USER}"
  [ -z "${DB_USER}" ]   && read -p "Informe o usuario do MySQL: " DB_USER
  [ -z "${DB_PASS}" ]   && read -p "Informe a senha: " DB_PASS
  [ -z "${DB_HOST}" ]   && read -p "Informe o host: " DB_PASS

  [ ! -d "${_PATH}/export_databases" ] && echo -e "[!] Diretório export_databases não encontrado." && return 1

  criar_bd

  [ -z "${DB_DOMAIN1}" ]  && read -p "Informe o nome do banco domain1: " DB_DOMAIN1

  echo -e "\n[+] Exportando ${DB_MAIN}..."
  mysqldump -C -h"$DB_HOST" -u${DB_USER} -p${DB_PASS} ${DB_MAIN} > ${_EXPORT_DATABASES}/${DB_MAIN}.sql

  for domain in $(cat ${DB_DOMAINS}); do
    echo -e "[+] Exportando ${domain}..."
    mysqldump -C  -h"$DB_HOST" -u${DB_USER} -p${DB_PASS} ${domain} > ${_EXPORT_DATABASES}/${domain}.sql
    [ "$?" != 0 ] && echo -e "[!] Problema na exportação." && return 1
  done
  }

backup_edirectory(){
	#Dependencias:
	#-load_project
	#-dump_databases
	#-limpar_variaveis

    [ -z "$_USER" ] && read -p "Informe o usuario: " _USER
    load_project "${_USER}"
    [ -z "$EDIR11_ROOT" ] && read -p "Caminho do edirectory: " EDIR11_ROOT

    _PATH="${EDIR11_ROOT%/*}"
    _EXPORT_DATABASES="${_PATH}/export_databases"
    data_hoje=$(date +%Y-%m-%d)

    cd ${_PATH}
    [ ! -d "${EDIR11_ROOT}" ] && echo -e "[!] Diretório edirectory não encontrado." && return 1
    [ ! -d "${_EXPORT_DATABASES}" ] && mkdir ${_EXPORT_DATABASES}

    dump_databases
    ARQ_BACKUP="edir_${DOMAIN_1}_${EDIR_VERSION}.tar.gz"
    [ -f "${ARQ_BACKUP}" ] && rm -rf "${ARQ_BACKUP}"

    echo -e "[+] Compactando diretório edirectory + databases..."
    if [ -d "edirectory" ]; then
      tar zcf "${ARQ_BACKUP}" edirectory/ export_databases/
    else
      edirectory=$(echo ${EDIR11_ROOT} | sed 's/\//\ /g' | awk '{print $NF}')
      tar zcf "${ARQ_BACKUP}" $edirectory export_databases/
    fi

    [ "$?" == 0 ] && echo -e "[+] Removendo diretório temporário."
    rm -rf "${_EXPORT_DATABASES}"

    echo -e "[+] Arquivo criado: ${ARQ_BACKUP}"
    echo -e "[+] Backup concluído.\n"
    limpar_variaveis
    }
