#!/bin/bash

CONTROLLER=unifi.swallow-grue.ts.net
TARGETPATH=/mnt/backup/unifi/udm
LOGPATH=/var/log/udm

NOW=$(date +"%Y-%m-%d_%H-%M-%S")
DATUM=$(date +"%Y-%m-%d")
STARTTIME=$(date +"%H:%M:%S")
CERT=~/.ssh/id_rsa
REMOTEUSER=root
BACKUPPATH=/data/unifi/data/backup/autobackup/
FIRMWAREPATH=/srv/unifi/data/firmware
CONFIGFILE=/srv/unifi/data/sites/default/config.gateway.json
LOGFILE=${NOW}_LogFile.log
LOGGING=${LOGPATH}/${LOGFILE}
STOREPATH=

echo Variables:
echo LogFile: ___________ $LOGGING
echo CertFile: __________ $CERT
echo CloudKey-User: _____ $REMOTEUSER
echo Controller: ________ $CONTROLLER
echo Backup-Source: _____ $BACKUPPATH
echo Firmware-Path: _____ $FIRMWAREPATH
echo Config-File: _______ $CONFIGFILE
echo Store-Path: ________ $TARGETPATH
echo " "

([ -d $LOGPATH ] || (echo "Folder ${LOGPATH} doesn't exists." && mkdir -p $LOGPATH && echo "Folder ${LOGPATH} created."))
([ -d $TARGETPATH ] || (echo "Folder $TARGETPATH doesn't exists." && mkdir -p $TARGETPATH && echo "Folder $TARGETPATH created."))
echo "Backup started on $DATUM at $STARTTIME."
echo "Backup started on $DATUM at $STARTTIME." > $LOGGING
echo ""
echo "Copy $BACKUPPATH from $CONTROLLER to $STOREPATH/$TARGETPATH."
echo "" >> $LOGGING
echo "Copy $BACKUPPATH from $CONTROLLER to $STOREPATH/$TARGETPATH." >> $LOGGING

rsync -rvhP $REMOTEUSER@$CONTROLLER:$BACKUPPATH $TARGETPATH 2>&1 >> $LOGGING
# scp -prvi $CERT $REMOTEUSER@$CONTROLLER:$BACKUPPATH $TARGETPATH 2>&1 >> $LOGGING
scpbackup=$?
if [ $scpbackup -eq 0 ]; then
    echo "    Done."
    echo "Done." >> $LOGGING
else
    echo "    Error!"
    echo "Error!" >> $LOGGING
fi
# remove eXecute from all autobackup_*-files
find $TARGETPATH -type f -name autobackup_* -exec chmod -x {} \;
ENDTIME=$(date +"%H:%M:%S")
echo ""
echo "Backup finished on $DATUM at $ENDTIME."
echo "" >> $LOGGING
echo "Backup finished on $DATUM at $ENDTIME." >> $LOGGING
grep "volume1/homes" $LOGGING > /dev/null 2>&1
modifylog=$?
echo $modifylog
if [ $modifylog -eq 0 ]; then
    echo "" >> $LOGGING && echo "Script has been executed by Synology task manager." >> $LOGGING
fi