#!/bin/sh
#
# Copyright (C) Matthieu Patou <mat@matws.net> 2010-2011
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Revised 2013-09-25, Brian Martin, as follows:
#    - Allow retention period ("DAYS") to be specified as a parameter.
#    - Allow individual positional parameters to be left at the default
#      by specifying "-"
#    - Use IS0 8601 standard dates (yyyy-mm-dd instead of mmddyyyy).
#    - Display tar exit codes when reporting errors.
#    - Don't send error messages to /dev/null, so we know what failed.
#    - Suppress useless tar "socket ignored" message.
#    - Fix retention period bug when deleting old backups ($DAYS variable
#      could be set, but was ignored).
#
# Revised 2019-06-30, Rohhie, as follows:
# Caution: Use at your own risk, Because the test is insufficient.
#    - Removed the FROMWARE parameter and added variables to specify 
#      3 directories.
#    - Backup TDB files. However, netlogon_creds_cli.tdb is excluded.
#    - Added --xattrs parameter to tar command.
#    - Included the information of ACLs as acl.txt in the backup.
#      However, this file can not be used to restore ACLs.
#
# Revised 2022-08-24, Rohhie, as follows:
# Caution: Use at your own risk, Because the test is insufficient.
#    - Removed previously added process of adding acl.txt.
#    - Added process to create command list to set NTACL.

PROV_ETC=/etc/samba
PROV_PRV=/var/lib/samba/private
PROV_SVL=/var/lib/samba/sysvol
WHERE=/var/backup
DAYS=90				# Set default retention period.

if [ -n "$1" ] && [ "$1" = "-h" -o "$1" = "--usage" ]; then
	echo "samba_backup [destinationdir] [retpd]"
	echo "Will backup your provision located in provisiondir to archive stored"
	echo "in destinationdir for retpd days. Use - to leave an option unchanged."
	echo "Default destinationi dir: $WHERE"
	echo "Default retention period: $DAYS"
	exit 0
fi

[ -n "$1" -a "$1" != "-" ]&&WHERE=$1		# Use parm or default if "-".  Validate later.
[ -n "$2" -a "$2" -eq "$2" 2> /dev/null ]&&DAYS=$2	# Use parm or default if non-numeric (incl "-").

if [ "$1" = "." ]; then
	WHERE=`pwd`
fi

#Number of days to keep the backup
WHEN=`date +%Y-%m-%d`	# ISO 8601 standard date.

if [ ! -d $PROV_ETC ]; then
	echo "Missing or wrong provision directory $PROV_ETC"
	exit 1
fi

if [ ! -d $PROV_PRV ]; then
	echo "Missing or wrong provision directory $PROV_PRV"
	exit 1
fi

if [ ! -d $PROV_SVL ]; then
	echo "Missing or wrong provision directory $PROV_SVL"
	exit 1
fi

if [ ! -d $WHERE ]; then
	echo "Missing backup directory $WHERE"
	exit 1
fi

# Run the backup.
#    --warning=no-file-ignored set to suppress "socket ignored" messages.
#    --xattrs set to support extended attributes.
run_the_backup() {
	targetdir=$1
	n=${targetdir##*/}	# basename
	cd ${targetdir%/*}	# dirname

	case "$n" in
		"sysvol")
			# Generate commands to add extended attributes to files and directories.
			find ./$n -exec bash -c 'TMP=$(samba-tool ntacl get "{}" --as-sddl); echo "samba-tool ntacl set \"$TMP\" \"{}\""' \; > NTACL
			mv NTACL $n
			tar cjf ${WHERE}/samba4_${n}.${WHEN}.tar.bz2 $n --xattrs --warning=no-file-ignored
			Status=$?	# Preserve $? for message, since [ alters it.
			rm $n/NTACL
			;;
		"private")
			tar cjf ${WHERE}/samba4_${n}.${WHEN}.tar.bz2 --exclude=\*\.\[lt\]db $n --xattrs --warning=no-file-ignored --transform 's/\(.[l,t]db\).bak$/\1/'
			Status=$?	# Preserve $? for message, since [ alters it.
			;;
		*)
			tar cjf ${WHERE}/samba4_${n}.${WHEN}.tar.bz2 $n --xattrs --warning=no-file-ignored
			Status=$?	# Preserve $? for message, since [ alters it.
	esac

	if [ $Status -ne 0 ]; then
		echo "Error while archiving ${WHERE}/${n}.${WHEN}.tar.bz2 - status = $Status"
		return $Status
	fi

	return 0
}

# Backup "etc"
#
run_the_backup $PROV_ETC
if [ $? -ne 0 ]; then
	exit 1
fi

# Backup "private"
#
find $PROV_PRV -name "*.[lt]db.bak" -exec rm {} \;

for ldb in `find $PROV_PRV -name "*.[lt]db"`; do
	if [ "${ldb##*/}" = "netlogon_creds_cli.tdb" ]; then
		continue
	fi
	tdbbackup $ldb
	Status=$?   # Preserve $? for message, since [ alters it.
	if [ $Status -ne 0 ]; then
		echo "Error while backing up $ldb - status $Status"
		exit 1
	fi
done

run_the_backup $PROV_PRV
if [ $? -ne 0 ]; then
	exit 1
fi

find $PROV_PRV -name "*.[lt]db.bak" -exec rm {} \;

# Backup "sysvol"
#
run_the_backup $PROV_SVL
if [ $? -ne 0 ]; then
	exit 1
fi

# Remove old backup file.
#
find $WHERE -name "samba4_*bz2" -mtime +$DAYS -exec rm {} \;
