#!/bin/bash

# disabled mail send by default because mails got too big for indivia's smtp

if [ "$1" == "help" -o "$1" == "-h" -o "$1" == "--help" ]; then
	echo "backup.bash [mail|testmail|help/--help/-h]"
	exit 0
fi

mailcfgfp="../../conf/mail.conf"
mastcfgfp="../../conf/mustard.ini"

basedir=`dirname "$0"`
cd "$basedir"

function isok {
	if [ $? -eq 0 ]; then
		echo "ok :-)"
	else
		echo "qualcosa è andato storto, muoio :-("
		exit $?
	fi
}

date=`date`

mailmta=`cat "$mailcfgfp"|grep -P '^mta='|sed -e 's/^mta=//' -e 's/^"//' -e 's/"$//'`
mailfrom=`cat "$mailcfgfp"|grep -P '^from='|sed -e 's/^from=//' -e 's/^"//' -e 's/"$//'`
mailto=`cat "$mailcfgfp"|grep -P '^to='|sed -e 's/^to=//' -e 's/^"//' -e 's/"$//'`

if [ "$1" != "testmail" ]; then
	dbname=`cat "$mastcfgfp"|grep -P '^db_name='|sed -e 's/^db_name=//' -e 's/^"//' -e 's/"$//'`
	dbuser=`cat "$mastcfgfp"|grep -P '^db_admin_name='|sed -e 's/^db_admin_name=//' -e 's/^"//' -e 's/"$//'`
	dbpass=`cat "$mastcfgfp"|grep -P '^db_admin_password='|sed -e 's/^db_admin_password=//' -e 's/^"//' -e 's/"$//'`
	ofp=backups/"$dbname"_backup-`date +%Y-%m-%d--%H.%M.%S`.sql
	echo -n "Eseguo il dump... "
	mysqldump -u "$dbuser" -p"$dbpass" "$dbname" -r "$ofp"
	isok
else
	ofp=backups/test.data
	[ -e "${ofp}.xz" ] && rm "${ofp}.xz"
	echo -n "Creo il finto file di dump da allegare per test... "
	dd if=/dev/urandom of="$ofp" bs=1024 count=1024 &>/dev/null
	isok
fi
echo -n "Comprimo il dump... "
xz -9 "$ofp"
isok
if [ "$1" == "mail" -o "$1" == "testmail" ]; then
	echo -n "Invio il dump... "
	echo "Ecco il backup del database di mastodon.help di $date." | s-nail -s "Backup del database di mastodon.help di $date" -a "${ofp}.xz" -S v15-compat -S from="$mailfrom" -S smtp-use-starttls -S mta="$mailmta" "$mailto"
	isok
	[ "$1" == "testmail" -a -e "${ofp}.xz" ] && rm "${ofp}.xz"
fi
exit 0
