#!/bin/sh

# Script to backup nextcloud instance with borgbackup
# Reference: https://docs.nextcloud.com/server/stable/admin_manual/maintenance/backup.html

export BORG_REPO=borg@x-borg:#insert repo name
export BORG_PASSPHRASE='insert repo passsphrase here'

mysql_dump=0
if [ $mysql_dump -eq 1 ]
then
	MYSQL_SERVER='x-mariadb'
	MYSQL_PORT='3306'
	MYSQL_USER='insert user name'
	MYSQL_PASSWORD='insert user password'
	MYSQL_DB='insert db name'
	MYSQL_DUMP_PATH='/tmp/mysqldump.bak'
fi

global_exit=0
timestamp=$(date +%FT%T)

# some helpers and error handling:
info() { printf "\n%s %s\n\n" "$( date )" "$*" >&2; }
abort() 
{
	info "Finished Abort, $global_exit"
	exit $global_exit
}
trap 'echo $( date ) Backup interrupted >&2; global_exit=$(( 2 > global_exit ? 2 : global_exit )); abort' INT TERM



info "Starting backup process at $timestamp"

if [ $mysql_dump -eq 1 ]
then
    info "Dumping mysql database"
    mysqldump --single-transaction -h $MYSQL_SERVER --port $MYSQL_PORT -u $MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DB > $MYSQL_DUMP_PATH
    sqldump_exit=$?
    global_exit=$(( sqldump_exit > global_exit ? sqldump_exit : global_exit ))

    if [ ${global_exit} -eq 0 ]; then
        info "Done dumping mysql database, $sqldump_exit"
    else
        info "Failed to dump nextcloud database, $global_exit"
        abort
    fi
fi

info "Backing up data"

borg create                         \
    --verbose                       \
    --filter AME                    \
    --list                          \
    --stats                         \
    --show-rc                       \
    --compression zstd,22           \
    --exclude-caches                \
                                    \
    ::'{hostname}-data-'$timestamp  \
    'insert data path here'         \

backup_exit=$?
# use highest exit code as global exit code
global_exit=$(( backup_exit > global_exit ? backup_exit : global_exit ))

info "Data backup done, $backup_exit"




# Use the `prune` subcommand to maintain 7 daily, 4 weekly and 6 monthly
# archives of THIS machine. The '{hostname}-' prefix is very important to
# limit prune's operation to this machine's archives and not apply to
# other machines' archives also:

info "Prune data archives"

borg prune                          \
    --list                          \
    --prefix '{hostname}-data'      \
    --show-rc                       \
    --keep-daily    7               \
    --keep-weekly   4               \
    --keep-monthly  6               \

prune_exit=$?
global_exit=$(( prune_exit > global_exit ? prune_exit : global_exit ))

info "Done pruning data archives, $prune_exit"
if [ ${global_exit} -eq 0 ]; then
    info "Script finished successfully"
elif [ ${global_exit} -eq 1 ]; then
    info "Script finished with warnings"
else
    info "Script finished with errors"
fi



exit ${global_exit}
