#!/usr/bin/env bash
set -e -x

echo "#### START: " `date`

PG_EXEC=/usr/bin/psql
PG_EXEC_OPTIONS="-o /dev/null"
DB_NEW=openerp
VERSION=7.0
SOURCE_PATH=${HOME}/openerp

# Compute the right path for the server and the addons (all, official, web & custom)
OPENERP_SERVER_PATH=${SOURCE_PATH}/server
OPENERP_FILESTORE_PATH=${OPENERP_SERVER_PATH}/bin/filestore/${DB_NEW}
OPENERP_WEB_PATH=${SOURCE_PATH}/web
OPENERP_CUSTOM_PATH=${SOURCE_PATH}/custom

OPENERP_WEB_ADDONS_PATH=${OPENERP_WEB_PATH}/addons
OPENERP_CUSTOM_ADDONS_PATH=$OPENERP_CUSTOM_PATH

OPENERP_ADDONS_PATH=${SOURCE_PATH}/addons

DATE=`date +'%s'`

BACKUP=${SOURCE_PATH}/openerp_last.dump.sql.gz
DB_TMP=_${DB_NEW}_${DATE}

OPENERP_ADDONS_PATH=${OPENERP_ADDONS_PATH},${OPENERP_WEB_ADDONS_PATH},${OPENERP_CUSTOM_ADDONS_PATH},${OPENERP_CUSTOM_ADDONS_PATH}/test

OPENERP_PID_FILE=${SOURCE_PATH}/test_openerp.pid
OPENERP_ARGUMENTS="--log-level=debug --logfile=${HOME}/log/openerp.log  --addons-path=${OPENERP_ADDONS_PATH} --no-xmlrpcs --no-netrpc --xmlrpc-port=8369 --pidfile=${OPENERP_PID_FILE} --smtp=localhost --smtp-port=1025 --proxy-mode"

${PG_EXEC} -d postgres -c "DROP DATABASE IF EXISTS ${DB_TMP};"
${PG_EXEC} -d postgres -c "CREATE DATABASE ${DB_TMP};"

#mkdir -p ${OPENERP_FILESTORE_PATH}
rsync -e 'ssh -i /home/odoo/config/rsnapshot_id_rsa' -rtvz --delete --progress root@openerp.my.openerp.com:/home/odoo/backup/openerp_last.dump.sql.gz ${BACKUP}
rsync -e 'ssh -i /home/odoo/config/rsnapshot_id_rsa' -rtHvz --delete --progress root@openerp.my.openerp.com:/home/odoo/filestore/  /home/accounts/filestore/

zcat ${BACKUP} | time ${PG_EXEC} ${PG_EXEC_OPTIONS} -d ${DB_TMP}

# hack: the server need to know about the module... (update module list is only called if we update/install base module)
psql -d $DB_TMP -c "insert into ir_module_module(name,state) values('openerp_enterprise_test', 'to install')"
$OPENERP_SERVER_PATH/openerp-server $OPENERP_ARGUMENTS -d $DB_TMP -i openerp_enterprise_test --stop-after-init

# Update the path of the filestore, we don't use the original filestore
# !!! TODO use symlinks to use the same as prod
${PG_EXEC} -d ${DB_TMP} -c "UPDATE document_storage SET path='${OPENERP_FILESTORE_PATH}';"


if [ -f "${OPENERP_PID_FILE}" ]; then
    kill -9 `cat ${OPENERP_PID_FILE}`
    rm -f ${OPENERP_PID_FILE}
fi

${PG_EXEC} -d postgres -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '${DB_NEW}' and pid != pg_backend_pid();"
${PG_EXEC} -d postgres -c "DROP DATABASE IF EXISTS ${DB_NEW};"
${PG_EXEC} -d postgres -c "ALTER DATABASE ${DB_TMP} RENAME TO ${DB_NEW};"

OPENERP_CMD="./openerp-server ${OPENERP_ARGUMENTS} -d ${DB_NEW}"
(cd $OPENERP_SERVER_PATH && nohup ${OPENERP_CMD} --db-filter='openerp.*' &)


echo "#### END: " `date`
