#!/bin/bash

alias mv=mv

PATH=$PATH:/usr/local/pd-admin2/bin

DUMPPATH=/home/mysqldump-for-upgrade/

DATABASES="vadmin roundcubemail"

MYSQLPASS=`cat /opt/pdadmin/etc/mysql_rootpw.conf`
if [ "$MYSQLPASS" == "" ]; then
   MYSQLPASS=`cat /etc/admin/mysql_rootpw`
fi

mkdir -p $DUMPPATH
chmod 700 $DUMPPATH

rm $DUMPPATH/*

for i in $DATABASES
do
 T=`date +%s`
 i=`echo $i | sed "s/.*\///"`
 if [ ! -e /etc/backup.conf/dont_dump_$i ]; then
   if [ ! -e /etc/backup.conf/dont_lock_$i ] && [ ! -e /etc/backup.conf/dont_lock ] ; then
      mysqldump --allow-keywords \
                --add-drop-table \
                --hex-blob \
                --default-character-set=utf8 \
                --opt \
                --flush-logs \
                --max_allowed_packet=16M \
                --quote-names \
                -u root -p$MYSQLPASS $i 2>/root/mysql_fehler.txt > $DUMPPATH/$i.$T
    else 
      false
    fi

    if [ $? -ne 0 ]; then
      # Text ohne LOCK
        mysqldump --allow-keywords \
                  --add-drop-table \
                  --create-options \
                  --quick \
                  --hex-blob \
                  --extended-insert \
                  --disable-keys \
                  --default-character-set=utf8 \
                  --skip-opt \
                  --flush-logs \
                  --max_allowed_packet=16M \
                  --quote-names \
                  -u root -p$MYSQLPASS $i 2>/root/mysql_fehler.txt > $DUMPPATH/$i.$T
     fi

     if [ $? -ne 0 ]; then
        cat /root/mysql_fehler.txt | mail -s "`hostname -f`: Cannot dump $i" sysadm@providerdienste.de
     else
        mv $DUMPPATH/$i.$T $DUMPPATH/$i
     fi

   fi
done

for i in $(ls -1d /home/mysql/usrdb* | cut -d_ -f2 | sort -u); do

    DATABASES=$(cd /home/mysql && ls -1d usrdb_$i*)
    echo $i
    echo "--------------------"
    echo $DATABASES


      mysqldump --allow-keywords \
                --add-drop-table \
                --hex-blob \
                --default-character-set=utf8 \
                --opt \
                --flush-logs \
                --max_allowed_packet=64M \
                --quote-names \
                -u root -p$MYSQLPASS --databases $DATABASES 2>/root/mysql_fehler.txt > $DUMPPATH/$i.$T

     if [ $? -ne 0 ]; then
        cat /root/mysql_fehler.txt | mail -s "`hostname -f`: Cannot dump $i" sysadm@providerdienste.de
     else
        mv $DUMPPATH/$i.$T $DUMPPATH/$i
     fi

done
