#!/bin/bash

# Bash script on Domoticz server that will backup its database to a 
# local machine (mDns host name: backserver.local) as a compressed
# file:  /home/becky/DomoticzBackups/domoticz-20200528-1342.db.gz

# Local SFTP server parameters, must be set correctly
#
SERVER="backserver.local"       # could be IP address
USERNAME="becky"               
PASSWORD="xxxxxxxx"               
DESTDIR="~/DomoticzBackups/"    # trailing "/" necessary

# Domoticz parameters
#
HOST="goldserver.local"         # or explicit IP address ok; "127.0.0.1" and "localhost" may not work
DOMOTICZ_PORT="8080"            # default HTTP port, could be different

# Create timestamped backup files
#
TIMESTAMP=`/bin/date +%Y%m%d-%H%M`
BACKUPFILE="domoticz-$TIMESTAMP.db" # backups will be named something like "domoticz-20200622-1042.db.gz"
BACKUPFILEGZ="$BACKUPFILE".gz

# Ask Domoticz to backup the database
#
curl -s http://$HOST:$DOMOTICZ_PORT/backupdatabase.php > /tmp/$BACKUPFILE
curlerr=$?

# Stop if this did not work, logging error
#
if [ $curlerr -ne 0 ]; then
  logger -p err "Domoticz backup database not created (error: $curlerr)"
  exit 1
fi

# Compress the database
#
gzip -9 /tmp/$BACKUPFILE

# and upload it
#
curl -k  -u "$USERNAME:$PASSWORD" -T "/tmp/$BACKUPFILEGZ" "sftp://$SERVER/$DESTDIR" 
curlerr=$?

# delete the backup up data base
#
/bin/rm /tmp/$BACKUPFILEGZ

# log error if one has occured
#
if [ $curlerr -ne 0 ]; then
  logger -p err "Domoticz database not backed up (error: $curlerr)"
  exit 2
fi

# date of last backup
#
echo $TIMESTAMP > ~/domoticz/backup.stamp
