#!/bin/bash
#
# Univention samba backup
#  backup samba provision
#
# SPDX-FileCopyrightText: 2014-2025 Univention GmbH
# SPDX-License-Identifier: AGPL-3.0-only

. /usr/share/univention-lib/backup.sh
. /usr/share/univention-lib/base.sh

display_help() {
	cat <<-EOL
		univention-samba4-backup: backups the samba provision directory

		Syntax:
		    univention-samba4-backup [options]

		Options:
		    --help|-h			display this message
		    --where|-w <DIR>		backup directory
		    --days|-d <INT>		retention period in days
	EOL
}

terminate_on_error() {
	>&2 echo "$*"
	exit 1
}

WHERE=/var/univention-backup/samba
DAYS=""
WHEN="$(date +%Y-%m-%d)"

while [ $# -gt 0 ]; do
	case "$1" in
		# just for compatibility reasons
		"--from-where"|"-f")
			echo "Warning: --from-where|-f removed and ignored"
                        shift 2 || exit 2
			;;
		"--where"|"-w")
			WHERE="${2:?missing parameter for $1}"
			shift 2 || exit 2
			;;
		"--days"|"-d")
			DAYS="${2:?missing parameter for $1}"
			[ $DAYS -eq $DAYS ] 2>/dev/null
			if [ ! $? -eq 0 ]; then
				display_help
				exit 1
			fi
			shift 2 || exit 2
			;;
		"--help"|"-h"|"-?")
			display_help
			exit 0
			;;
		*)
			display_help
			exit 1
			;;
	esac
done

if [ ! -d $WHERE ]; then
	terminate_on_error "Missing backup directory $WHERE"
fi
install -o root -g root -m 700 -d "$WHERE"

umask 0026 # samba-tool updates private/sam.ldb.d/metadata.tdb
samba-tool domain backup offline --targetdir="$WHERE" || die "ERROR: samba-tool domain backup failed"
chmod 600 "$WHERE"/samba-backup-*.bz2
clean_old_backups 'samba/samba-backup-.*.bz2' "$DAYS"
