#! /bin/bash
#
# nextcloud.sh
# Backup script for Nextcloud. Meant to be sourced by our main backup script
# Copyright (C) 2020 Vintage Salt <rehashedsalt@cock.li>
#
# Distributed under terms of the MIT license.
#

set -e

export OUTDIR="$BACKUPSDIR/{{ nextcloud_url }}"
retention=5 # 5-day retention period

# Sanity checks
if [ -z "$BACKUPSDIR" ]; then
	log "BACKUPSDIR was undefined. Run the main backup script instead of this one."
	return 1
fi
if ! [ -d "$OUTDIR" ]; then
	if ! mkdir "$OUTDIR"; then
		log "Unable to find or create output directory: $OUTDIR"
		return 2
	fi
fi
# Enforce permissions on our output directory since the git user will need them
chown root.git "$OUTDIR"
chmod 770 "$OUTDIR"

# Purge oldest backup if we need to
currentbackupcount="$(ls -1 "$OUTDIR" | wc -l)"
# Multiplying by three here because our backups are three-parters
if (( currentbackupcount >= retention * 3 )); then
	lastbackup="$(find "$OUTDIR" -name \*.tar.gz 2>/dev/null | sort | head -n 1)"
	lastbackup="${lastbackup%-*.gz}"
	if [ -f "$file" ]; then
		log "Removing old backups for: $lastbackup"
		for file in "$lastbackup"*; do
			log "Removing old backup part: $file"
			rm "$file"
		done
	fi
fi
# WE MAKE BACKUP NOW SERGEI
if cd "{{ nextcloud_webroot }}"; then
	log "Enabling maintenance mode"
	sudo -u www-data ./occ maintenance:mode --on > /dev/null 2>&1
	trap 'sudo -u www-data ./occ maintenance:mode --off' EXIT
	date="$(date -Iseconds)"
	log "Creating data backup"
	tar czhf "$OUTDIR/{{ nextcloud_url }}-$date-data.tar.gz" "/var/nextcloud" --exclude "/var/nextcloud/*/files_trashbin"
	log "Creating webroot backup"
	tar czf "$OUTDIR/{{ nextcloud_url }}-$date-webroot.tar.gz" "{{ nextcloud_webroot }}"
	log "Creating DB backup"
	mysqldump nextcloud --single-transaction | gzip > "$OUTDIR/{{ nextcloud_url }}-$date-db.sql.gz"
	log "Unsetting maintenance mode"
	sudo -u www-data ./occ maintenance:mode --off > /dev/null 2>&1
	trap : EXIT
else
	log "Could not change directory: $OUTDIR"
	return 3
fi