#!/bin/bash

# defaults
start=$(date +%s)
DATE=$(date +%F)
TARGETFILE_DB="oxid_db_staging.sql.gz"
CHECK_MARK="\033[0;32m\xE2\x9C\x94\033[0m"
SCRIPTDIR=$(dirname "$0")

cd $SCRIPTDIR

ENV=$(printenv OXID_ENV)
CONFIG="$SCRIPTDIR/../../configurations/$ENV/.config"

if test -f "$CONFIG"; then
  source $CONFIG
else
  echo "No config found. Exiting... $CONFIG ¯\_(ツ)_/¯"
  exit 1
fi

# create dump of pimcore db
echo -n "Exporting database..."
OXID_TABLES="ddmedia molliepaymentconfig   mollierequestlog    oxacceptedterms     oxaccessoire2article  oxactions    oxactions2article    oxactions_set1 oxaddress    oxadminlog   oxartextends  oxartextends_set1    oxarticles   oxarticles2shop     oxarticles_set1     oxattribute   oxattribute2shop    oxattribute_set1    oxbenefit    oxcategories  oxcategories2shop    oxcategories_set1    oxcategory2attribute  oxcontents   oxcontents_set1     oxcounters   oxcountry    oxcountry_set1 oxdel2delset  oxdelivery   oxdelivery2shop     oxdelivery_set1     oxdeliveryset  oxdeliveryset2shop   oxdeliveryset_set1   oxdiscount   oxdiscount2shop     oxdiscount_set1     oxfield2role  oxfield2shop  oxfield2shop_set1    oxfiles     oxgroups    oxgroups_set1  oxlinks     oxlinks2shop  oxlinks_set1  oxmanufacturers     oxmanufacturers2shop  oxmanufacturers_set1  oxmediaurls   oxmediaurls_set1    oxnews oxnews2shop   oxnews_set1   oxnewsletter  oxnewssubscribed    oxobject2action     oxobject2article    oxobject2attribute   oxobject2attribute_set1     oxobject2benefit    oxobject2category    oxobject2delivery    oxobject2discount    oxobject2group oxobject2list  oxobject2payment    oxobject2role  oxobject2selectlist   oxobject2seodata    oxobjectrights oxpayments   oxpayments_set1     oxprice2article     oxpricealarm  oxratings    oxrecommlists  oxremark    oxreviews    oxrolefields  oxroles     oxselectlist  oxselectlist2shop    oxselectlist_set1    oxshops     oxshops_set1  oxstates    oxstates_set1  oxtplblocks   oxtranslation  oxvendor    oxvendor2shop  oxvendor_set1  oxvouchers   oxvoucherseries     oxvoucherseries2shop  oxwrapping   oxwrapping2shop     oxwrapping_set1" 
mysqldump --host=$MYSQLHOST --user=$MYSQLUSER --password=$MYSQLPASS --add-drop-table --no-data --quick --opt --max_allowed_packet=1000000000 $MYSQLDB $OXID_TABLES | grep -v "50013 DEFINER"| gzip > $TARGETFILE_DB
mysqldump --host=$MYSQLHOST --user=$MYSQLUSER --password=$MYSQLPASS --no-create-info --quick --opt --max_allowed_packet=1000000000 $MYSQLDB $OXID_TABLES | grep -v "50013 DEFINER"| gzip >> $TARGETFILE_DB
SQLSTATUS=$?

if [ $SQLSTATUS -eq 0 ]; then
  echo -e "\\r${CHECK_MARK} Exporting database... DONE"
else
  echo -e "Exporting database... FAILED"
  exit 1
fi

echo -n "moving dump and to exchange Folder"
mv $TARGETFILE_DB /var/www/dump

end=$(date +%s)
executiontime=$((end-start))

echo "Oxid database successfully exported to dump directory (took $executiontime seconds)"
